Swap Numbers in Cyclic Order Using Call by Reference in C

Exercise:

Write a C Program swap numbers in cyclic order using call by reference.

Click Here to View the Solution!
#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 *num1, int *num2, int *num3) {
    int temp;
    // swapping in cyclic order
    temp = *num2;
    *num2 = *num1;
    *num1 = *num3;
    *num3 = temp;
}
Click Here to View the Output!
Enter a, b and c respectively: 3 5 4
Value before swapping:
a = 3 
b = 5 
c = 4
Value after swapping:
a = 4 
b = 3 
c = 5
Click Here to View the Explanation!
  • This program is used to swap elements in a cyclic order by using call by reference.
  • A void type function cyclicSwap is declared that takes three integer element pointers *a, *b and *c.
  • In main(), the program requests the user to enter the values of a, b and c and stores them in their variables using the scanf() function.
  • The values before the swapping are printed.
  • The function cyclicSwap is called in main to which the addresses of the values are passed by using ampersand as cyclicSwap(&a, &b, &c).
  • The swapped values after the function is called are printed.
  • The function cyclicSwap is then initialized by using a temp variable. The pointer values num1, num2 and num3 are swapped in a cyclic order. In this definition of the function, the addresses have been assigned to the pointers.

%d bloggers like this: