In this article we will see program to compute x to the power n using while loop in C Programming. To understand this program, you must have basic knowledge of c programming.
main()
{
int count, n;
float x, y;
printf("Enter the values of x and n : ");
scanf("%f %d", &x, &n);
y = 1.0;
count = 1; /* Initialisation */
while ( count <= n) /* Testing */
{
y = y*x;
count++; /* Incrementing */
}
printf("\nx = %f; n = %d; x to power n = %f\n",x,n,y);
}
Output:{
int count, n;
float x, y;
printf("Enter the values of x and n : ");
scanf("%f %d", &x, &n);
y = 1.0;
count = 1; /* Initialisation */
while ( count <= n) /* Testing */
{
y = y*x;
count++; /* Incrementing */
}
printf("\nx = %f; n = %d; x to power n = %f\n",x,n,y);
}
Enter the values of x and n : 2.5 4
x = 2.500000; n = 4; x to power n = 39.062500
Enter the values of x and n : 0.5 4
x = 0.500000; n = 4; x to power n = 0.062500
x = 2.500000; n = 4; x to power n = 39.062500
Enter the values of x and n : 0.5 4
x = 0.500000; n = 4; x to power n = 0.062500
C program to find power of a number using pow() function :
To calculate power of a number using pow() function, it requires to add "#include <stdio.h>" library.
Syntax of pow function in c programming language is as below. Which calculate the result of x raised to power of y.
double pow(double x, double y);
#include <stdio.h>
#include <math.h>
int main()
{
double basenumber, result, exponent;
printf("Please enter a base number: ");
scanf("%lf \n", &basenumber);
printf("Please enter an exponent: ");
scanf("%lf \n", &exponent);
result = pow(basenumber, exponent);
printf("%.1lf^%.1lf = %.2lf", basenumber, exponent, result);
return 0;
}
Output:#include <math.h>
int main()
{
double basenumber, result, exponent;
printf("Please enter a base number: ");
scanf("%lf \n", &basenumber);
printf("Please enter an exponent: ");
scanf("%lf \n", &exponent);
result = pow(basenumber, exponent);
printf("%.1lf^%.1lf = %.2lf", basenumber, exponent, result);
return 0;
}
Please enter a base number: 2
Please enter an exponent: 4
2^4 = 16
Please enter an exponent: 4
2^4 = 16
0 Comments