Skip to content
Related Articles

Related Articles

Swap three numbers in cycle
  • Last Updated : 28 May, 2018

Given three numbers, swap them in cyclic form. First number should get the value of third, second should get the value of first and third should get value of second.

Examples:

Input : a = 2, b = 4, c = 7
Output : a = 7, b = 2, c = 4

Input : a = 10, b = 20, c = 30
Output : a = 30, b = 10, c = 20

Prerequisite : Pointers, Call by Reference,

The idea is extend simple two variable swapping.

    // Before overwriting b, store its 
    // value in temp.
    temp = b;

    // Now do required swapping starting
    // with b.
    b = a;
    a = c;
    c = temp;

C++




// C program to perform Cyclic Swapping
// using Call by Reference
#include <stdio.h>
  
void cyclicSwap(int* a, int* b, int* c)
{
    // Before overwriting b, store its 
    // value in temp.
    int temp = *b;
  
    // Now do required swapping starting
    // with b.
    *b = *a;
    *a = *c;
    *c = temp;
}
  
int main()
{
    int a = 2, b = 4, c = 7;
  
    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;
}


C#




// C# program to perform Cyclic Swapping
// using Call by Reference
using System;
class GFG {
      
    static void cyclicSwap(ref int a, 
                   ref int b, ref int c)
    {
          
        // Before overwriting b, store 
        // its value in temp.
        int temp = b;
      
        // Now do required swapping 
        // starting with b.
        b = a;
        a = c;
        c = temp;
    }
      
    // Driver code
    public static void Main()
    {
        int a = 2, b = 4, c = 7;
  
        Console.Write("Value before swapping:\n");
        Console.Write("a = " + a + "\n"+ "b = "
                    b + "\n" + "c = " + c + "\n");
          
        cyclicSwap(ref a, ref b, ref c);
      
        Console.Write("Value after swapping:\n");
        Console.Write("a = " + a + "\n"+ "b = " +
                   b + "\n" + "c = " + c + "\n");
    
}
  
// This code is contributed by Sam007.



Output:

Value before swapping:
a = 2 
b = 4 
c = 7
Value after swapping:
a = 7 
b = 2 
c = 4



My Personal Notes arrow_drop_up
Recommended Articles
Page :