C++ Primer Plus Chapter 5 Exercise 4

c plus plusExercise 4 wants us to loop through the months in a year and ask how many books we sold for a each month, then sum the total. I went with a string array initialized to the months. A simple for loop takes us through the year. Here is my solution:

4. You sell the book C++ for Fools. Write a program that has you enter a year’s worth of
monthly sales (in terms of number of books, not of money). The program should use a
loop to prompt you by month, using an array of char * (or an array of string objects, if
you prefer) initialized to the month strings and storing the input data in an array of int.
Then, the program should find the sum of the array contents and report the total sales
for the year.

#include <iostream>
#include <string>

using namespace std;

int main()
{
string month[12] = {"January","February ","March ","April ","May","June","July","August","September","October","November","December"};
int sales[12];
int sum = 0;

cout << "Enter sales for the month: " << endl;

for(int i = 0; i < 12; i++)
{
cout << month[i] << ": ";
cin >> sales[i];
sum=sum+sales[i];
};

cout << "Total sales for the year: " << sum << endl;

return 0;
}

Advertisements

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;

cin.get();
return 0;
}