+ 1
Loop
#include <iostream> using namespace std; int main() { int num = 1; int number; int total = 0; while (num <= 5) { cin >> number; total += number; num++; } cout << total << endl; return 0; } Please who can explain this code
1 Answer
+ 4
The loop executes 5x (1 - 5).
1 <= 5 true -> execute loop
get user input //e.g. 1
total += number //total = 0 + 1 = 1
increment num //2
2 <= 5 true
user input //e.g. 2
total += number //total = 1 + 2 = 3
num++ //3
3 <= 5 true
user input //e.g. 3
total += number //total = 3 + 3 = 6
num++ //4
4 <= 5 true
user input //e.g. 4
total += number //total = 6 + 4 = 10
num++ //5
5 <= 5 true
user input //e.g. 5
total += number //total = 10 + 5 = 15
num++ //6
6 <= 5 false -> end loop
print total -> output 15
On sololearn you have to enter all values at the beginning (enter 5 values).