Functions in C/C++ - examples
1. Replacement of the position
2. Is the number simple?
3. Printing the array
4. Extracting even elements of an array
5. Number of repetitions of a certain character
6. Daily earnings
Example:
Input:
12_2_2021 2045.33
23_8_2021 1034.66
15_4_2021 1567.99
Output:
Array 1:
12.02.2021
23.08.2021
15.04.2021
Array 2:
2045.31
1034.66
1567.99
7. Login
Example:
Input:
Enter your username and password:
"Tot"
"user1"
Re-enter incorrect password
"admin"
"user"
Exit:
The user is successfully logged in
8. Daily earnings
Example:
Input:
12_2_2021 2045.33
23_8_2021 1034.66
15_4_2021 1567.99
Output:
Array1:
12.02.2021
23.08.2021
15.04.2021
Array2:
2045.31
1034.66
1567.99
9. Login
Example:
Input:
Enter your username and password:
"Mika"
"user1"
Re-enter incorrect password
"admin"
"user"
Output:
The user is successfully logged in
10. Determination of the maximum
Enter two integers and determine their maximum using the previously defined function.
Create the function "maximum()", which receives two integers, a and b, as parameters, and then, inside the function, examine which of them is larger.
If "a" is greater, the function should return "a" as a return value, otherwise "b".
Inside the main function, enter two integers, then call the previously created maximum function to determine it. Print that value in the rest of the program.
/*Solution for C programming language*/
int maximum(int a, int b)
{
{
else
{
int main()
{
printf("a=?,b=?\n");
scanf("%d%d",&a,&b);
maxAB = maximum(a,b);
printf("Maximum is %d",maxAB);
return 0;
11. Determining whether a number is prime
Read more about prime numbers on the website: A prime numbers and factoring
/*Solution in the programming language C*/
int prime(int a)
{
if(a==1 || a==2){
int d=2;
while(d < a){
break;
d++;
int main()
{
printf("x=?\n");
scanf("%d",&x);
if(prime(x)){
else{
return 0;
12. Writing bits from left to right
Create a function "bits()", which receives an integer "a" as a parameter.
Inside the function, use a loop to create powers of 2, starting with 215, and then decrease the exponent through the cycles.
Check in each cycle, whether that power of two is less than the rest of the number, which is initially equal to the whole number "a" sent.
If yes, print 1 as bit, if not, print zero. Recalculate the remainder of the number that remains when we subtract the current power of 2 from the previous remainder.
In the main "main" function, call the previously created function to be executed.
/*Solution in the programming language C*/
int bits(int a)
{
for(int i = 15;i >= 0;i--){
if(a <= rem){
rem=rem % a; //a=4, rem =7%4=3; a=2, rem =3%2=1; a=1, rem =1%1=0
else{
printf("\n");
int main()
{
printf("x=?\n");
scanf("%d",&x);
bits(x);
return 0;
13. Rounding to K decimal places.
Enter three integers M,N and K. (eg 13,3,2)
Find the quotient M/N, (eg 13/3=4.333333), and choose double or float as the data type, in order to save the decimals.
Multiply the resulting number by 10K, and then convert that number into a whole number, so that it contains both the digits of the result and the digits that should be displayed after the decimal point (eg 433).
Extract the integer result from this number, by dividing by 10K, as well as the decimal part by looking for the remainder of the division by 10K.
Print the integer part first, then put "." and add the decimal part below.
/*Solution in programming language C*/
int main()
{
double resD;
printf("M=?,N=?,K=?\n");
scanf("%d%d%d",&M,&N,&K); //13,3,2
resD=(double)M/N; //4.333333
printf("res=%f\n",resD);
coef=(int)pow(10,K); //100
res=resD*coef; //433
resD=(double)res/coef; //4.3300000
printf("res=%g\n",resD);
int num,dec;
num=res/coef; //4
dec=res % coef; //33
printf("%d.%d\n",num,dec);
14. Combinatorics-Calculation of combinations.
for the given natural numbers n,k,p S=Cn k-Cn k+1 +..+(-1) p*Cn k+p,
according to the formula for calculating combinations
15. Bit in the given position.
16. Number in reverse order.
312 * 221 = 68952
213 * 122 = 25986
17. The closest number that satisfies the condition.
n+S(n)+S(S(n))+S(S(S(n)))+S(S(....S(n)....)=2003
17. Calculating the factorial of n.
Enter a number, e.g. 5. Call a separate function that computes the factorial and pass n as a parameter. Factorial function: Check if n == 0 and if so return 1 (because 0! = 1). Then compute the product in a loop, multiplying the running product by the loop variable i. Decrease the loop variable from n down to 1.
#include <stdio.h>
/* C solution (compilable in C89/C99 and newer) */
int factorial(int n)
{
int f;
if (n == 0)
{
return 1;
if (n < 0)
{
return -1; /* error indicator */
f = 1;
for (i = n; i > 0; i--)
{
return f;
int main(void)
{
printf("Enter an integer n: ");
if (scanf("%d", &n) != 1)
{
return 1;
if (n >= 0)
{
printf("Factorial is %d\n", f);
else
{
return 0;
#include <iostream>
/* C++ solution (compilable with modern C++ compilers) */
unsigned long long factorial(int n)
{
if (n < 0) return 0ULL; /* error indicator: returning 0 */
unsigned long long f = 1ULL;
for (int i = 1; i <= n; ++i)
{
return f;
int main()
{
std::cout << "Enter an integer n: ";<br>
if (!(std::cin >> n))
{
return 1;
if (n < 0)
{
return 0;
unsigned long long result = factorial(n);
std::cout << "Factorial is " << result << std::endl;
return 0;
Combined tasks with the use of functions
Task 1: Shift array elements to the left (rotation)
Write a function in C that shifts all elements of an array one position to the left (cyclic rotation). The function should modify the array in-place, and the last element should become the previously first element.
- Create a function
cycle_leftthat takes parametersint A[]andint n. - In the main function: read the size n, input n array elements, call
cycle_left, and then display the result using the helper functionprint_array. - Pay attention to edge cases: n <= 1 (array remains unchanged).
Short explanation of the task:
The goal is to demonstrate how an array can be modified directly in a function (by passing a pointer to the first element) and to understand a simple algorithmic operation of shifting elements (O(n) time complexity).
Task 2: Sorting an array using Bubble Sort
Write a C program that sorts an array of integers using the standard
Bubble Sort algorithm. Implement a function
bubble_sort that takes an array and its length and sorts the elements
in-place. In main, read the array size, input the elements,
call the sorting function, and display the result.
- Create a function
bubble_sort(int A[], int n). - Add a helper function
print_arrayto print the array. - Optimize Bubble Sort to terminate early if the array is already sorted (using a flag).
Short explanation of the task:
Bubble sort compares adjacent pairs and, if needed, swaps them so that the largest element “bubbles up” to the end in one iteration. Repeat the process until the array is sorted. The algorithm is simple to implement (and stable), but has a time complexity of O(n²).
#include <stdio.h> #include <stdlib.h> /* Helper function to print an array */ void print_array(int A[], int n) {printf("print_array:\n"); for (int i = 0; i < n; i++) {} /* Bubble sort (optimized version with early exit flag) */ void bubble_sort(int A[], int n) {printf("%d ", A[i]);} printf("\n");for (int pass = 0; pass < n - 1; pass++) {} int main() {int swapped = 0; for (int i = 0; i < n - pass - 1; i++) {}// If element at i is greater than the next one, swap if (A[i] > A[i + 1]) {} if (!swapped) {int temp = A[i]; A[i] = A[i + 1]; A[i + 1] = temp; swapped = 1;}// No swaps in this pass — array is already sorted break;}int n; // Read array size scanf("%d", &n); // Note: VLA (C99) is used. For older standards, use malloc. int arr[n]; for (int i = 0; i < n; i++) {}printf("Enter element %d of the array\n", (i + 1)); scanf("%d", &arr[i]);} // Sorting bubble_sort(arr, n); // Print sorted array print_array(arr, n); return 0;
Explanation of the solution
- Principle: Bubble sort compares adjacent elements and, by swapping the larger with the smaller, moves larger elements toward the end.
-
Optimization: We use a variable
swappedto terminate early if there were zero swaps in a full pass — meaning the array is already sorted. -
In-place: Sorting modifies the passed array directly (no extra memory needed except for temporary
temp). - Stability: Bubble sort is a stable algorithm — the relative order of equal elements is preserved.
-
Time complexity:
- Worst and average case: O(n²).
- Best case (already sorted, thanks to the flag): O(n).
-
Space: O(1) extra memory (only
tempand the flag). - C compatibility note: if you want portability to older C compilers, use malloc and free instead of VLA.
Extension (optional): Implement a version that sorts in descending order or one that returns the number of passes required to sort.
Task 3: Reverse an array
Write a program in C that implements a function to reverse the elements of an integer array in-place. The function should swap the elements so that the first becomes the last, the second becomes the second-to-last, and so on. In main, read the size of the array, input the elements, call the reverse function, and display the result.
- Create a function
reverse_array(int A[], int n)that modifies the array directly. - In main: read n, fill the array, call
reverse_array, and then print the array usingprint_array. - Pay attention to edge cases (n <= 1).
Short explanation of the task:
The goal is to demonstrate array manipulation using two indices (left/right) and swapping elements until they cross. The algorithm works in-place with O(1) extra memory and time complexity O(n).
#include <stdio.h> #include <stdlib.h> /* Helper function to print an array */ void print_array(int A[], int n) {printf("print_array:\n"); for (int i = 0; i < n; i++) {} /* Function that reverses an array 'in-place' using two pointers */ void reverse_array(int A[], int n) {printf("%d ", A[i]);} printf("\n");// If the array is empty or has one element, nothing to change if (n <= 1) {} int main() {return;} int left = 0; int right = n - 1; while (left < right) {int tmp = A[left]; A[left] = A[right]; A[right] = tmp; left++; right--;}int n; // Read the size of the array scanf("%d", &n); // Note: using VLA (C99). For older standards use malloc. int arr[n]; for (int i = 0; i < n; i++) {}printf("Enter element %d:\n", (i + 1)); scanf("%d", &arr[i]);} // Call the function that reverses the array reverse_array(arr, n); // Print the result print_array(arr, n); return 0;
Solution explanation
-
The function
reverse_arrayuses two indices: left starts from index 0, and right from the last element. -
In the while loop, as long as left < right, we swap the values at those positions using a temporary variable
tmp. Then we increment left++ and decrement right--. This guarantees that each pair is swapped exactly once. - The algorithm works in-place (no extra large buffers) and uses O(1) additional memory. Time complexity is O(n) because each element is swapped at most once.
-
Edge cases: if
n <= 1, the function immediately returns since no changes are needed. For very largen, consider using dynamic allocation instead of VLA for portability. - Advantages of this approach: simplicity, efficiency, and low memory usage. Useful when you need to quickly reverse the order of elements.
Extension (optional): Write a version that returns a newly allocated reversed array (does not modify the original),
or a generic function that reverses an array of type void* using a swap function (useful for other data types).
|
Previous
|< Two dimensional arrays in C/C++ - examples |
Next
Algorithms examples >| |

