Calculate Power of a Number: C Program


Two numbers are entered through the keyboard. Write a program to find the value of one number raised to the power of another.

Related Read:
while loop in C programming

In this program, we ask the user to input values for base and exponent. We use while loop in this program. The while loop is executed “exponent” times. And inside while loop we multiply base value and output the result.

One Number Raised To Another: C Program


[youtube https://www.youtube.com/watch?v=bVhc7kuaJtM]

YouTube Link: https://www.youtube.com/watch?v=bVhc7kuaJtM [Watch the Video In Full Screen.]


Source Code:One Number Raised To Another: C Program

#include < stdio.h >

int main()
{
    int base, exponent, res = 1, temp;

    printf("Enter the base\n");
    scanf("%d", &base);

    printf("Enter the exponent\n");
    scanf("%d", &exponent);

    temp = exponent;

    while(exponent)
    {
        res = res * base;
        exponent--;
    }

    printf("%d to the power of %d is %d\n", base, temp, res);

    return 0;
}

Output:
Enter the base
5
Enter the exponent
4
5 to the power of 4 is 625

Note:
1. We are initializing value of variable res to 1 in order to make sure it doesn’t have garbage value in it. If it was an addition operation we could have assigned it a initial value of 0. But in above program we are doing multiplication. So multiplying any number with 0 will give 0 as result. So we initialize the value of variable res to 1.

2. We modify the value of variable exponent in while loop. So to preserve the user entered value for exponent, we take another variable temp and store the original number(exponent value) entered by the user.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

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