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; }

13th Oct 2019, 5:42 PM
Kponyo John Djama Kofi
Kponyo John Djama Kofi - avatar
2 odpowiedzi
+ 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; }
13th Oct 2019, 5:48 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 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
17th Oct 2019, 3:27 AM
Wisam Ibrahim Hasan
Wisam Ibrahim Hasan - avatar