Programming Example
Program to raise a floating point number to a positive integer by the iterative and recursive method
Program to raise a floating point number to a positive integer
#include<stdio.h>
float power(float a , int n);
float Ipower(float a , int n);
main( )
{
float a, p;
int n;
printf("Enter a and n : ");
scanf("%f %d", &a, &n);
p = power(a, n);
printf("%f raised to power %d is %f\n", a, n, p);
p = Ipower(a, n);
printf("%f raised to power %d is %f\n", a, n, p);
}/*End of main()*/
/*Recursive*/
float power(float a , int n)
{
if(n == 0)
return(1);
else
return(a * power(a,n-1));
}/*End of power()*/
/*Iterative*/
float Ipower(float a , int n)
{
int i;
float result=1;
for(i=1; i<=n; i++)
result = result * a;
return result;
}/*End of Ipower()*/
Enter a and n : 1.2
2
1.200000 raised to power 2 is 1.440000
1.200000 raised to power 2 is 1.440000
Press any key to continue . . .
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.