C program to efficiently multiply a number with 7 using bitwise operator

  • Write a program in C to multiply a number with 7 using bitwise operator.
  • How to multiply a number by 7 in one line.
Required knowledge Bitwise operator in C
    Let's derive an expression to multiply a number with 7 using bitwise operator. Let N be the number that we want to multiply with 7.

    N x 7 = N + N + N + N + N + N + N
    N x 7 = N + N + N + N + N + N + N + (N - N)
    N x 7 = (N + N + N + N + N + N + N + N) - N
    N x 7 = 8xN - N

    As we know that, left shifting any number by one bit multiply it by 2. Hence, multiplying any number with 8 is equivalent to right shifting it by 3 bits(For Example : NX3 = N << 3). Replacing 8xN in above statement by 8 << 3.

    N x 7 = (N << 3) - N
WARNING !!!!
This approach can only be used to multiply integers or char by 7 because bitwise Operators can only be applied on char and integer operands. We cannot use bitwise operators with float, double, long double, void and other user define complex data types.

C program to multiply a number with 7 using bitwise operator.

#include<stdio.h>

int main() {
    int num;
    
    printf("Enter an integer\n");
    scanf("%d", &num);
    
    printf("7 X %d = %d", num, (num << 3) - num);

    return 0;
}
Output
Enter an integer
3
3 X 7 = 21
Enter an integer
0
0 X 7 = 0