0
why does my c++ code below results to 35 instead of 25...?
#include <iostream> using namespace std; int main() { int num = 1; int n = 0; while (num < 10) { cout << "Number: " << num << endl; num = num + 2; n = n+num; } cout << "Total = " << n; return 0; }
2 ответов
+ 4
Lets modify your code little bit as you are adding num to n after modification in value of n not before modification in its value
See output for below code(see values of num getting printed) to get why result is coming 35.
#include <iostream>
using namespace std;
int main()
{
int num = 1;
int n = 0;
while (num < 10) {
num = num + 2;
cout << "Number: " << num << endl;
n = n+num;
}
cout << "Total = " << n;
return 0;
}
+ 1
Your program is perfect, but since you used "while " for checking condition ; the last check when num greater than 10 will be included. So just change the line of condition to the following:
While (num < 9)
You will get the right output 25