Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
C++
//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 exponent, I get an irrevelant answer. For example, when I type 2 for base and 3 for exponent, instead of getting 8, I get a number with many digits. Please help me. Thanks.
Posted
Updated 2-Jun-15 5:26am
v2
Comments
[no name] 2-Jun-15 11:12am    
Probably for the exact same reason as your other homework assignment. Learning to debug your code is also a valuable skill.
Richard MacCutchan 2-Jun-15 11:29am    
What is the value of c before the for loop starts inside your power method. A quick desk check should reveal basic errors like that.
Member 11735960 2-Jun-15 11:32am    
Yes. I have now initialized the value of c=1 and got the right answer. But, since I am a beginner, I don't understand how the value of variable c is something else. Can I get an explanation on that. Thanks.
CHill60 2-Jun-15 12:01pm    
Richard MacCutchan 2-Jun-15 12:03pm    
If you don't initialise it to some value then it will just contain some random data which means your program will produce rubbish. You must initialise all your variables before you try to do anything with them.

1 solution

In C/C++ a variable that not initialized has undefined value...The reason is that the memory block used to store the variable (the variable name is actually a pointer to a memory address) may had used in the past by other variables and never cleaned...
So if the initial value of a variable is important (like in your case) you have to do that initialization...
In Microsoft compilers setting warning level to 4 will alert you about potentially uninitialized variables...
In GCC you may use -Wmaybe-uninitialized to do the same...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900