Q:

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

0

C program to round off an integer number to the next lower multiple 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, and then we will round off the input number to the next lower multiple of 2 using C program.

Program:

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.

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 print the range of fundamental data t... >>
<< C program to find the position of MSB bit of an un...