# C program to rotate the bits for a given number

CServer Side ProgrammingProgramming

Consider the factors given below to write a C program to rotate the bits for a given number.

• Rotating the bit from left to right or right to left.

• In left rotation, the bits are shifted from left to right.

• In right rotation, the bits are shifted from right to left.

• Take a number and try to rotate either left or right based on user program.

• User has to enter the number rotation at run time along with a number.

## Program 1

Following is the C program to apply left rotation for a given number.

Live Demo

#include<stdio.h>
#include<stdlib.h>
int main(){
int number, rotate, Msb, size;
printf("Enter any number:");
scanf("%d",&number);
printf("Enter number of rotations:\n");
scanf("%d",&rotate);
size = sizeof(int) * 8;
rotate %= size;
while(rotate--){
Msb = (number >> size) & 1;
number = (number << 1) | Msb;
}
printf("After Left rotation the value is = %d\n",number);
return 0;
}

## Output

When the above program is executed, it produces the following result −

Enter any number:12
Enter number of rotations:
2
After Left rotation the value is = 48

## Program 2

Given below is the C program to apply right rotation for a given number.

Live Demo

#include<stdio.h>
#include<stdlib.h>
int main(){
int number,rotate, Lsb, size;
printf("Enter any number:");
scanf("%d",&number);
printf("Enter number of rotations:\n");
scanf("%d",&rotate);
size = sizeof(int) * 8;
rotate %= size;
while(rotate--){
Lsb = number & 1;
number = (number >> 1) &(~(1<<size));
number=number|(Lsb<<size);
}
printf("After right rotation the value is = %d\n",number);
return 0;
}

## Output

When the above program is executed, it produces the following result −

Enter any number:18
Enter number of rotations:
2
After right rotation the value is = 4
Published on 12-Mar-2021 06:34:11