0
Pls...
int num = 1; int number; int total = 0; while (num <= 5) { cin >> number; total += number; num++; } cout << total << endl; /* what do num and number mean here.if i input 5,how the output is 25? */
2 Answers
+ 6
In this code, num is your loop counter (counts the iterations of the loop so it can exit once it meets condition). number is the variable that you're actually using for your calcuations. total is where your'e storing the result of the calculation.
So in this code, it'll iterate 5 times. Your calculation for each loop iteration is 5 + 5 (to get total). Since the loop runs 5 times, you get 5 + 5 + 5 + 5 + 5, which equals 25.
Note that my info to you is based upon the input value of 5 that you entered. Obviously, the numbers will change depending upon the input value given by user.
+ 1
Here's simplified version:
int total = 0; // variable for the sum
for (int i=1; i<=5; i++) { // repeat 5 times
int number; // variable for user input
cin >> number; // get a number from the user
total += number; // add the number to the sum
}
cout << total << endl; // print out the sum