C Program Swap Numbers in cyclic order Using Call by Reference
The three integers that the user entered in cyclical sequence are swapped in this tutorial using call by reference.
C Program:
#include <stdio.h>
void cyclic_Swap ( int *X, int *Y, int *Z );
int main ()
{
// Considering three variables
int X, Y, Z;
// Asks user for three inputs
printf ("Enter the value of X, Y and Z respectively:\n ");
// Storing values in the variables
scanf ( "%d %d %d", & X, & Y, & Z );
// Printing the input values thoroughly
printf ( "Before swapping, the values are\n" );
printf ("X = %d \nY = %d \nZ = %d\n", X, Y, Z);
// Swapping function
cyclic_Swap ( & X, & Y, & Z );
// Printing the values after succesfully swapping
printf ( "After swapping, the values are:\n" );
printf ( "X = %d \nY = %d \nZ = %d", X, Y, Z );
return 0;
}
// Function
void cyclic_Swap ( int *num1, int *num2, int *num3 )
{
int temp;
temp = *num2;
*num2 = *num1;
*num1 = *num3;
*num3 = temp;
}
Output:
Enter the value of X, Y and Z respectively:
15
18
12
Before swapping, the values are
X = 15
Y = 18
Z = 12
After swapping, the values are:
X = 12
Y = 15
Z = 18
Likewise, variables X, Y, and Z are used to hold the three numbers that the user input. The cyclic_Swap() function receives the addresses of these numbers as input.
cyclic_Swap ( & X, & Y, & Z );
These addresses have been given to pointers in the function specification for cyclic_Swap().
void cyclic_Swap ( int *num1, int *num2, int *num3 )
{
.....
}
The values of X, Y, and Z inside main() are also updated when num1, num2, and num3 inside cyclic_Swap() are updated.
Keep in mind: There is no return from the cyclic_Swap() function.