Home > Backend Development > C++ > body text

C program to calculate the power of a given number

PHPz
Release: 2023-09-22 21:41:02
forward
906 people have browsed it

C program to calculate the power of a given number

Get two integers from the user as base and exponent and calculate powers as described below.

Example

Consider the following to write a C program.

  • Assume the base is 3
  • The exponent is 4
  • Power=3*3*3*3

Algorithm

Follow the algorithm given below:

Step 1: Declare int and long variables.
Step 2: Enter base value through console.
Step 3: Enter exponent value through console.
Step 4: While loop.
Exponent !=0
   i. Value *=base
   ii. –exponent
Step 5: Print the result.
Copy after login

Example

The following program explains how to calculate the power of a given number in C language.

#include<stdio.h>
int main(){
   int base, exponent;
   long value = 1;
   printf("Enter a base value:</p><p> ");
   scanf("%d", &base);
   printf("Enter an exponent value: ");
   scanf("%d", &exponent);
   while (exponent != 0){
      value *= base;
      --exponent;
   }
   printf("result = %ld", value);
   return 0;
}
Copy after login

Output

When the above program is executed, the following results are produced-

Run 1:
Enter a base value:
5
Enter an exponent value: 4
result = 625
Run 2:
Enter a base value:
8
Enter an exponent value: 3
result = 512
Copy after login

Example

If we want to find powers of real numbers , we can use the pow function, which is a predefined function in math.h.

#include<math.h>
#include<stdio.h>
int main() {
   double base, exponent, value;
   printf("Enter a base value: ");
   scanf("%lf", &base);
   printf("Enter an exponent value: ");
   scanf("%lf", &exponent);
   // calculates the power
   value = pow(base, exponent);
   printf("%.1lf^%.1lf = %.2lf", base, exponent, value);
   return 0;
}
Copy after login

Output

When the above program is executed, the following results are produced -

Enter a base value: 3.4
Enter an exponent value: 2.3
3.4^2.3 = 16.69
Copy after login

The above is the detailed content of C program to calculate the power of a given number. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!