This C program calculates the power of a base number raised to an exponent entered by the user, using the pow()
function from the math.h
library.
It prompts the user to enter the base number and exponent using printf()
and scanf()
, respectively. It then uses the pow()
function to calculate the power of the base number raised to the exponent and stores the result in the result
variable.
After that, it displays the final result using printf()
statement.
#include <stdio.h>
#include <math.h>
int main()
{
int base_number, exponent, result;
printf("Enter the Base Number: \n");
scanf("%d", &base_number);
printf("Enter Exponent: \n");
scanf("%d", &exponent);
result = pow(base_number, exponent);
printf("%d to the Power of %d is: %d \n", base_number, exponent, result);
return 0;
}
Result:
Enter the Base Number:
10
Enter Exponent:
3
10 to the Power of 3 is: 1000
Process returned 0 (0x0) execution time : 2.725 s
Press any key to continue.
Here's an explanation of the code line by line:
#include <stdio.h>
#include <math.h>
These two lines include the standard input-output library and the math library in C programming.
int main()
{
int base_number, exponent, result;
This is the main function of the program. It declares three integer variables: base_number
, exponent
, and result
.
printf("Enter the Base Number: \n");
scanf("%d", &base_number);
printf("Enter Exponent: \n");
scanf("%d", &exponent);
These printf()
statements display prompts for the user to enter the base_number
and exponent
values respectively. The scanf()
function reads in integer values for these variables from the user input using the %d
format specifier.
result = pow(base_number, exponent);
This line uses the pow()
function from the math.h
library to calculate the power of the base_number
raised to the exponent
. The pow()
function returns a double
value, which is then stored in the integer variable result
.
printf("%d to the Power of %d is: %d \n", base_number, exponent, result);
return 0;
}
This printf()
statement displays the final result of the calculation, which is the base_number
raised to the exponent
, using the %d
format specifier to print integer values. The program ends with a return value of 0.
No comments:
Post a Comment