How to set bits in all numbers from 1 to n in C ++

In this tutorial, I will be showing to set bits of all numbers from 1 to n. I will be using C++ to implement my approach.

Setting bits of a number basically means to change the bit to 1 from 0. The bit should be on for the specified index by the user. Let us take an example to make this idea clear:

Number:  129

Binary:     10000001

Set Bit:     7

Result:     193

I will be using a bitwise operator for carrying out this function. It can also be done without the use of a bitwise operator. However, changing every number into its binary would make the program very complex. Hence, I have used the operator to keep the concept easy to understand.

I have made two functions: setbit() and main() function in my code to carry out this operation,

The setbit()  function takes two parametrized inputs. One is the total numbers that need to be altered from 1 to n. The second parameter is the k(th) bit that needs to be set in each number. I have used a for loop to go through all numbers from 1 to n. I set the bit, using the bitwise OR ( | ) operator. However, note here we need to set the k(th) bit so we need to go to that bit first. For this, I have used the left shift operator that shifts the 1 to the desired bit and then does the bitwise OR.

In the main() function, I take the two user inputs and pass them as parameters to my setbit() function.

I have shown my code below:

using namespace std;

void setbit(int k, int t)
    int i;
    //Loop for numbers from 1 to n
        //using biwise OR 
        int x = (i) | 1 << (k-1);
        cout << (i) << "  -->  " << x << " " << endl;

int main()
    int n, bit;
    cout << "Enter n" << endl;
    cin >> n;
    cout << "Enter bit to be set in numbers from 1 to n" << endl;
    cin >> bit;
    setbit(bit, n);
    return 0;


I take user input as n = 5 and k = 3. So for numbers from 1 to 5, the 3rd bit will be set.


Enter n
Enter bit to be set in numbers from 1 to n
1 --> 5 
2 --> 6 
3 --> 7 
4 --> 4 
5 --> 5


Leave a Reply

Your email address will not be published. Required fields are marked *