Given three variables x, y, z write a function to circularly shift their values to right. In other words if x = 5, y = 8, z = 10, after circular shift y = 5, z = 8, x = 10. Call the function with variables a, b, c to circularly shift values.
Page Contents
1. We need to write a function which receives 3 numbers.
2. Inside the function we need to swap the values of 3 variables circularly to the right.
i.e., value of x to y, value of y to z, and value of z to a.
Related Read:
Basics of Pointers In C Programming Language
Swap 2 Numbers Using a Temporary Variable: C
Any address preceded by a * (Indirection operator) will fetch the value present at that address.
Video Tutorial: C Program To Shift Variable Values Circularly To Right
#include<stdio.h> void shift_right(int*, int*, int*); int main() { int x, y, z; printf("Enter 3 numbers\n"); scanf("%d%d%d", &x, &y, &z); printf("Before shifting right: x = %d, y = %d and z = %d\n", x, y, z); shift_right(&x, &y, &z); printf("After shifting right: x = %d, y = %d and z = %d\n", x, y, z); return 0; } void shift_right(int *a, int *b, int *c) { int temp; temp = *c; *c = *b; *b = *a; *a = temp; }
Output 1:
Enter 3 numbers
5
8
10
Before shifting right: x = 5, y = 8 and z = 10
After shifting right: x = 10, y = 5 and z = 8
Output 2:
Enter 3 numbers
2
3
1
Before shifting right: x = 2, y = 3 and z = 1
After shifting right: x = 1, y = 2 and z = 3
We ask the user to enter 3 numbers and store it inside the address of variables x, y and z. Now we pass these 3 address to the function shift_right();
Inside shift_right() function
Inside shift_right() function we shift the value present at *c to a temp variable. Then, we shift the value of *b to *c, then the value of *a to *b, and then we shift the value present in temp to *a. This shifts the values of variables x, y and z circularly to the right.
*a has the value present at the address &x;
*b has the value present at the address &y;
*c has the value present at the address &z;
int temp;
temp = *c;
*c = *b;
*b = *a;
*a = temp;
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert