C Program to Calculate the Power of a Number

by | Jan 30, 2023 | C, C Programs

Home » C » C Programs » C Program to Calculate the Power of a Number

Introduction

In this example, we will explore calculating the power of a number.

The user will be asked to enter an integer as the base value and the power value which will be the exponent of the base number.

For example, 9 raised to the power 3 means 9*9*9=721, where 9 is the base value and 3 is the exponent.

To understand the program, you should know about

1. Operators in C

2. while and do while loop in C

Program

#include<stdio.h>

int main()

{

float b; // b is base number

printf("Enter a base number\n");

scanf("%f",&b);




int p; // p is the power or exponent

printf("Enter an exponent\n");

scanf("%d",&p);




float result=1;

while(p!=0) //condition

{

result=result*b;

p--;

}

printf("Result = %.2f",result);

return 0;

}

 

Output

Explanation

‘b’ is the variable for the base number and ‘p’ is the power of the base number.

float result=1;

To store the final result variable ‘result’ is initialized with 1.

while(p!=0)

If the above condition gives a true result then the body of the while loop is executed.

Since ‘p’ is 3 thus the condition becomes true and the value of the base entered by the user is 9.2 therefore,

result=result*b; it will assign 1*9.2 i.e., result=9.2000

p–; ‘p’ gets decremented to 2

the condition becomes true for p=2 thus,

result=result*b; it will assign 9.2000*9.2 i.e., result=84.6400

p–; ‘p’ gets decremented to 1

the condition becomes true for p=1 thus,

result=result*b; it will assign 84.6400*9.2 i.e., result=778.6880

p–; ‘p’ gets decremented to 0

the condition becomes false for p=0 thus,

the final result is 778.6880

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author