Calculate X^n where n can either be zero, a positive integer or negative integer.

#include <stdio.h>

int main(void)
{
int base, index, tmp;
float res = 1.0;

printf("\nEnter the base and index :");
scanf("%d%d",&base, &index);

tmp = index;

/* First method using a simple if() condition */
if(index < 0)
index *= -1;
else if(index == 0)
res = 0;

do
{
res *= base;
index--;
}while(index > 0);

/* Second method using a while() loop that runs either way */
/*
do
{
res *= base;
if(index > 0) index--;
else index++;
}while(index != 0);
*/

if(tmp < 0)
{
res = 1 / res;
}

printf("\n%d raised to %d is %f", base, tmp, res);


return 0;
}

No comments:

Post a Comment

kiss on google ads if you are anonymous because your ip is trackable.thank you.

......from.admin