c
  1. c-program-swap-numbers-in-cyclicorder-using-call-by-reference

Program Swap Numbers in Cyclic Order Using Call by Reference - (C Programs)

In this C program, we are swapping two numbers in a cyclic order using call by reference. In this technique, instead of passing a copy of the value to the function, we pass the address of the variable. By doing this, any changes made inside the function are reflected in the original variables.

Syntax

void cyclicSwap(int *a, int *b, int *c);

Here, a, b, and c are pointers to integers, representing the values of three variables.

Example

#include<stdio.h>
void cyclicSwap(int *a, int *b, int *c);

void main()
{
    int a, b, c;
    
    printf("Enter the three numbers: ");
    scanf("%d %d %d", &a, &b, &c);
    
    printf("Before cyclic swapping: a = %d, b = %d, c = %d\n", a, b, c);
    
    cyclicSwap(&a, &b, &c);
    
    printf("After cyclic swapping: a = %d, b = %d, c = %d\n", a, b, c);
}

void cyclicSwap(int *a, int *b, int *c)
{
    int temp;
    
    // Swapping in cyclic order
    temp = *b;
    *b = *a;
    *a = *c;
    *c = temp;
}

Output

Enter the three numbers: 1 2 3
Before cyclic swapping: a = 1, b = 2, c = 3
After cyclic swapping: a = 3, b = 1, c = 2

Explanation

In this program, we have defined a function cyclicSwap that takes three pointers to integers as arguments.

Inside the cyclicSwap function, the values of a, b, and c are swapped in a cyclic order. First, the value of b is stored in a temporary variable temp. Then, the value of a is assigned to b, the value of c is assigned to a, and the value of temp is assigned to c. Thus, the values are swapped in a cyclic order.

In the main function, we have declared three variables a, b, and c and initialized them with user-input values. We have then printed the values before swapping. We have then passed the addresses of a, b, and c to the cyclicSwap function. After the function is executed, the values of a, b, and c are printed again to verify that they have been swapped in a cyclic order.

Use

This program can be used to swap the values of three variables in a cyclic order using call by reference in C. It demonstrates how pointers can be used to manipulate values in memory and swap them.

Summary

In this tutorial, we have learned how to swap the values of three variables in a cyclic order using call by reference in C. We have covered the syntax, example, explanation, and use of the program. The program demonstrates how pointers can be used to manipulate values in memory and swap them.

Published on: