Saturday, May 22, 2010

Please help with the error in my C++ "while" statement?

Hi- I am trying to correct the errors in the following code. I don't know exactly what it is supposed to accomplish, but I assume it needs to show a count from 1 - 10.





#include %26lt;iostream%26gt;





using namespace std;





int main ()


{





int n = 0;


int sum;





while (n %26lt;= 10)


{


sum = sum + n;


n++;


}





return 0;





}











When I try to compile, it keeps telling me that "uninitialized local variable 'sum' used" but I don't know what the variable for sum should even be. Sorry for asking such a broad question, I am stumped trying to learn this stuff.





Thanks

Please help with the error in my C++ "while" statement?
if u want to show the output where is the output commands
Reply:change "int sum;" to "int sum= 0;" or any number you need,
Reply:#include %26lt;iostream%26gt;





using namespace std;





int main ()


{





int n = 0;


int sum=0;





while (n %26lt;= 10)


{


sum = sum + n;


n++;


}





return sum;





}








Calulate the sumation from 1 to 10.
Reply:I will go into some detail...





Memory is "dirty". That means that every memory location contains random data. This data may be left over from programs that have just finished running. When a program exits, it usually doesn't "clean up" memory by setting everything to 0.





When you declare a variable, (int sum;), you're saying "give me a bit of memory big enough for an integer and label it 'sum' for me". The memory allocated to sum could come from anywhere and more than likely, will be "dirty". So sum will have a random value in it that will be interpreted by your program as an integer.





To make sure your variables have sensible values in them, you need to initialise them. so typing...





int sum = 0;





gives sum a known initial (first) value (0).





Hope that helps!!
Reply:You should change





int sum;





to





int sum = 0;





sum will hold the sum of the numbers from 1 to 10
Reply:it's because sum has nothing to begin with, I wont go into more detail but,


change





int sum;


to


int sum = 0;





and add:


cout %26lt;%26lt; n %26lt;%26lt; endl;


to actually see something happen


No comments:

Post a Comment