Instructions: Write a program in C++ that creates a two-dimensional array of int
ID: 3696458 • Letter: I
Question
Instructions:
Write a program in C++ that creates a two-dimensional array of integers according to the user's request.
Fill all elements of the array with random integers.
Print the array contents along with the sum of each each row, column and major diagonals.
Then, offer to repeat as many times as the user wishes.
Hints:
Use functions as you think reasonable.
Ask the user for the number of rows and columns for the array, but limit them to a reasonable size for display.
Note that you must use the same number of rows and columns in order to have full diagonals available.
Also use the mod operator to limit the range of the random numbers that fill the array to help with display.
Be sure to deallocate the memory used before allocating more for a new array.
Explanation / Answer
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
int order,value;
cout<<"Enter order of the Square Matrix(No of rows=No of columns)::";
cin>>order;
int square[order][order],sumRow[order],sumCol[order],sumDiag[2],j,k,row,col;
//here This Nested loop will take the user given values and fill the two-dimensional array
for (row = 0; row < order; row++)
{
for (int col = 0; col < order; col++)
{
square[row][col] = rand() % 20+1;
cout<< square[row][col]<<" ";
}
cout<<" ";
}
for (row = 0; row < order; row++) {
for (col = 0; col < order; col ++) {
sumRow[row] += square[row][col];
}
cout<<"sum row " << row << "::" << sumRow[row]<<endl;
}
//calculating the Sum of Each column
for (col = 0; col < order; col++) {
for (row = 0; row < order; row ++) {
sumCol[col] += square[row][col];
}
cout<<"sum columns " << col << "::" << sumCol[col]<<endl;
}
//calculating the Sum of Diagonal 1
for (row = 0; row < order; row++) {
sumDiag[0] += square[row][row];
}
cout<<"sum diagonal 0 " << "::" << sumDiag[0]<<endl;
//calculating the Sum of Diagonal 2
for(row = 0; row < order; row++) {
sumDiag[1] += square[row][order - 1 - row];
}
cout<<"sum diagonal 1 " << "::" << sumDiag[1]<<endl;
return 0;
}