C++ Primer Plus Chapter 5 Exercise 5

c plus plusExercise 5 is a remake of exercise 4, except this time we introduce a two dimensional array into our loops. The purpose of this is to fill it first with years then months. This way, the program will iterate through 12 months for 3 years. See the source below for the solution.

5. Do Programming Exercise 4, but use a two-dimensional array to store input for 3 years
of monthly sales. Report the total sales for each individual year and for the combined
years.

#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[3][12];
int yearTotal;
int sum = 0;
int total = 0;
int everything = 0;

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

for(int y = 0; y < 3; y++)
{
for(int m = 0; m < 12; m++)
{
cout << month[m] << ": ";
cin >> sales[y][m];
sum=sum+sales[y][m];
total=sum;

}

}

for(int y = 0; y < 3; y++)
{
yearTotal = 0;
for(int m =0; m < 12; m++)
{
cout << month[m] << sales[y][m] << endl;
yearTotal+=sales[y][m];
everything+=sales[y][m];
}

cout << "Sales for this year: " << yearTotal << endl;
}

cout << "The data for all years: " << everything << endl;

return 0;
}

Advertisements

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

  1. #include
    #include
    using namespace std;

    int main() {

    string months[12] = {“January”,”February”, “March”, “April”, “May”, “June”,”July”, “August”, “September”, “October”,”November”, “December”};

    int yearly[3][12];

    int sum_of_year1=0;

    int sum_of_year2=0;

    int sum_of_year3=0;

    for( int i =0; i <3; i++){
    cout<< "Sales for year " << i+1 << endl;
    for(int j=0; j < 12; j++){

    cout << months[j] <> yearly[i][j];

    if(i==0){

    sum_of_year1=sum_of_year1+yearly[i][j];

    }

    else if(i==1){
    sum_of_year2=sum_of_year2+yearly[i][j];
    }

    else if (i==2){

    sum_of_year3=sum_of_year3+yearly[i][j];
    }
    }

    cout << endl;

    }

    cout << "first year " << sum_of_year1 << endl;

    cout << "second year " << sum_of_year2 << endl;

    cout << "Third year " << sum_of_year3 << endl;

    cout << "The total sum " << sum_of_year1 + sum_of_year2 + sum_of_year3 << endl;

    return 0;

    my code(me being lazy) i put in if- statements to get sum of each year based on summing up each rows

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