يقدم هذا المقال حلاً برمجياً بلغة C++ لتعريف مصفوفة ثلاثية الأبعاد، وإدخال قيم عناصرها من المستخدم، ثم عرض مجموع قيم كل صف على حدة.
لتحقيق متطلب برمجي يتضمن تعريف مصفوفة ثنائية الأبعاد بحجم 3 صفوف و 3 أعمدة، يتوجب على البرنامج طلب إدخال عدد صحيح لكل عنصر من عناصر المصفوفة من المستخدم. بعد ذلك، يعرض البرنامج ناتج جمع قيم العناصر الموجودة في كل صف من صفوف المصفوفة بشكل منفصل.
الحل بلغة C++:
# include <iostream>
int main () {
const int rows = 3 ;
const int cols = 3 ;
int matrix[rows][cols];
int s;
// Loop to get user input for matrix elements
for ( int i = 0 ; i < rows; i++) {
for ( int j = 0 ; j < cols; j++) {
std::cout << "Enter matrix[" << i << "][" << j << "]: " ;
std::cin >> matrix[i][j];
}
}
// Loop to calculate and display sum of each row
for ( int i = 0 ; i < rows; i++) {
s = 0 ;
for ( int j = 0 ; j < cols; j++) {
s += matrix[i][j];
}
std::cout << "\nThe sum of all elements in row " << i << ": " << s;
}
std::cout << "\n" ;
// This part is typically used to pause the console on Windows
char end;
std::cin >> end;
return 0 ;
}
عند تنفيذ البرنامج وإدخال القيم المحددة، سيتم عرض النتائج التالية:
Enter matrix[0][0]: 1
Enter matrix[0][1]: 2
Enter matrix[0][2]: 3
Enter matrix[1][0]: 4
Enter matrix[1][1]: 5
Enter matrix[1][2]: 6
Enter matrix[2][0]: 7
Enter matrix[2][1]: 8
Enter matrix[2][2]: 9
The sum of all elements in row 0: 6
The sum of all elements in row 1: 15
The sum of all elements in row 2: 24