Lowest price ever! Learn Generative AI for 48% less!
Get my discount0
Why does it give different answer for the following code?
int num = 1; int total = 0; while (num <= 5) { cin >> num; total += num; num ++; } cout << "Total = " << total << endl; return 0; } I entered five numbers which are 1, 7, 6, 8, 9 the answer should be 31 right but why does it output total = 8 someone please help
5 Answers
+ 2
your while loop is checking if num <= 5, when you enter 1, the first loop 1<=5, the second time you enter 7, then increment num, 7+1 = 8. 8 is not less than or equal to 5 so your loop exits and you get 8.
instead I think you might want a for loop.
try
int num = 0;
int total = 0;
for (int i=0; I <=5; i++)
{
cin >> num;
total += num;
}
cout << "Total = " << total << endl;
return 0;
that will let you enter 5 numbers and then add them together
+ 1
yes I see, originally you had num used twice instead of number and num.
that cause you to check against the wrong variable. The latest post should work :)
0
sorry, updated it a little to remove the unnecessary parts for your basic example
0
thanks.
but I found out that when I use the code of c++ lesson which is -
int num = 1;
int number;
int total = 0;
while (num <= 5)
{
cin >> number;
total += number;
num++ ;
}
cout << " Total = " << total << endl;
return 0;
}
giving number 1, 7, 6, 8, 9
And
The output was 31
maybe i made syntax error by not writing
int number;
in the code of my previous question.
If so, please make me sure about that.
0
thank you