<//To find the power of a number
#include<stdio.h>
#include<conio.h>
int power(int a,int b);
int main()
{ clrscr();
int a,b;
printf("\nEnter the base:");
scanf("%d",&a);
printf("\nEnter the power:");
scanf("%d",&b);
printf("\nThe answer is:%d",power(a,b));
getch();
return 0;
}
int power(int x,int y)
{ int c;
for(int i=1;i<=y;i++)
c*=x;
return c;
}>
When I enter the base and power, I get an irrelevant answer. For example, when I enter 2 for base and 3 for exponent, instead of getting 8, I get some other number with many digits. Please help me. Thanks.
You don't set the value of c before your loop so it is set to some random value. It is also good practice to use braces for all loops (even one line loops) and the use prefix increment.
@4683
Thanks for all of your useful replies. I have solved the problem. But since I am a beginner, I don't understand why the value of variable c is something else. I will try to find that out. Thanks.
Until you set the value of a variable for the first time, it isn't set to any specific value, in fact is it set to a random value, as I said. Also 4683 is the number of posts, not the username.