powers of 2 in cpp

To calculate powers of 2 in C++, you can use the bitwise left shift operator (<<). Here is an example:

#include <iostream>

int main() {
    int power = 0;
    int result = 1;

    for (int i = 0; i <= 10; i++) {
        std::cout << "2^" << power << " = " << result << std::endl;
        power++;
        result = result << 1;
    }

    return 0;
}

Explanation of each step:

  1. We include the <iostream> library to use the input/output functions in C++.

  2. In the main() function, we declare two variables: power and result. power will keep track of the exponent value, and result will store the current power of 2.

  3. We start a for loop that will iterate from 0 to 10 (inclusive). You can adjust the loop range as per your requirement.

  4. Inside the loop, we output the value of power and result using std::cout.

  5. We increment the power variable by 1 to move to the next exponent.

  6. We update the result variable by left shifting it by 1 (result = result << 1). The left shift operator (<<) effectively multiplies the number by 2.

  7. After the loop finishes, the program will exit with a return value of 0.

This program will output the powers of 2 from 2^0 to 2^10. You can modify the loop range or customize the output format as per your needs.