TimeLinux1

Tuesday, November 13, 2012

C Programing Examples - Power of a number.


The following program will calculate the power of a non negative integer to non negative power. Can be extended easily for negative powers by replacing multiplication by division in power function.

[root@MS-vaio C_Progs]# cat power.c
=====
#include <stdio.h>
main()
{
int a,b,c;
int powr (int x, int y);
printf("\n Please enter a positive integer and its power, separated by comma:");
scanf ("%d, %d",&a,&b);
c=powr(a,b);
printf("\n %d to the power %d is: %d \n",a,b,c);
}

///powr function starts here...
powr (int x, int y)
{
int i,j;
if (y==0)
    {
     return (1);
    }
if (y==1)
   {
return (x);
   }
else
   {
    j=x;
    for(i=2;i<=y;i++)
x=x*j;
        return (x);
    }
}
==========Sample Run======
[root@MS-vaio C_Progs]# gcc -o answ power.c
[root@MS-vaio C_Progs]# ./answ

 Please enter a positive integer and its power, separated by comma: 5, 5

 5 to the power 5 is: 3125 

No comments:

Post a Comment