correct the mistake

sum=0;
while(cout<20)
cin>>num;
sum=sum+num;
count++;

can someone fix it so that it finds the sum of 20 numbers
Next time, at least post what exactly is going wrong. Are there errors? If so, which ones? Is it outputting the wrong value? Is it simply not accepting input?

Anyway, I'm assuming this is just an excerpt since you're missing declarations, includes and a namespace. So here goes:

a) Your loop is lacking encapsulation; only cin>>num is being executed 20 times, the rest only once after the while ends. I'm guessing the final value of sum is equal to the first number you type in?
b) Maybe just a typo but it should be "while(count<20)", not cout.
c) Adding additional values to a total is more efficient in this form: "sum+=num" ("add num to sum").
d) Since you're using a fixed number of iterations, you're better off with a for loop.
e) Not entirely sure, but I've always heard that "++i" is more efficient than "i++" since no copying is done.



Fix like this:
1
2
3
4
5
sum = 0;
for(int count = 0; count < 20; ++count) {
  cin >> num;
  sum+=num;
}
Last edited on
I was just wondering it was the exact same code that was on my exam and it asked us to correct it so it finds the sum of 20 numbers

thanks for the help
Well now I regret answering.
The variable in the while(cout<20) cout must be couNt that's number 1
2-You are missing an initialization for count you must have int count =0; somewhere that is the mistake!
so it must be like this:
1
2
3
4
5
6
sum=0;
count=0; // This was missing!
while(count<20) //changed cout to count!
cin>>num;
sum=sum+num;
count++;

Topic archived. No new replies allowed.