Popular Tutorials
Start Learning CCertification Courses
Created with over a decade of experience and thousands of feedback.
C Program Swap Numbers in Cyclic Order Using Call by Reference
In this example, the three numbers entered by the user are swapped in cyclic order using call by reference.
To understand this example, you should have the knowledge of the following C programming topics:
Program to Swap Elements Using Call by Reference
#include <stdio.h>
void cyclicSwap(int *a, int *b, int *c);
int main() {
int a, b, c;
printf("Enter a, b and c respectively: ");
scanf("%d %d %d", &a, &b, &c);
printf("Value before swapping:\n");
printf("a = %d \nb = %d \nc = %d\n", a, b, c);
cyclicSwap(&a, &b, &c);
printf("Value after swapping:\n");
printf("a = %d \nb = %d \nc = %d", a, b, c);
return 0;
}
void cyclicSwap(int *n1, int *n2, int *n3) {
int temp;
// swapping in cyclic order
temp = *n2;
*n2 = *n1;
*n1 = *n3;
*n3 = temp;
}
Output
Enter a, b and c respectively: 1 2 3 Value before swapping: a = 1 b = 2 c = 3 Value after swapping: a = 3 b = 1 c = 2
Here, the three numbers entered by the user are stored in variables
a, b and c respectively. The addresses of
these numbers are passed to the cyclicSwap() function.
cyclicSwap(&a, &b, &c);
In the function definition of cyclicSwap(), we have assigned
these addresses to pointers.
cyclicSwap(int *n1, int *n2, int *n3) {
...
}
When n1, n2 and n3 inside
cyclicSwap() are changed, the values of a,
b and c inside main() are also changed.
Note: The cyclicSwap() function is not returning
anything.
Did you find this article helpful?