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:
We include the
<iostream>
library to use the input/output functions in C++.In the
main()
function, we declare two variables:power
andresult
.power
will keep track of the exponent value, andresult
will store the current power of 2.We start a
for
loop that will iterate from 0 to 10 (inclusive). You can adjust the loop range as per your requirement.Inside the loop, we output the value of
power
andresult
usingstd::cout
.We increment the
power
variable by 1 to move to the next exponent.We update the
result
variable by left shifting it by 1 (result = result << 1
). The left shift operator (<<
) effectively multiplies the number by 2.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.