C program using function

What is wrong with this C program using function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<//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.
Last edited on
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.
Last edited on
On line 17: Initialze c with 1: int c = 1;
@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.
Last edited on
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.
Topic archived. No new replies allowed.