Swap Numbers in a Cyclic Manner in C
C Program to Swap Numbers in a Cyclic Order
In this page, we have provided codes and algorithms to swap numbers in a cyclic manner in C. This includes swapping two numbers and swapping three numbers in a cyclic order.
Swap Two Numbers in a Cyclic Order in C
To swap numbers in a cyclic manner in a C program, you can use a temporary variable to store the value of one of the numbers while the other number is being assigned to it.
Step 2:- assign it the value of x
Step 3:- assign the value of y to x and the value of temp (original valueof x) to y.
Step 4:- print the swapped values of x and y
Program to Swap Two Numbers in a Cycle
#include <stdio.h> int main() { int x = 10; int y = 20; printf("Before swapping: x = %d, y = %d\n", x, y); int temp = x; x = y; y = temp; printf("After swapping: x = %d, y = %d\n", x, y); return 0; }
Output
Before swapping: x = 10, y = 20
After swapping: x = 20, y = 10
Swap Three Numbers in a Cyclic Order in C
It is similar to swapping two numbers. The only difference is that there are three temporary variables to assign the values of three numbers.
Step 2:- print these values to console using printf function.
Step 3:- define two temporary variables, temp1 and temp2 and assign them the values of x and y respectively.
Step 4:- assign the value of z to x, value of temp1 to y and temp2 to z.
Step 5:- the values of x,y and z are printed with the values being rotated in a cyclic manner.
Prime Course Trailer
#include <stdio.h> int main() { int x = 10; int y = 20; int z = 30; printf("Before swapping: x = %d, y = %d, z = %d\n", x, y, z); int temp1 = x; int temp2 = y; x = z; y = temp1; z = temp2; printf("After swapping: x = %d, y = %d, z = %d\n", x, y, z); return 0; }
Output
Before swapping: x = 10, y = 20, z = 30
After swapping: x = 30, y = 10, z = 20
Swap Variables of Different Types in C Program
Step 2:- define two variables x and y
Step 3:- define a variable temp of type union value and assign it the value of x.
Step 4:- Assign the value of y o x, casting it to an int first, and the value of temp.i
Step 5:- Print the values of x and y being swapped
#include <stdio.h> union value { int i; float f; char c; }; int main() { int x = 10; float y = 20.5; printf("Before swapping: x = %d, y = %f\n", x, y); union value temp; temp.i = x; x = (int) y; y = (float) temp.i; printf("After swapping: x = %d, y = %f\n", x, y); return 0; }
Output
Before swapping: x = 10, y = 20.500000 After swapping: x = 20, y = 10.000000
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment