[Programming] Question 13: Demonstrate division by powers of 2 using right shift operator in C?

Learn how to efficiently divide integers by powers of 2 using the right shift operator (>>) in C. This guide explains how shifting the bits of a number to the right effectively performs division by powers of 2, offering a faster alternative to traditional division operations. The tutorial includes clear examples, step-by-step explanations, and sample code to help you understand and apply this technique in your C programs.

#include <stdio.h>

int main() {
	int num = 32;

	printf("Original number: %d\n", num);

	num = num >> 2; // Divide by 2^2 = 4

	printf("After division by 4: %d\n", num);

	return 0;
}

Inside the main() function:

- An integer variable num is initialized with the value 32.

- The original value of num is printed to the console.

- The num variable is right shifted by 2 bits using the `>>` operator, effectively dividing it by 4 (2^2).

- The result after division is printed to the console.



Featured Posts

Leetcode 4. Median of Two Sorted Arrays

  4. Median of Two Sorted Arrays Hard Given two sorted arrays  nums1  and  nums2  of size  m  and  n  respectively, return  the median  of t...

Popular Posts