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.
To read the article about recursive functions, go to the page: Recursive algorithms
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.
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.
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.
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.
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.
Add all factorials from 1 to n; the user enters n
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
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
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.
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
Write a function that prints the bits of x from left to right.
Write a function that prints the quotient of natural numbers M/N to k decimals
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
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.
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
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
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
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.
ciklus_levo which takes the parameters int A[] and int n.ciklus_levo and then show the result by calling the helper function stampaj_niz.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).
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.
bubble_sort(int A[], int n).stampaj_niz for printing the array.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;
}
swapped to stop if there were
zero swaps in a whole pass — that means the array is already sorted and we can stop early.
temp).
temp and the flag).
Extension (optional): Implement a version that sorts in descending order or that returns the number of passes needed for sorting.
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.
obrni_niz(int A[], int n) which changes the array directly.obrni_niz and then print the array with stampaj_niz.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;
}
obrni_niz uses two indices: levo (left) starts at index zero, and desno (right) at the last element.
tmp,
then move levo++ and desno--. This guarantees that each pair is swapped only once.
n <= 1 the function returns immediately because nothing changes; if n is very large, consider dynamic allocation instead of a VLA for portability.
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 >|
void must return a value with a return statement in every case.main, use a reference in C++ (int &x), and a pointer in C.jeProst(n) (isPrime), zbirCifara(n) (digitSum).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?
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.
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.
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.
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.
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.
cycle_left that takes parameters int A[] and int n.cycle_left, and then display the result using the helper function print_array.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).
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.
bubble_sort(int A[], int n).print_array to print the array.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++) {} /* Bubble sort (optimized version with early exit flag) */voidbubble_sort(int A[], int n) {printf("%d ", A[i]);} printf("\n");for (int pass = 0; pass < n - 1; pass++) {} intmain() {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]) {} 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 sortedbreak;}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;
swapped to terminate early if there were zero swaps in a full pass — meaning the array is already sorted.
temp).
temp and the flag).
Extension (optional): Implement a version that sorts in descending order or one that returns the number of passes required to sort.
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.
reverse_array(int A[], int n) that modifies the array directly.reverse_array, and then print the array using print_array.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++) {} /* Function that reverses an array 'in-place' using two pointers */voidreverse_array(int A[], int n) {printf("%d ", A[i]);} printf("\n");// If the array is empty or has one element, nothing to changeif (n <= 1) {} intmain() {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 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;
reverse_array uses two indices: left starts from index 0, and right from the last element.
tmp.
Then we increment left++ and decrement right--. This guarantees that each pair is swapped exactly once.
n <= 1, the function immediately returns since no changes are needed.
For very large n, consider using dynamic allocation instead of VLA for portability.
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>| |