Functions in C/C++ – examples

Page 10 of 11 · Basic examples

To read the article about recursive functions, go to the page: Recursive algorithms

Before you start: read the lessons Functions in C, Functions in C++.
How to practice: first try to solve the task yourself (at least on paper), then open the hints, and the solution only at the end. The solutions are mostly in C or C++; if you are learning Java or Python, rewrite the idea in your language.
TASK 01

Swapping places

Read two integers X and Y. Make a function that swaps the values of two integer variables. Use this function to swap the values of the variables X and Y.

TASK 02

Printing an array

Read n. Then read an array of n elements. Make a separate method for printing it. Using that method, print the elements of the array on the screen.

TASK 03

Extracting the even elements of an array

Read an array of n elements. The user enters the number n and the elements of the array. Make a method that copies the even elements from the original array. Use the method to extract the even elements from the original array.

TASK 04

The number of occurrences of a character

Enter any text from the keyboard. Make a separate function that counts the given character. Use the function to find how many times the letter "p" appears in the entered text.

TASK 05

Computing the factorial of n

Make a function that computes the factorial of a number n. In the main function read n and use the previously made function to compute the factorial of that number.

TASK 06

The sum of the factorials of the first n natural numbers

Add all factorials from 1 to n; the user enters n

TASK 07

Daily wages

Mihajlo works part-time and earns money for his work on a daily basis. He writes the dates and the amount earned that day in his notebook, because he keeps records. Make a program that helps Mihajlo with the entered dates and earnings, entered so that one line holds one date with the daily earnings. Make a function that, from the given array of daily earnings, separates the dates and 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 (day, 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

TASK 08

Logging in

Make a method (function) for logging a user in by entering a username and password. Allow the user at most 3 attempts to enter the password. The method should answer whether the user logged in successfully or not. Call the function from the main method. If the method returns that the user is logged in, print the message: "The user logged in successfully", otherwise print "The user did not log in successfully". The correct combination of username and password is known: admin korisnik.

Example:
Input
:
Enter your username and password:
"Mika"
"korisnik1"
Wrong password, enter again
"admin"
"korisnik"
Output:
The user logged in successfully

TASK 09

Finding the maximum

Make a function that finds the maximum of two integers passed as parameters of the function.
Read two integers and find their maximum using the previously defined function.

TASK 10

Checking whether a number is prime

Make a function that checks whether the number passed to it as a parameter is prime.
Read an integer and find whether it is prime using the previously defined function.
Read more about prime numbers on the page: Prime numbers and factorization

TASK 11

Printing bits from left to right

Write a function that prints the bits of x from left to right.

TASK 12

Rounding to K decimals

Write a function that prints the quotient of natural numbers M/N to k decimals

TASK 13

Computing combinations

Write a program that, for given natural numbers n,k,p, computes
S=Cnk-Cnk+1 +..+(-1)p*Cnk+p,
using the formula for combinations

TASK 14

The bit at a given position

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

TASK 15

A number in reverse order

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

TASK 16

The closest number that satisfies the condition

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

TASK 17

Letters in a new order

In one country, in a reformist mood, the order of the capital letters of the alphabet was changed as follows:
"MILOSCGRABDEFHJKNPQTUVWXYZ"
a) Write a function that compares two strings according to the new order of letters
b) test the function by printing an array of the names of newly appointed ambassadors in the order defined by the new alphabet

Combined tasks using functions

TASK 18

Shift the array elements to the left (rotation)

Write a function in C that shifts all elements of an array one place to the left (cyclic rotation). The function should modify the array in-place and the last element should become the previous first element.

  • Create the function ciklus_levo which takes the parameters int A[] and int n.
  • In the main function: read the size n, enter n array elements, call ciklus_levo and then show the result by calling the helper function stampaj_niz.
  • Pay attention to edge cases: n <= 1 (the array does not change).

A short explanation of the task:

The goal is to show how an array is changed directly in a function (by passing a pointer to the first element) and to understand the simple algorithmic operation of shifting elements (O(n) time complexity).

TASK 19

Sorting an array with Bubble Sort

Write a C program that sorts an array of integers using the standard Bubble Sort algorithm. Implement the function bubble_sort which takes an array and its length and sorts the elements in-place. In main read the size of the array, read the elements, call the sorting and show the result.

  • Create the function bubble_sort(int A[], int n).
  • Add the helper function stampaj_niz for printing the array.
  • Optimize Bubble Sort to stop early if the array is already sorted (using a flag).

A short explanation of the task:

Bubble sort compares neighboring pairs and swaps them when needed, so that the largest element "bubbles up" to the end in one iteration. Repeat the procedure until the array is sorted. The algorithm is simple to implement (and stable), but its time complexity is O(n²).

#include <stdio.h>

/* Helper function for printing the array */
void stampaj_niz(int A[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%d ", A[i]);
    printf("\n");
}

/* Bubble sort with a flag: if there are no swaps in a pass, the array is sorted */
void bubble_sort(int A[], int n)
{
    for (int prolaz = 0; prolaz < n - 1; prolaz++)
    {
        int bilo_zamena = 0;
        for (int i = 0; i < n - prolaz - 1; i++)
        {
            if (A[i] > A[i + 1])          /* neighbors in the wrong order */
            {
                int temp = A[i];
                A[i] = A[i + 1];
                A[i + 1] = temp;
                bilo_zamena = 1;
            }
        }
        if (!bilo_zamena)                 /* the array is already sorted */
            break;
    }
}

int main()
{
    int n;
    scanf("%d", &n);
    int niz[n];                           /* variable-length array (C99) */
    for (int i = 0; i < n; i++)
        scanf("%d", &niz[i]);

    bubble_sort(niz, n);
    stampaj_niz(niz, n);
    return 0;
}

Explanation of the solution

  • Principle: Bubble sort compares neighboring elements and, by swapping the bigger with the smaller one, moves the bigger elements towards the end.
  • Optimization: We use the variable swapped to stop if there were zero swaps in a whole pass — that means the array is already sorted and we can stop early.
  • In-place: Sorting changes the contents of the passed array directly (no extra memory is needed except the temporary temp).
  • Stability: Bubble sort is a stable algorithm — the relative order of equal elements is kept.
  • Time complexity:
    • Worst and average case: O(n²).
    • Best case (an already sorted array, thanks to the flag): O(n).
  • Space:O(1) extra memory (only temp and the flag).
  • Note about C compatibility: if you want portability to old C compilers, use malloc and free instead of a VLA.

Extension (optional): Implement a version that sorts in descending order or that returns the number of passes needed for sorting.

TASK 20

Reverse an array

Write a program in C that implements a function that reverses the elements of an integer array in-place. The function should swap elements so that the first becomes the last, the second becomes the second to last, etc. In main read the size of the array, enter the elements, call the reversing function and show the result.

  • Create the function obrni_niz(int A[], int n) which changes the array directly.
  • In main: read n, fill the array, call obrni_niz and then print the array with stampaj_niz.
  • Pay attention to edge cases (n <= 1).

A short explanation of the task:

The goal is to show how to manipulate array elements using two indices (left/right) and swap elements until they cross. The algorithm works in-place with O(1) extra memory and time complexity O(n).

#include <stdio.h>

void stampaj_niz(int A[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%d ", A[i]);
    printf("\n");
}

/* Reverses the array in place: swaps the first with the last, the second with the second to last... */
void obrni_niz(int A[], int n)
{
    int levo = 0, desno = n - 1;
    while (levo < desno)
    {
        int tmp = A[levo];
        A[levo] = A[desno];
        A[desno] = tmp;
        levo++;
        desno--;
    }
}

int main()
{
    int n;
    scanf("%d", &n);
    int niz[n];
    for (int i = 0; i < n; i++)
        scanf("%d", &niz[i]);

    obrni_niz(niz, n);
    stampaj_niz(niz, n);
    return 0;
}

Explanation of the solution

  • The function obrni_niz uses two indices: levo (left) starts at index zero, and desno (right) at the last element.
  • In a while loop, as long as levo < desno, we swap the values at those positions using the temporary variable tmp, then move levo++ and desno--. This guarantees that each pair is swapped only once.
  • The algorithm works in-place (without extra large buffers) and uses O(1) extra memory. The time complexity is O(n) because each element takes part in at most one swap.
  • Edge cases: if n <= 1 the function returns immediately because nothing changes; if n is very large, consider dynamic allocation instead of a VLA for portability.
  • Advantages of this approach: simplicity, efficiency and low memory use. Suitable when you need to reverse the order of elements quickly.

Extension (optional): Write a version that returns a newly allocated array (does not change the original), or a generic function that reverses an array of type void* using an element-swap function (useful for other types).

Previous
|< Matrices – examplesNext
Algorithms – examples >|

Common mistakes and tips
  • A function that is not void must return a value with a return statement in every case.
  • A parameter is passed as a copy; for a function to change a variable from main, use a reference in C++ (int &x), and a pointer in C.
  • A good function does one thing and has a name that says so: jeProst(n) (isPrime), zbirCifara(n) (digitSum).

Check your knowledge

Open the quiz

Mini quiz: functions

1. What is the return type of a function that only prints text?




2. The function void uvecaj(int x) { x++; } is called with uvecaj(a), where a = 5. What is a after the call?



3. When is it better to put part of a program into a function?