+ 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..
5 Réponses
+ 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?
+ 5
ooo i see what you are asking now. please i will try again.
+ 2
try:
int num, number, total;
num = 1;
total = 0;
+ 1
it is same, right?
+ 1
jay i really appreciate your help, its make me more understand
thank you so much