# Program to set Nth bit of a number in C++

Written by

Garvit Gulati

Given a number num and a value n, we have to set the value of nth bit from right in the binary representation of that number.

### Introduction to Left shift and Right shift operator

• The left shift and right shift operators are used to shift the bits of a number either left or right as specified.
• RIGHT SHIFT(>>): it accepts to numbers, and shifts the first number to the right, number of times as specified by the second number. For example,
• Shifting a number to left n times, is equivalent to multiplying the number by 2n.

### # Approaching the problem

Setting nth bit of a number means assigning the value 1 to its nth bit if it was 0 and if 1 leaving it as it is.

To set the nth bit of  a number we have to operate it with a number such that it edits only the nth bit of that number.

Since we have to turn it to 1 if its zero and leave it as it is if its 1, its clear that we have to perform an OR operation with a number that has 1 at the nth bit. Rest of the bits should be zero so that it doesn’t change any other bit. The number will be obtained by shifting 1 to the right by n-1 times.

For example, we have to set 2nd bit 13

 13 1 1 0 1 1>>(n-1) 0 0 1 0 OR 1 1 1 1 =15

### # Algorithm

1. The user is prompted to enter an integer value, which is stored in the `num` variable.
2. The user is then prompted to enter the position of the bit they wish to set, which is stored in the `n` variable.
3. A bitwise OR operation is performed between `num` and a value that has a single bit set at the `n`th position. This is done by shifting the value 1 to the left by `n-1` bits using the `<<` operator and using the OR operator (`|`) to set the `n`th bit of `num`.
4. The result of the OR operation is printed to the console.

Code

``````#include <iostream>
using namespace std;

int main()
{
int num, n;

cout << "Enter number: ";
cin >> num;

cout << "Enter bit number you wish to set: ";
cin >> n;

cout << "Bit set Successfully" << endl;
cout << "Answer: " << (num | (1 << (n - 1))) << endl;

return 0;
}

``````

Output

``````Enter Number
13

Enter bit number you wish to set
2

Bit set Successfully