C++ Primer Plus Chapter 5 Exercise 1

c plus plusThe beginning of chapter 5 switches gears and finally officially introduces us to loops. Exercise 1 requires we write a loop to sum all numbers between two user supplied variables. Here is my solution:

1. Write a program that requests the user to enter two integers. The program should then
calculate and report the sum of all the integers between and including the two integers. At this point, assume that the smaller integer is entered first. For example, if the user enters 2 and 9, the program should report that the sum of all the integers from 2 through 9 is 44.

#include <iostream>;

using namespace std;

int main()
int a, b;
int c = 0;

cout << "Enter 1st integer, lower:" ;
cin >> a;
cout >> "Enter 2nd integer, higher: ";
cin >> b;

for(int n = a; n = b; n++)
c = c+n;

cout << "The sum of all numbers between: " << a << "and" << b << "is" << c << endl;

return 0;

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