+ 1

conditionals and loops

i have a question int num = 1; int number; int total = 0; while (num <= 5) { cin >> number; total += number; num++; } cout << total << endl; why int total = 0 ? then how total += number is work? and please explain how loop like this workin? im really confused to understand this one thanks..

27th Apr 2017, 2:16 AM
agung pramudji
agung pramudji - avatar
5 Respostas
+ 6
int total = 0; we should always initialise variables that are going to be used for caculations so they will never be null/empty when we use them. total+=number is the same as saying total = total + number the while loop while(num<=5) repeats the code between its { } brackets until the variable num is equal to or greater than 5. as you can see each time the loop is run num is incremented by 1 using num++ is this better?
27th Apr 2017, 2:34 AM
jay
jay - avatar
+ 5
ooo i see what you are asking now. please i will try again.
27th Apr 2017, 2:28 AM
jay
jay - avatar
+ 2
try: int num, number, total; num = 1; total = 0;
27th Apr 2017, 2:20 AM
jay
jay - avatar
+ 1
it is same, right?
27th Apr 2017, 2:22 AM
agung pramudji
agung pramudji - avatar
+ 1
jay i really appreciate your help, its make me more understand thank you so much
27th Apr 2017, 2:42 AM
agung pramudji
agung pramudji - avatar