how to calculate 2^7 in cpp code
To calculate 2^7 in C++, you can use the power function from the <cmath>
library. Here's the code snippet:
#include <iostream>
#include <cmath>
int main() {
int base = 2;
int exponent = 7;
int result = pow(base, exponent);
std::cout << "Result: " << result << std::endl;
return 0;
}
Let's break down the code step by step:
- Include the necessary header files:
cpp #include <iostream> #include <cmath>
<iostream>
is required to use thestd::cout
andstd::endl
for output.<cmath>
is required to use thepow()
function for calculating the power.Declare and initialize variables:
cpp int base = 2; int exponent = 7;
base
variable stores the base value (2 in this case).exponent
variable stores the exponent value (7 in this case).Calculate the power using the
pow()
function:cpp int result = pow(base, exponent);
- The
pow()
function takes two arguments:base
andexponent
. - It calculates the power of
base
raised to theexponent
and returns the result. The result is stored in the
result
variable.Print the result:
cpp std::cout << "Result: " << result << std::endl;
- The
std::cout
is used to print the result to the console. - The
<<
operator is used to concatenate the string "Result: " with the value ofresult
. The
std::endl
is used to insert a new line after printing the result.End the program:
cpp return 0;
- This statement ends the program execution and returns the value 0 to indicate successful execution.
By running this code, you will get the output:
Result: 128
This means that 2^7 is equal to 128.