124k views
4 votes
Write c++ program that creates a two-dimensional array with dimensions of 10×10 and named matrix. On the diagonal of this matrix, put the numbers from 0 to 9 and the number 0 everywhere else. Additionally, the program should calculate the sum of the elements on the diagonal.

1 Answer

4 votes

Final answer:

The requested C++ program initializes a 10x10 two-dimensional array, fills its diagonal with 0 to 9, and calculates the sum of the diagonal elements. The program includes the initialization, population, and output steps for the matrix and its diagonal sum.

Step-by-step explanation:

The C++ program to create a 10×10 two-dimensional array with diagonal numbers is as follows:

#include
using namespace std;

int main() {
int matrix[10][10];
int sum = 0;

// Initialize matrix and calculate the diagonal sum
for(int i = 0; i < 10; ++i) {
for(int j = 0; j < 10; ++j) {
if(i == j) {
matrix[i][j] = i;
sum += i;
} else {
matrix[i][j] = 0;
}
}
}

// Print matrix
for(int i = 0; i < 10; ++i) {
for(int j = 0; j < 10; ++j) {
cout << matrix[i][j] << ' ';
}
cout << endl;
}

// Output the sum of the diagonal elements
cout << "Sum of diagonal elements: " << sum << endl;

return 0;
}

This program initializes a two-dimensional array, fills the diagonal with numbers from 0 to 9, and calculates the sum of the diagonal. After populating the array, it prints the matrix and outputs the sum.

User Ratnadeep
by
7.7k points