While loops | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

While loops

#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; } I can't seem to wrap my head around this one Can someone try and explain it to me simple terms ? Thanks Harry

23rd Aug 2018, 1:31 PM
harry
2 Answers
+ 2
difficult to explain without knowing what exactly you dont understand, so i will explain all of it actions inside the while loop will be repeating as long as loop condition is true. In this case, variable "num" must be lower or equal to 5 (num <= 5). Loop condition is checked on entering the loop, and at the end of the loop. Condition met - loop repeats. Not met - code ahead of loop executes this exact loop on each itteration runthrough asks user to input a number and saves it to variable "number" (cin>>number). It then adds this number to the "total" variable (total += number), and adds 1 to the "num" (num++) this will repeat 5 times, at which point "num" will become 6, and the program will execute "cout<<total<<endl", displaying the value of the variable "total"
23rd Aug 2018, 1:54 PM
Data
Data - avatar
+ 2
If compiled on pc, on "cin>>number" program would stop and wait for input, but since in sololearn you can only enter input before running the program, if you only entered, for example, 10, it will use 10 in all of the imput requests if you enter 10, then this 10 will be added to "total" 5 times, resulting in "total" being 50
23rd Aug 2018, 1:56 PM
Data
Data - avatar