Q:

C program to find the next number power of 2

0

C program to find the next number power of 2

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Read an integer number from the user, then find the next number power of 2 using the bitwise right shift operator using C program.

Program:

The source code to find the next number power of 2 is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to find the next number power of 2

#include <stdio.h>
#include <math.h>

int main()
{
    int num = 0;
    int i = 0;

    printf("Enter Number: ");
    scanf("%d", &num);

    num--;

    while (i <= 4) {
        num = num | (num >> (int)pow(2, i));
        i++;
    }

    num++;

    printf("The next number, power of 2 is: %d\n", num);

    return 0;
}

Output:

RUN 1:
Enter Number: 18
The next number, power of 2 is: 32

RUN 2:
Enter Number: 3
The next number, power of 2 is: 4

RUN 3:
Enter Number: 123
The next number, power of 2 is: 128

Explanation:

In the main() function, we read an integer number from the user and then found the next number, power of 2 using the bitwise right shift (>>) operator and printed the result on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C solved programs/examples on Bitwise Operators

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to find the position of MSB bit of an un... >>
<< C program to check a number contain the alternativ...