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

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
}

Related

Find the column with the maximum negative matrix element and the column with the minimum element

I want to know the column with the maximum negative matrix element and the column with the minimum element so that I can rearrange them. More specifically, I'm interested in return values of The column with the maximum negative element: and The column with the minimum element: But about half the time, the results about which columns they are return completely wrong. The interesting thing is that the results don't always come back wrong. What am I doing wrong?
#include <iostream>
#include <time.h>
#include <cmath>
using namespace std;
int main(void) {
// random number for rand()
srand(time(0));
int m = 5; // row count
int n = 5; // column count
// declaration of a dynamic array of pointers
double **arr = (double**) malloc(n * sizeof(double));
// filling the array with pointers
for (int i = 0; i < n; i++)
arr[i] = (double*) malloc(m * sizeof(double));
// array initialization with random numbers
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = (double) (rand() % 400 - 199) / 2.0; // (-100.0; 100.0)
// matrix output
cout << "\n\033[92mOriginal array:\033[94m" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
printf("%5.1f ", arr[i][j]);
cout << endl;
}
// array for the sums of modules of the row elements
float *sumOfAbsolutes = (float*) malloc(m * sizeof(float));
// Initializing the array with zeros
for (int i = 0; i < m; i++) sumOfAbsolutes[i] = 0;
// filling the array with the sums of element modules
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
sumOfAbsolutes[i] += abs(arr[i][j]);
// output
cout << "\n\033[92mSums of modules of array row elements:" << endl;
for (int i = 0; i < m; i++)
cout << "\033[92m" << i << ": \033[94m"<< sumOfAbsolutes[i] << " ";
cout << "\n\n";
// sorting
for (int i = 0; i < (m - 1); i++)
for (int j = i; j < m; j++)
if (sumOfAbsolutes[i] > sumOfAbsolutes[j]) {
double tmp = sumOfAbsolutes[i];
sumOfAbsolutes[i] = sumOfAbsolutes[j];
sumOfAbsolutes[j] = tmp;
double *tmp2 = arr[i];
arr[i] = arr[j];
arr[j] = tmp2;
}
// matrix output
cout << "\033[92mSorted array:\033[94m" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
printf("%5.1f ", arr[i][j]);
cout << endl;
}
int columnWithMaxNegNum = 0; // the column with the maximal negative element
int minNumber = 0; // the column with the minimum element
// search for the maximal negative element
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] < 0 && arr[i][j] > arr[i][columnWithMaxNegNum])
columnWithMaxNegNum = j;
// minimum element search
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] < arr[i][minNumber]) minNumber = j;
cout << "\n\033[92mThe column with the maximum negative element: \033[94m" << columnWithMaxNegNum << endl;
cout << "\033[92mThe column with the minimum element: \033[94m" << minNumber << endl;
// rearrangement of columns
for (int i = 0; i < m; i++) {
double temp = arr[i][columnWithMaxNegNum];
arr[i][columnWithMaxNegNum] = arr[i][minNumber];
arr[i][minNumber] = temp;
}
cout << "\n\033[92mRearrangement of columns:" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
printf("\033[94m%5.1f ", arr[i][j]);
cout << "\n\033[0m";
}
// memory cleanup
free(sumOfAbsolutes);
for (int i = 0; i < n; i++)
free(arr[i]);
free(arr);
}
I assume that this is some kind of homework, since normally, we'd use vectors and algorithms to write much shorter code.
The following loop doesn't find the maximal negative:
// search for the maximal negative element
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] < 0 && arr[i][j] > arr[i][columnWithMaxNegNum])
columnWithMaxNegNum = j;
Because the the search is dependent of the line. You'd need to go for:
double maxNegNum = -100.0; // tbd
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] < 0 && arr[i][j] > maxNegNum) {
columnWithMaxNegNum = j;
maxNegNum = arr[i][j];
}
The same applies for the minimum :
double minN=100.0;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] < minN) {
minNumber = j;
minN = arr[i][j];
}
Not related: if you go for C++ forget malloc and free, and use new/delete and new[]/delete[] instead. Here a first attempt: Online demo
Caution/Limitations:
If by no negative number are found, the maximum negative value would be inaccurate.
If several equal maximum negative values and minimum values are found, only the first one( from left to right and to bottom) will be considered.

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 */

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
}
}

Finding the average of individual rows and columns in random array

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.

Dynamic Multidimensional array in C++

I made Matrix Multiplication program in c++ using dynamic Multidimensional arrays.
problem is when i enter test values
matrix A = row1{ 1 } , row2 { 2 } matrix B = row1 {1 ,2 , 3} , it stops working at the loop where user
inputs values of first array , i found it using debugging. but program works fine when i enter
matrix A = row1{ 1 , 2 } , row2 { 3 , 4 } matrix B = row1 {5 , 6 } , row2 {7 , 8}
i want this program to be a general program that can multiply all matrixs
#include <iostream>
using namespace std;
class Lab_02
{
public:
void Product(){
int a1Rows, a1Columns;
int a2Rows, a2Columns;
cout << "Plz Enter the no. of rows for Array 1 :";
cin >> a1Rows;
cout << "Plz Enter the no. of columns for Array 1 :";
cin >> a1Columns;
cout << "Plz Enter the no. of rows for Array 2 :";
cin >> a2Rows;
cout << "Plz Enter the no. of columns for Array 2 :";
cin >> a2Columns;
int **dynamicArray = 0;
int **dynamicArray2 = 0;
int **dynamicArray3 = 0;
cout << endl;
for (int i = 0; i < a1Rows; i++)
{
dynamicArray3 = new int *[a1Rows];
}
for (int i = 0; i < a2Columns; i++)
{
dynamicArray3[i] = new int[a2Columns];
}
// memory allocated for elements of rows.
for (int i = 0; i < a1Rows; i++)
{
dynamicArray = new int *[a1Rows];
}
// memory allocated for elements of each column.
for (int i = 0; i < a1Columns; i++)
{
dynamicArray[i] = new int[a1Columns];
}
// memory allocated for elements of rows.
for (int i = 0; i < a2Rows; i++)
{
dynamicArray2 = new int *[a2Rows];
}
// memory allocated for elements of each column.
for (int i = 0; i < a2Columns; i++)
{
dynamicArray2[i] = new int[a2Columns];
}
cout << "enter the values or array 1 \n";
for (int i = 0; i < a1Rows; i++)
{
for (int j = 0; j < a1Columns; j++)
{
cout << "array[" << i << "][" << j << "]\t";
cin >> dynamicArray[i][j];
}
}
cout << "enter the values or array 2 :\n";
for (int i = 0; i < a2Rows; i++)
{
for (int j = 0; j < a2Columns; j++)
{
cout << "array[" << i << "][" << j << "]\t";
cin >> dynamicArray2[i][j];
}
}
int sum;
for (int i = 0; i < a1Rows; i++)
{
for (int j = 0; j < a1Columns ; j++)
{
sum = 0;
for (int k = 0; k < a2Columns ; k++)
{
sum = sum + (dynamicArray[i][k] * dynamicArray2[k][j]);
}
dynamicArray3[i][j] = sum;
}
}
cout <<"Result" << endl << endl;
for (int i = 0; i < a1Rows; i++)
{
for (int j = 0; j < a2Columns; j++)
{
cout << dynamicArray3[i][j] << "\t";
}
cout << endl;
}
}
};
void main(void)
{
Lab_02 object;
object.Product();
}
Your memory allocations for the matricies are the issue.
Change them to something like the following
// memory allocated for elements of rows.
dynamicArray = new int *[a1Rows];
// memory allocated for elements of each column.
for (int i = 0; i < a1Rows; i++)
{
dynamicArray[i] = new int[a1Columns];
}
You need to allocate one array of array for the rows and then you need to loop over the rows and allocate the columns.
The issue with the code is that you are not supposed to allocate the "rows" in a loop. All you need is one allocation for the rows, and then loop to allocate the data for each row.
So for example, instead of this:
for (int i = 0; i < a1Rows; i++)
{
dynamicArray = new int *[a1Rows];
}
// memory allocated for elements of each column.
for (int i = 0; i < a1Columns; i++)
{
dynamicArray[i] = new int[a1Columns];
}
The correct way would be this:
dynamicArray = new int *[a1Rows];
for (int i = 0; i < a1Columns; i++)
{
dynamicArray[i] = new int[a1Columns];
}
You made the same mistake for each of the loops.
Also, some points:
You failed to deallocate the memory that was allocated.
If you used std::vector, then things become much easier.
You need to check if the matrices are multiplyable before performing the sum loop. By multiplyable meaning that the number of columns and rows of matrix A and B satisfy the requirements for multiplication of A and B.
for (int i = 0; i < a1Rows; i++)
{
for (int j = 0; j < a1Columns; j++)
{
sum = 0;
for (int k = 0; k < a2Columns; k++)
sum = sum + (dynamicArray[i][k] * dynamicArray2[k][j]);
dynamicArray3[i][j] = sum;
}
}
This loop will go haywire if the dynamicArray1 and dynamicArray2 do not have the requisite number of columns and rows before multiplying.
First, the following test should be done before multiplying:
if (a1Columns != a2Rows)
return;
Second, your k loop is wrong. It should be this:
for (int k = 0; k < a2Rows; k++)
sum = sum + (dynamicArray[i][k] * dynamicArray2[k][j]);
dynamicArray3[i][j] = sum;