C program to round off an integer number to the next lower multiple of 2

Here, we are going to learn how to round off an integer number to the next lower multiple of 2 in C programming language?
Submitted by Nidhi, on July 24, 2021

Problem statement

Read an integer number from the user, and then we will round off the input number to the next lower multiple of 2 using C program.

C program to round off an integer number to the next lower multiple of 2

The source code to round off an integer number to the next lower multiple of 2 is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to round off an integer number
// to the next lower multiple of 2

#include <stdio.h>

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

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

    if (num > 0) {
        for (; tmp <= num >> 1;)
            tmp = tmp << 1;
        num = tmp;
    }
    else {
        num = ~num;
        num = num + 1;

        for (; tmp <= num >> 1;)
            tmp = tmp << 1;

        tmp = tmp << 1;
        tmp = ~tmp;
        tmp = tmp + 1;
        num = tmp;
    }
    printf("Result is: %d\n", num);

    return 0;
}

Output

RUN 1:
Enter number: 6
Result is: 4

RUN 2:
Enter number: 34
Result is: 32

RUN 3:
Enter number: 732
Result is: 512

Explanation

In the main() function, we read an integer number from the user and then we round off the given integer number to the next lower multiple of 2 and printed the result on the console screen.

C Bitwise Operators Programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.