C program to find the power of a number
This C program is to find power of a number.For example if base is 2 and exponent is 3 then the power of a number is 23 = 8.
Logic
We iterate till our exponent is 1 and keep multiplying the base with power which is initialized to 1 at the start of the program.
Dry Run of the Program
Take input ‘base’ and ‘exponent’ .Let us take base=2 and exponent=3
1st iteration while(e>0) i.e. while(3>0)
power=power*b i.e. power=1*2 hence power=2
e–; i.e. e=2
3rd iteration while(e>0) i.e. while(2>0)
power=power*b i.e. power=2*2 hence power=4
e–; i.e. e=1
3rd iteration while(e>0) i.e. while(1>0)
power=power*b i.e. power=4*2 hence power=8
e–; i.e. e=0
While Loop ends here as e=0.
We get power of 23 = 8.
Program
#include<stdio.h> void main() { int b,e,power=1; printf("Enter the base\n"); scanf("%d",&b); printf("Enter the exponent\n"); scanf("%d",&e); while(e>0) { power=power*b; e--; } printf("The power of the no = %d",power); }