Finding the average of individual rows and columns in random array - c++

I've got to make a program that creates a 10x10 array of random numbers 0-9 and find the average of each individual row and column and also the whole array. I've got the array right but i'm stuck on how to select a single row or column then find the average of it, any tips?
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const int numRows = 10;
const int numCols = 10;
int val[numRows][numCols];
int i, j;
double sum = 0, avgR, avgC;
void randNum() // Creates 10x10 array of random nums 0-9
{
srand(2622); // random seed
for (i = 0; i < numRows; i++) // Creates random rows
{
cout << endl << endl;
for (j = 0; j < numCols; j++) // Creates random columns
{
val[i][j] = rand() % 10;
cout << setw(6) << val[i][j];
}
}
cout << endl << endl;
}
void randAvg() // finds average of each row and column
{
for (i = 0; i < numCols; i++)
{
sum += val[i][j];
}
avgR = sum / numRows;
cout << " " << avgR << endl;
}
int main() // calls each function
{
randNum();
randAvg();
}

A two dimensional array has a row and a column. When you access each elements of such an array in a loop,it is better to reflect that structure with your loops.
So this in your code:
for (i = 0; i < numCols; i++)
{
sum += val[i][j];
}
Is trying to access a single column(given by j) in each row(given by i) of your array
Since the value of j is now made 10 by the call to the randNum() function, you are accessing one element past your array (technically this happens when you are at the last row) which is not good. That is why it's not a good idea to use global variables to share information between functions.
With these:
//assuming sum and avgR are declared
//average of a row
for (int i = 0; i < numRows; i++)//iterate each row(one loop for the row)
{
sum=0;//reset sum for each row
for (int j = 0; j < numCols; j++)//iterate each column in each row(one loop for the column)
sum += val[i][j];//will sum up the contents of the current row
avgR=sum/numCols;//give you the average of each row
}
//average of a column
for (int j = 0; j < numCols; j++)//iterate each column
{
sum=0;//reset sum for each column
for (int i = 0; i < numRows; i++)//iterate each row for each column
sum += val[i][j];//will sum up the contents of the current column
avgR=sum/numRows;//give you the average of each column
}
Am i sure you will be able to figure out how to get the average of the whole array.

In either case, you will have to iterate over all array entries. While building the column average, you iterate over each column and in each iteration, you iterate over all rows, computing the average.
During the row average, you iterate over all rows and in each iteration compute the average over all columns:
void randAvg()
{
for (int i = 0; i < numCols; i++)
{
float sum = 0.f;
for (int j = 0; j < numRows; j++) {
sum += val[i][j];
}
float avg = sum / numRows;
cout << "Average of column " << i << ": " << avg << endl;
}
for (int i = 0; i < numRows; i++)
{
float sum = 0.f;
for (int j = 0; j < numCols; j++) {
sum += val[j][i];
}
float avg = sum / numRows;
cout << "Average of row " << i << ": " << avg << endl;
}
float sum = 0.f;
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numCols; j++) {
sum += val[j][i];
}
}
float avg = sum / (numRows*numCols);
cout << "Overall average: " << avg << endl;
}
Disclaimer: Untested code, should work though.

Related

How to create a 2D array and calculate the average of it?

THE PROBLEM
Create a 4X3 integer array and fill it, column by column, with the odd numbers starting with 1. In a separate, one dimensional array, store the average of each column of the 4X3 array. Output the 4X3 array (as a 4X3 array) and output the average of each column underneath each column. Label these as the average.
#include <iostream>
using namespace std;
int main() {
// variables defined here
int i, j, A[4][3], average[3], sum = 0, oddnumber = 1;
for(i = 0; i < 3; i++) {
for(j = 0; j < 4; j++) {
A[j][i] = oddnumber;
oddnumber = oddnumber + 2;
sum = sum + A[j][i];
}
average[i] = sum / 4.0;
sum = 0;
}
// output
cout << "The Array is: \n";
for(i = 0; i < 4; i++) {
for(j = 0; j < 3; j++) {
cout << A[i][j] << "\n";
}
}
cout << "Average: \n";
for(i = 0; i < 3; i++) {
cout << average[i] << "\n";
}
}
When I run the program, the values does not appear in a table (2D array) but in one column only.
You get one column only because you output a newline (\n) after each number.
for(i = 0; i < 4; i++) {
for(j = 0; j < 3; j++) {
cout << A[i][j] << "\n"; // here
}
}
Instead, output the newline after each row has been printed. You may also want to insert a tab (\t) or space between the numbers in each row to not get a very long number as output:
for(i = 0; i < 4; i++) {
for(j = 0; j < 3; j++) {
std::cout << A[i][j] << '\t'; // a tab after each number in the row
}
std::cout << '\n'; // newline after the row is done
}

How do I set all the diagonals in a matrix equal to zero?

I have a problem with my homework that asks me to have the compiler print out a matrix in which all the diagonals are outputted as zero. I also have to pass it to a function. However, I have no idea how to do this..
Here is my code:
#include <iostream>
using namespace std;
int diagonals();
int main()
{
//problem 1
int matrix[3][3];
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3 ; j++)
{
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
cout << "\nReverse of the matrix:" << endl;
for (int j = 1; j <= 3; j++)
{
for (int i = 1; i <= 3; i++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}//end of problem 1
//problem 2
cout << "Diagonals changed to 0:\n" << endl;
}
your matrix declaration says int matrix[3][3]; that it has three 1-D array & in each 1-D array you can store three elements. And in C/C++ array index starts from zero.
Problematic statement is for (int i = 1; i <= 3; i++) as you are skipping matrix[0][0] and trying to store into matrix[3][3] which doesn't exist which in turn causes undefined behavior.
So firstly start iterating loop from 0 to number of rows & column respectively.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3 ; j++) {
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
Coming to task you mentioned, print out a matrix in which all the diagonals are outputted as zero. ? write one condition so that if row value & col value are equal then assign it to zero otherwise scan from user. Here is the sample code
int main(void) {
int matrix[3][3] = { 0 }; /* initialize it */
int row = sizeof(matrix)/sizeof(matrix[0]); /* find no of rows */
int col = sizeof(matrix[0])/sizeof(matrix[0][0]);/* find no of columns */
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if( i == j)
matrix[i][j] = 0;/* when i and j are equal means thats diagonal and assign it to zero */
else /* if its not diagonal then scan from user */
std::cin>>matrix[i][j];
}
}
return 0;
}
Secondly, I also have to pass it to a function. for this learn how to pass 2d array to a function. Here is the sample example.
void diagonal(int (*mat)[3],int row, int col) { /* mat is pointer to an array */
std::cout<<"printing matrix "<<std::endl;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
std::cout<<mat[i][j]<<"\t";
}
std::cout<<std::endl;
}
}
And call diagonal() like below from main() function as
diagonal(matrix,row,col); /* pass matrix, no of rows, no of columns */

How do you calculate the total number of -1s and the total numbers of 1s in the table? (c++)

Here is the coding below :) I have also commented on some parts so that it is easier to understand the output of the code.
I have a slight idea that I need to use an "if statement" with "rand()%" in order to make sure that the program knows we want to calculate the sum of 1s and -1s only. for e.g using "rand()%2-1" can help with getting the total sum of 1s outputted in the table. Again, I'm not sure if this idea will work or not.
So the program should output something like "The amount of 1s in the table is 5 and the amount of -1s in the table is 3" for the first time its ran. Then when it is ran the second time, it could output something like "The amount of 1s in the table is 2 and the amount is -1s in the table is 5"
Sorry for any confusions and All your help will be highly appreciated :) :)
#include<iostream>
#include<iomanip>
#include<ctime>
using namespace std;
int main() {
srand(time(0));
const int ROWS=3;
const int COLS=4;
int table[ROWS][COLS];
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++) {
table[i][j] = rand()%3-1;
}
}
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++)
cout << setw(3) << table[i][j];
cout << endl;
}
bool checkTable [ROWS][COLS];
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++) {
if (table[i][j] !=0) {
checkTable[i][j] = true;
}
else{
checkTable[i][j] = false;
}
//The output in the line below is the final line outputted by the
console. This prints out "1" if there is a value in the index within
the table provided above (the value is represented by 1 or -1), and
prints out "0" if there is no value in the index (represented by 0)
cout << " " << checkTable[i][j];
}
}
return 0;
}
[...] for e.g using "rand()%2-1" can help with getting the total sum of 1s
outputted in the table.
I dont really understand what you mean by that. Counting and randomness dont go well together. I mean of course you can fill a matrix with random numbers and then do some counting, but rand() wont help anything for the counting.
You need something as simple as that:
int main() {
srand(time(0));
const int ROWS=3;
const int COLS=4;
int table[ROWS][COLS];
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++) {
table[i][j] = rand()%3-1;
}
}
unsigned ones_counter = 0;
for (int i = 0; i < ROWS; i ++) {
for (int j = 0; j < COLS; j++) { // dont forget the bracket
cout << setw(3) << table[i][j];
if (table[i][j] == 1) { ones_counter++;} // <- this is counting
}
cout << endl;
}
std::cout << "number of 1s in the table : " << ones_counter << "\n";
....

Two-dimensional array: calculate sum of rows and product of columns

I am currently working on a task which says the following:
Input a two-dimensional array A (m,n) [m < 10, n < 20]. In the n + 1 column calculate the sum of the rows, and in the m + 1 row the product of the columns. Print out the resulting matrix.
According to my understanding of this task, at the end of each column must be the sum of according rows (so on the right hand side), and the product of the column (at the end/bottom?).
This task is so confusing I do not know where to start. I found some code that covers the idea but does not include the product and it does not display these values as the task asks me to:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[3][3];
int i, j, s = 0, sum = 0;
cout << "Enter 9 elements of 3*3 Matrix \n";
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
cin >> a[i][j];
cout << "Matrix Entered By you is \n";
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
cout << a[i][j] << " ";
cout << endl;
}
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
s = s + a[i][j];
cout << "sum of" << i + 1 << " Row is" << s;
s = 0;
cout << endl;
}
cout << endl;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
s = s + a[j][i];
cout << "sum of" << i + 1 << " Column is" << s;
s = 0;
cout << endl;
}
cout << endl;
for (i = 0; i < 3; i++)
sum = sum + a[i][i];
cout << "Sum of Diagnols Elements is \n" << sum;
getch();
}
We beginners should help each other.
Here you are
#include <iostream>
#include <iomanip>
int main()
{
const size_t M = 10;
const size_t N = 20;
int a[M][N] = {};
std::cout << "Enter number of rows: (less than " << M << "): ";
size_t m;
std::cin >> m;
if (!(m < M) || (m == 0)) m = M - 1;
std::cout << "Enter number of columns: (less than " << N << "): ";
size_t n;
std::cin >> n;
if (!(n < N) || (n == 0)) n = N - 1;
std::cout << std::endl;
for (size_t i = 0; i < m; i++)
{
std::cout << "Enter " << n
<< " numbers for the row " << i << ": ";
for (size_t j = 0; j < n; j++) std::cin >> a[i][j];
}
for (size_t j = 0; j < n; j++) a[m][j] = 1;
for (size_t i = 0; i < m; i++)
{
for (size_t j = 0; j < n; j++)
{
a[i][n] += a[i][j];
a[m][j] *= a[i][j];
}
}
std::cout << std::endl;
for (size_t i = 0; i < m + 1; i++)
{
for (size_t j = 0; j < n + 1; j++)
{
std::cout << std::setw(3) << a[i][j] << ' ';
}
std::cout << '\n';
}
std::cout << std::endl;
}
The program output might look like
Enter number of rows: (less than 10): 3
Enter number of columns: (less than 20): 3
Enter 3 numbers for the row 0: 1 2 3
Enter 3 numbers for the row 1: 4 5 6
Enter 3 numbers for the row 2: 7 8 9
1 2 3 6
4 5 6 15
7 8 9 24
28 80 162 0
So you have to declare an array with 10 rows and 20 columns. The user should enter the dimensions of the array that are correspondingly less than 10 and 20. One row and one column are reserved for sums and products.
It is desirable that the array would be initially initialized by zeroes.
int a[M][N] = {};
In this case you need not to set the last column with zeroes as you have to do with last row initializing it with ones.
That is all.:)
Start with the declaration: make sure that your program works with m×n matrix, not simply a 3×3 matrix. Since m and n have limits of 10 and 20, and because you must add an extra row and a column to the result, the declaration should be
int a[11][21];
You also need to declare m and n, have end-user enter them, and validate them to be within their acceptable ranges:
int m, n;
cin >> m >> n;
... // Do the validation
Now you can rewrite your loops in terms of m and n, rather than using 3 throughout your code.
With these declarations in place, you can total the numbers in place, i.e. for each row r you would write
for (int i = 0 ; i != n ; i++) {
a[r][n+1] += a[r][i];
}
Similarly, you would compute the product (don't forget to start it with the initial value of 1, not 0).
At the end you would print an (m+1)×(n+1) matrix to complete the task.
Solution : use this kind of functions for your array after making it global.
void Adder(int row, int colum)
{
for (int i = 0; i < row - 1; i++)
{
int temp = 0;
for (int j = 0; j < colum - 1; j++)
{
temp += a[i][j]; // added all other than last one
}
a[i][j] = temp; // assigned to last one in row
}
}
void Mul(int row, int colum)
{
for (int i = 0; i < colum- 1; i++)
{
int temp = 1;
for (int j = 0; j < row - 1; j++)
{
temp *= a[j][i]; // multiplied all element other than last one
}
a[j][i] = temp; // assigned to last one in column
}
}

How to Sum Column of a Matrix and Store it in a Vector in C++

Is there a straight forward way to do it?
I'm stuck here:
#include <iostream>
#include <vector>
#include <cstdlib>
using std::size_t;
using std::vector;
int main()
{
vector<vector<int> > Matrix;
//Create the 2x2 matrix.
size_t rows = 2;
size_t cols = 2;
// 1: set the number of rows.
Matrix.resize(rows);
for(size_t i = 0; i < rows; ++i)
{
Matrix[i].resize(cols);
}
// Create Matrix
Matrix[0][0] = 1;
Matrix[0][1] = 2;
Matrix[1][0] = 3;
Matrix[1][1] = 4;
// Create Vector to store sum
vector <int> ColSum;
for(size_t i = 0; i < rows; ++i)
{
for(size_t j = 0; j < cols; ++j)
{
std::cout <<"["<<i<<"]"<<"["<<j<<"] = " <<Matrix[i][j]<<std::endl;
// I'm stuck here
}
}
return 0;
}
Given the matrix above:
1 2
3 4
In the end we hope to print the result of a vector
(that keeps the sum of each column):
4 6
Note that the matrix can be of any dimension.
for( size_t row = 0; row < Matrix.size(); row++ )
{
ColSum[row] = 0;
for( size_t column = 0; column < Matrix[row].size(); column++ )
{
ColSum[row] += Matrix[row][column];
}
}
// Create Vector to store sum
vector <int> ColSum;
ColSum.Resize(cols);
for(size_t i = 0; i < rows; ++i)
{
for(size_t j = 0; j < cols; ++j)
{
std::cout <<"["<<i<<"]"<<"["<<j<<"] = " <<Matrix[i][j]<<std::endl;
ColSum[j] += Matrix[i][j];
}
}
This should work. At the end, you will have sums in ColSum
vector <int> ColSum;
ColSum.resize(cols);
for(size_t j = 0; j < cols; ++j)
{
int sum = 0;
for(size_t i = 0; i < rows; ++i)
{
sum += Matrix[i][j];
}
ColSum[j] = sum;
}
#include <iostream.h>
#include <conio.h>
int main()
{
int A[10][10],m,n,x,y,sum=0;
//Create a Matrix A
cout << "Enter number of rows and columns in Matrix A : \n";
cin>>n>>m;
cout << "Enter elements of Matrix A : \n";
for(x=1;x<n+1;++x)
for(y=1;y<m+1;++y)
cin>>A[x][y];
//Find sum of each row
for(x=1;x<n+1;++x)
{
A[x][m+1]=0;
for(y=1;y<m+1;++y)
A[x][m+1]=A[x][m+1]+A[x][y];
}
//Find sum of each column
for(y=1;y<m+1;++y)
{
A[n+1][y]=0;
for(x=1;x<n+1;++x)
A[n+1][y]+=A[x][y];
}
cout << "\nMatrix A, Row Sum (Last Column)" << " and Column Sum (Last Row) : \n";
for(x=1;x<n+1;++x)
{
for(y=1;y<m+2;++y)
cout << A[x][y] << " ";
cout << "\n";
}
//Print sum of each column
x=n+1;
for(y=1;y<m+1;++y)
cout << A[x][y] << " ";
cout << "\n";
if(m==n)
{
for(x=1;x<m+1;x++)
for(y=1;y<n+1;y++)
if(x==y)
sum+=A[x][y];
else
if(y==m-(x+1))
sum+=A[x][y];
}
cout << "Sum of diagonal elements is : " << sum << endl;
getch();
return 0;
}