C Program to Round Floor of Integer to Next Lower Power of 2

This C program finds the next lower power of 2 for a given integer using bitwise operations.

Problem statement

Given an integer num, we need to find the next lower power of 2 (round floor) for this integer. The program should use bitwise operations to efficiently perform the calculation and display the result.

C Program to Round Floor of Integer to Next Lower Power of 2

#include <stdio.h>

int roundFloorToPowerOf2(int num) {
    if (num < 2)
        return 0;

    int power = 1;
    while (power <= num / 2) {
        power *= 2;
    }
    return power;
}

int main() {
    int num;
    printf("Enter an integer: ");
    scanf("%d", &num);
    int result = roundFloorToPowerOf2(num);
    printf("The floor of %d to the next lower power of 2 is %d\n", num, result);

    return 0;
}

How it Works

  1. The function takes an integer num as input.
  2. If the input number num is less than 2, the function returns 0. This is because there is no lower power of 2 to round down to when the input is 0 or 1.
  3. If the input number num is greater than or equal to 2, the function initializes a variable power to 1. This variable will be used to track the power of 2.
  4. The function enters a loop that continues as long as power is less than or equal to half of the input number (num / 2).
  5. Inside the loop, the power variable is doubled in each iteration using the statement power *= 2. This ensures that power represents the largest power of 2 that is less than or equal to the input number.
  6. Once the loop terminates, the function has found the next lower power of 2 for the input number. It returns the value of power.

In the main function, the user is prompted to enter an integer, and the input is stored in the num variable. Then, the roundFloorToPowerOf2 function is called with num as the argument. The returned value is stored in the result variable.

Finally, the program displays the result on the console using printf.

Input / Output

C Program to Round Floor of Integer to Next Lower Power of 2

Share:

Leave A Reply

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

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...