Thursday, July 30, 2009

Take a look at my C++ program and tell my why it doesnt work. whats wrong with my program?

This program should count the numbers from 1 to the num(input number), but it doesnt work properly. I use Dev-C++ compiler.





Here is my program:





#include %26lt;stdio.h%26gt;


#include %26lt;iostream%26gt;





using namespace std;


int main()


{


int i,num,sum;


i=0;


cout%26lt;%26lt;"Please enter a number : \n";


cin%26gt;%26gt;num;


cin.get();


for (int num,sum,i; i%26lt;num;)


{


sum=sum+i;


}


cout%26lt;%26lt;sum;


system("pause");


return sum;


}

Take a look at my C++ program and tell my why it doesnt work. whats wrong with my program?
Your problem is in your for loop.





for (int num,sum,i; i%26lt;num;)





In this statement, you are creating a variable that is called num that only exists in your for loop block. You do not need the variable num declared in your for loop.





What is happening is that you read input from the user, and store it in a variable called num. Later on however you create a new variable called num in the new context (your for loop) and this new value of num has a default value of 0. As soon as you create it in the for loop, you no longer have access to the num value that you read data into.





Change it to:


for (int sum,i; i%26lt;num;)
Reply:when using namespace std:


#include %26lt;cstdio%26gt;





int num, sum = 0;


no "i" since you will be redeclaring it inside the loop


remove cin.get();


remove i = 0;


for (int i = 1; i %26lt; num; i++) sum += i;
Reply:This statement:





for (int num,sum,i ... )





re-declares those variables and they are visible only in your for loop. They are different variables than those in your main function. This is called variable shadowing. You can remove that first part of the for loop statement altogether.
Reply:try:





cin%26lt;%26lt;"Please enter a number : \n";


cout%26gt;%26gt;num;


cout.get();


for (int num,sum,i; i%26lt;num;)


{


sum=sum+i;


}


cin%26lt;%26lt;sum;


No comments:

Post a Comment