//Program using While Loop
#include <stdio.h> int main() { int base, exxp, poow, i; printf("Enter base value : "); scanf("%d", &base); printf("Enter power value : "); scanf("%d", &exxp); poow = 1; i = 1; while(i <= exxp) { poow=poow*base; i++; } printf("%d Power %d is: %d ", base, exxp, poow); return 0; }
Output: Enter base value : 2 Enter power value : 3 2 Power 3 is: 8
Code Analysis Power of a number is calculated by multiplying the number by itself, the number of times it is multiplied is decided by its power value. For example 23 power 2 will be calculated by multiplying 23 two times i.e., 23*23.
//Program using for loop
#include <stdio.h> int main() { int base, exxp, poow, i; printf("Enter base value : "); scanf("%d", &base); printf("Enter power value : "); scanf("%d", &exxp); poow = 1; for(i=1; i<=exxp; i++) { poow = poow *base; } printf("%d Power %d is: %d ", base, exxp, poow); return 0; }
Output: Enter base value : 23 Enter power value : 3 23 Power 3 is: 12167
Code Analysis This code calculates the power of a number using a for loop.
//Program using Pow function
<span style="font-weight: 400;">#include <stdio.h></span> <span style="font-weight: 400;">#include<math.h></span> <span style="font-weight: 400;">int main()</span> <span style="font-weight: 400;">{</span> <span style="font-weight: 400;"> int base,poow,res;</span> <span style="font-weight: 400;"> </span> <span style="font-weight: 400;"> printf("Enter the base ");</span> <span style="font-weight: 400;"> scanf("%d", &base);</span> <span style="font-weight: 400;"> </span> <span style="font-weight: 400;"> printf("Enter the power ");</span> <span style="font-weight: 400;"> scanf("%d", &poow);</span> <span style="font-weight: 400;"> </span> <span style="font-weight: 400;"> res=pow(base,poow);</span> <span style="font-weight: 400;"> </span> <span style="font-weight: 400;"> printf("%d Power %d is: %d ", base, poow, res);</span> <span style="font-weight: 400;"> return 0;</span> <span style="font-weight: 400;">}</span>
Output: Enter the base 2 Enter the power 3 2 Power 3 is: 8
Code Analysis This code use header file . “math.h” has an inbuilt function pow(base,exponent) base is the number which is multiplied by itself, the number of times it is multiplied depends on its exponent value.
Leave a Reply