Google Add

Search

C Program to Calculate Power of a Number using For & While Loop

Write a c program to calculate power of a number using for & while loop without using inbuilt pow() function.

In this tutorial, You are going to learn  how to calculate power of a number without using pow() function. In this program, we take two numbers (base and exponent) as an input from a user and calculate it's result which is (baseexponent).

For example -

Input number (base) : 2

Input power (exponent) : 3

Result : 23 = 8 (2 * 2 * 2).






C Program to Calculate Power of a Number

C Program to Calculate Power of a Number


In this program, we take an input number and it's power from a user. Then in our code we run a loop from 1 to the value of power and calculate it's result.


#include <stdio.h>

int main(void) {
 
   int num, pow, result = 1, count = 1;
 
   printf("Enter a number \n");
   scanf("%d", &num);
 
   printf("Enter the power of a number\n");
   scanf("%d", &pow);
 
   // If a count is less than pow
 
   while(count <= pow) {
     //Multiply the number and assign to result
     result = result * num;
     count++;
   }
 
   printf("Result = %d", result);
 
   return 0;
}

Output -

Enter a number     2

Enter the power of a number    3

Result = 8

C interview questions with answers

C Program to Calculate Power of a Number using For Loop


#include <stdio.h>

int main(void) {
 
   int num, pow, result = 1;
 
   printf("Enter a number \n");
   scanf("%d", &num);
 
   printf("Enter the power of a number\n");
   scanf("%d", &pow);
 
   /* Using for loop,
      Initialize i to 1
      Termination condition (i is less than equal to pow)
    */
   for(int i = 1; i <= pow; i++) {
      //Multiply the number and assign to result
      result = result * num;
   }
 
   printf("Result = %d", result);
 
   return 0;
}




C program to print factorial of a number

C program to count number of vowels in a string

C program to print fibonacci series

No comments:

Post a Comment