Easy Tutorial
❮ C Pointers C Exercise Example79 ❯

C Language Example - Cyclic Swap of Values Using References

C Language Examples

Three variables a, b, and c, whose values are cyclically swapped in sequence by reference.

Example

#include<stdio.h>

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

int main()
{
    int a, b, c;

    printf("Enter the values of a, b, and c: ");
    scanf("%d %d %d", &a, &b, &c);

    printf("Before swapping:\n");
    printf("a = %d \nb = %d \nc = %d\n", a, b, c);

    cyclicSwap(&a, &b, &c);

    printf("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
    temp = *b;
    *b = *a;
    *a = *c;
    *c = temp;
}

Output:

Enter the values of a, b, and c: 1 2 3
Before swapping:
a = 1 
b = 2 
c = 3
After swapping:
a = 3 
b = 1 
c = 2

C Language Examples

❮ C Pointers C Exercise Example79 ❯