循环交换三个数字
给定三个数字,以循环形式交换它们。第一个数字应该得到第三个的值,第二个应该得到第一个的值,第三个应该得到第二个的值。
例子:
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
先决条件:指针,引用调用,
这个想法是扩展简单的两个变量交换。
// 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
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.
输出:
Value before swapping:
a = 2
b = 4
c = 7
Value after swapping:
a = 7
b = 2
c = 4