Write a Program in C to evaluate raised to the power
/*Using While Loop*/
#include<stdio.h>
void main()
{
int a, b, i, p;
printf("Enter value of a: ");
scanf("%d",&a);
printf("Enter value of b: ");
scanf("%d",&b);
p=1;
i=1;
while(i<=b)
{
p = p * a;
i++;
}
printf("%d to the power %d is : %d",a,b,p);
}
/*Using For Loop*/
#include<stdio.h>
void main()
{
int a, b, i, p;
printf("Enter value of a: ");
scanf("%d",&a);
printf("Enter value of b: ");
scanf("%d",&b);
p=1;
for(i=1;i<=b;i++)
p = p * a;
printf("%d to the power %d is : %d",a,b,p);
}
/* Using Function */
#include <stdio.h>
#include <conio.h>
double power(int, int);/*PROTOTYPE*/
void main( )
{
int x,y;
printf("Enter value of a: ");
scanf("%d",&x);
printf("Enter value of b: ");
scanf("%d",&y);
printf("%d to the power %d is : %f\n", x,y,power (x,y));
getch();
}
double power (int x, int y) /*FUNCTION DEFINITION*/
{
double p;
p = 1.0 ; /* X to the power 0 */
if(y >=0)
while(y--) /* positive powers */
p *= x;
else
while (y++) /* negative powers */
p /= x;
return(p); /* returns double type */
}
Comments
Post a Comment