Reputation: 69
I am trying to write a program in which a user will be prompted to enter an integer 3 times. After each integer, a sum will be displayed after the input. Then, with the second and third integers, the numbers should be added onto the initial sum within a loop. Here is what I have done:
#include <iostream>
using namespace std;
int main () {
double number=0, total=0;
for (double n=0; n<3; n++){
cout << "Enter an integer: ";
cin >> number;
cout << "Sum is: " << number <<endl;
total+=number; }
}
This is the output so far:
Enter an integer: 2
Sum is: 2
Enter an integer: 3
Sum is: 3
Enter an integer: 4
Sum is: 4
The goal is for the integers to continue to add to the sum until the loop is done. This is the output that I am trying to achieve:
Enter an integer: 2
Sum is: 2
Enter an integer: 3
Sum is: 5
Enter an integer: 4
Sum is: 9
Any help would be appreciated, as I am confused on how to solve this part, and it is the only part I need to figure out in order to complete it. Thanks for taking the time to read this!
Upvotes: 0
Views: 787
Reputation: 1156
cout << "Sum is: " << number << endl;
In this line you are printing the current number, not the total. You need to use total
instead.
Also move total += number;
before the previous line. Else you will be one step behind when displaying.
Thus your code should look like this:
#include <iostream>
using namespace std;
int main () {
double number=0, total=0;
for (double n=0; n<3; n++){
cout << "Enter an integer: ";
cin >> number;
total+=number;
cout << "Sum is: " << total << endl;
}
}
Upvotes: 2