C Program Swap Numbers in Cyclic Order Using Call by Reference
Three variables entered by the user are stored in variables a, b, and c respectively.
Then, these variables are passed to the function cyclicSwap()
. Instead of passing the actual variables, addresses of these variables are passed.
When these variables are swapped in cyclic order in the cyclicSwap()
function, variables a, b, and c in the main
function are also automatically swapped.
Example: 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 *a,int *b,int *c)
{
int temp;
// swapping in cyclic order
temp = *b;
*b = *a;
*a = *c;
*c = 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
Notice that we haven’t returned any values from the cyclicSwap()
function.
a step-by-step explanation of a C program that swaps numbers in cyclic order using call by reference:
#include <stdio.h>
// function prototype
void cyclicSwap(int *a, int *b, int *c);
int main() {
int a, b, c;
printf("Enter three integers: ");
scanf("%d %d %d", &a, &b, &c);
printf("Before swapping: a = %d, b = %d, c = %d\n", a, b, c);
cyclicSwap(&a, &b, &c); // pass the addresses of a, b, and c to the function
printf("After swapping: a = %d, b = %d, c = %d", a, b, c);
return 0;
}
// function definition
void cyclicSwap(int *a, int *b, int *c) {
int temp;
temp = *b; // store the value of b in a temporary variable
*b = *a; // assign the value of a to b
*a = *c; // assign the value of c to a
*c = temp; // assign the value of the temporary variable to c
}
Let’s break it down step-by-step:
We include the necessary header files:
stdio.h
for input/output functions.We declare three integer variables
a
,b
, andc
.We prompt the user to enter three integers using
printf()
and read them in usingscanf()
.We print the values of
a
,b
, andc
before swapping usingprintf()
.We call the
cyclicSwap()
function and pass the addresses ofa
,b
, andc
to it using the&
operator.The
cyclicSwap()
function takes in three integer pointersa
,b
, andc
. Inside the function, we declare an integer variabletemp
.We store the value of
b
intemp
usingtemp = *b
.We assign the value of
a
tob
using*b = *a
.We assign the value of
c
toa
using*a = *c
.We assign the value of
temp
toc
using*c = temp
.Once the function completes execution, the values of
a
,b
, andc
inmain()
are updated.We print the values of
a
,b
, andc
after swapping usingprintf()
.Finally, we return 0 to indicate successful completion of the program.