218k views
25 votes
Col 1 Col2 Col 3

Row 1 23.1 13.58 14
Row 2 56.783 46.29 45.71
Write a program that accomplishes the following objectives:
1. reads in the number of rows, then the number of columns,
2. using nested FOR loops, reads in the column data for each row,
3. adds up the data for each row and derives an average for each row,
4 also adds up all the data in the table and derives an overall average.
Hints
1. Look at slides 3 and 4 of CS1336_Lect5e_nested_loops.pptx and Pr5-14.cpp for samples of nested FOR loops, especially line 38 in slide 4 for a calculation of average per student. That is very much like a row average.
2 Have two running total variables, for example rowsum and totalsum. Initialize totalsum to 0 in the beginning of the program Initialize rowsum to 0 before the inner loop (see line 29 in slide 4). Keep running totals for both of these inside the inner loop (see line 36 in slide 4). Average the rowSum after each iteration of the inner loop (see line 38 in slide 4). Average the totalsum after the outside loop ends
When the input is as shown in Figure 1. your program should produce the output as shown in Figure 2.
Figure 1: (sample input) 23 23.1 13.58 14 56.783 46.29 45.71
Figure 2 (sample output) Lverage of data in row #1 is 16.89 Average of data in row #2 is 49.59 Average of all data is 33.24

User KING SABRI
by
6.6k points

1 Answer

5 votes

Answer:

In C++:

#include<iostream>

using namespace std;

int main(){

int rows, cols;

cout<<"Rows: "; cin>>rows;

cout<<"Columns: "; cin>>cols;

int rowsum = 0; int totalsum = 0;

float nums[rows][cols];

for(int i = 0;i<rows;i++){

for(int j = 0;j<cols;j++){

cout<<"Row "<<i+1<<", Column "<<j+1<<": ";

cin>>nums[i][j];

rowsum+=nums[i][j]; totalsum+=nums[i][j];

}

cout<<"Average of row "<<i+1<<": "<<(rowsum*1.0/cols*1.0)<<endl;

rowsum = 0;

}

cout<<"Overall Average: "<<(totalsum*1.0)/(rows*cols*1.0);

return 0;

}

Step-by-step explanation:

This line declares number of rows and number of columns as integer

int rows, cols;

This line prompts user for number of rows

cout<<"Rows: "; cin>>rows;

This line prompts user for number of columns

cout<<"Columns: "; cin>>cols;

This line initializes rowsum and totalsum to 0, respectively

int rowsum = 0; int totalsum = 0;

This line declares a 2d array

float nums[rows][cols];

The following iteration gets user input into the array

for(int i = 0;i<rows;i++){

for(int j = 0;j<cols;j++){

cout<<"Row "<<i+1<<", Column "<<j+1<<": ";

cin>>nums[i][j];

This line sum up the rows

rowsum+=nums[i][j];

This line sum up each entry

totalsum+=nums[i][j];

}

This line calculates and prints the average of each row

cout<<"Average of row "<<i+1<<": "<<(rowsum*1.0/cols*1.0)<<endl;

rowsum = 0;

}

This line calculates and prints the overall average

cout<<"Overall Average: "<<(totalsum*1.0)/(rows*cols*1.0);

User Walt Jones
by
6.5k points