​Functions in C/C++ - examples


If you want to learn about the functions in C and C++, visit the webpage: Functions in Functions in C or Function in C++

1. Replacement of the position

Load two integers of X and Y. Create a function that changes the positions of two integer variables. Use this function and replace the values ​​with X and Y variables.

2. Is the number simple?

Make a function that determines whether a number is simple. Enter a natural number and examine whether it's free.

3. Printing the array

Enter n. Then Enter n elements of that array. Create a special method for writing it. Use that method to print the array elements on the screen.​

4. Extracting even elements of an array

​Enter an array of n elements. The number n, as well as the elements of the array, is entered by the user. Create a method that overwrites even elements from the initial array. Use the created method to extract even elements from the initial sequence.

5. Number of repetitions of a certain character

​Enter some text from the keyboard. Create a special function that counts the passed character. Use the function to determine the number of repetitions of the letter "p" in the entered text.

6. Daily earnings

Michael is employed part-time and earns a daily income for his work. He writes down the dates and the value of that day's earnings in his notebook because he keeps records of it. Create a program that will help Michael to load date values ​​with earnings that are entered so that one date with daily earnings can be loaded in one row. Create a function that separates the dates and earnings from the passed array of daily earnings into two separate arrays in which these data are defined, the date as a string and the earnings as a real number. The date is entered in the format dd_mm__yyyy (date, month, year)

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

​Create a method (function) for user login based on entering a username and password. Allow the user to attempt a maximum of 3 password attempts. The method should give an answer whether the user is successfully logged in or not. Call the function from the main method. If the method returns that the user is logged in, then print the message: "The user is successfully logged in", otherwise write "The user is not successfully logged in". The username and password combination is known to be correct: admin user.
​
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

    Mihajlo is employed part-time and earns a daily income for his work. He writes down the dates and the value of that day's earnings in his notebook because he keeps records of it. Create a program that will help Mihajlo to load date values ​​with earnings that are entered so that one date with daily earnings can be loaded in one row. Create a function that separates the dates and earnings from the passed string of daily earnings into two separate strings in which these data are defined, the date as a string and the earnings as a real number. The date is entered in the format dd_mm__yyyy (date, month, year).

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

    ​Create a method (function) for user login based on entering a username and password. Allow the user to attempt a maximum of 3 password attempts. The method should give an answer whether the user is successfully logged in or not. Call the function from the main method. If the method returns that the user is logged in, then print the message: "The user is successfully logged in", otherwise write "The user is not successfully logged in". The username and password combination is known to be correct: admin user.

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

​Create a function that determines the maximum of two integers passed as function parameters.
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.

#include < stdio.h>

/*Solution for C programming language*/

int maximum(int a, int b)
{
if(a>b)
{
return a;
}
else
{
return b;
}
}

int main()
{
int a,b,maxAB;
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

Create a function that checks if the number passed to it as a parameter is prime. Enter an integer and determine if it is prime using the previously defined function.
Read more about prime numbers on the website: A prime numbers and factoring
#include < stdio.h>

/*Solution in the programming language C*/

int prime(int a)
{
int res=1;
if(a==1 || a==2){
return 1;
}
int d=2;
while(d < a){
if(a % d == 0){
res=0;
break;
}
d++;
} return res;
}

int main()
{
int x;
printf("x=?\n");
scanf("%d",&x);
if(prime(x)){
printf("The number %d is prime",x);
}
else{
printf("The number %d isn't prime",x);
}
return 0;
}

12. Writing bits from left to right

​​Write a function that prints the bits of x 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.

#include < stdio.h>

/*Solution in the programming language C*/

int bits(int a)
{
int rem = x; //7
for(int i = 15;i >= 0;i--){
int a=(int)pow(2,i);
if(a <= rem){
printf("1 ");
rem=rem % a; //a=4, rem =7%4=3; a=2, rem =3%2=1; a=1, rem =1%1=0
}
else{
printf("0 ");
}
}
printf("\n");
}

int main()
{
int x;
printf("x=?\n");
scanf("%d",&x);
bits(x);
return 0;
}

13. Rounding to K decimal places.

​​Write a function that prints the quotient of natural numbers M/N 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.

#include < stdio.h>

/*Solution in programming language C*/

int main()
{
int M,N,K,res,coef;
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.

Write a program to calculate
for the given natural numbers n,k,p S=Cnk-Cnk+1 +..+(-1) p*Cnk+p,
according to the formula for calculating combinations

15. Bit in the given position.

    Write a function that reports whether there is a 1 at position pos, the argument of the function (parameter) X. The bit positions are numbered, from right to left, starting from position 1.

16. Number in reverse order.

If the number M1 is obtained from the number M by writing its digits in inverse order, write a program that prints all pairs of three-digit numbers (a,b) that have the property: If A*B=C, then A1*B1=C1. E.g:
312 * 221 = 68952
213 * 122 = 25986

17. The closest number that satisfies the condition.

If S(n) denotes the sum of digits in the decimal notation of the number n, determine n such that it is the nearest number smaller than 2003, for which the equality holds:
n+S(n)+S(S(n))+S(S(S(n)))+S(S(....S(n)....)=2003

17. Calculating the factorial of n.

​Create a function that calculates the factorial of n. Inside the main function, load n and use the previously created function to calculate the factorial of that number.

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.

<!-- C solution -->
#include <stdio.h>

/* C solution (compilable in C89/C99 and newer) */

int factorial(int n)
{
int i;
int f;
if (n == 0)
{
/* 0! = 1 */
return 1;
}
if (n < 0)
{
/* Factorial of negative numbers is undefined here */
return -1; /* error indicator */
}
f = 1;
for (i = n; i > 0; i--)
{
f = f * i;
}
return f;
}

int main(void)
{
int n, f;
printf("Enter an integer n: ");
if (scanf("%d", &n) != 1)
{
printf("Invalid input\n");
return 1;
}

if (n >= 0)
{
f = factorial(n);
printf("Factorial is %d\n", f);
}
else
{
printf("You cannot enter a negative number\n");
}

return 0;
}

<!-- C++ solution -->
#include <iostream>

/* C++ solution (compilable with modern C++ compilers) */

unsigned long long factorial(int n)
{
if (n == 0) return 1ULL; /* 0! = 1 */
if (n < 0) return 0ULL; /* error indicator: returning 0 */
unsigned long long f = 1ULL;
for (int i = 1; i <= n; ++i)
{
f *= (unsigned long long)i; /* beware of overflow for large n */
}
return f;
}

int main()
{
int n;
std::cout << "Enter an integer n: ";<br>
if (!(std::cin >> n))
{
std::cout << "Invalid input\n";
return 1;
}

if (n < 0)
{
std::cout << "You cannot enter a negative number\n";
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_left that takes parameters int A[] and int n.
  • In the main function: read the size n, input n array elements, call cycle_left, and then display the result using the helper function print_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_array to 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 */voidprint_array(int A[], int n) {
printf("print_array:\n"); for (int i = 0; i < n; i++) {
printf("%d ", A[i]);
} printf("\n");
} /* Bubble sort (optimized version with early exit flag) */voidbubble_sort(int A[], int n) {
for (int pass = 0; pass < n - 1; pass++) {
int swapped = 0; for (int i = 0; i < n - pass - 1; i++) {
// If element at i is greater than the next one, swapif (A[i] > A[i + 1]) {
int temp = A[i]; A[i] = A[i + 1]; A[i + 1] = temp; swapped = 1;
}
} if (!swapped) {
// No swaps in this pass — array is already sortedbreak;
}
}
} intmain() {
int n; // Read array sizescanf("%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]);
} // Sortingbubble_sort(arr, n); // Print sorted arrayprint_array(arr, n); return0;
}

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 swapped to 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 temp and 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 using print_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 */voidprint_array(int A[], int n) {
printf("print_array:\n"); for (int i = 0; i < n; i++) {
printf("%d ", A[i]);
} printf("\n");
} /* Function that reverses an array 'in-place' using two pointers */voidreverse_array(int A[], int n) {
// If the array is empty or has one element, nothing to changeif (n <= 1) {
return;
} int left = 0; int right = n - 1; while (left < right) {
int tmp = A[left]; A[left] = A[right]; A[right] = tmp; left++; right--;
}
} intmain() {
int n; // Read the size of the arrayscanf("%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 arrayreverse_array(arr, n); // Print the resultprint_array(arr, n); return0;
}

Solution explanation

  • The function reverse_array uses 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 large n, 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).