C++ Primer Plus Chapter 5 Exercise 2

c plus plusExercise 2 ask us to write a loop that does not terminate until it sees a zero. A Do-While loop will best serve our interest for this exercise. The loop will sum all user inputted integers until a zero is inputted. Here is my solution:

2. Write a program that asks the user to type in numbers. After each entry, the program
should report the cumulative sum of the entries to date. The program should terminate
when the user enters 0.

#include <iostream>

using namespace std;

int main()
{
int number;
int sum = 0;

do
{
cout << "Enter numbers: ";
cin >> number;

sum = sum + number;
cout << "Current sum is: " << sum << endl;
}
while (number != 0);

return 0;
}
Advertisements

One thought on “C++ Primer Plus Chapter 5 Exercise 2

  1. I went with a simple ‘while’ loop as I wanted to check the cin prior to running the statement.

    [code]
    #include

    using namespace std;

    int main()
    {
    cout << "Enter a number, press " << endl;
    cout << "Press 0 to end program" << endl;;
    cout <> a;

    while (a != 0)
    {
    total += a;
    cout <> a;
    }
    cout << "total = " << total << endl;
    }
    [code\]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s