تحديات برمجيةالتحدي الرابع - حل التمرين الثاني بلغة C++
المطلوب
أكتب برنامج يعرّف مصفوفة إسمها matrix
تتألف من 3 أسطر و 3 أعمدة.
بعدها يطلب من المستخدم إدخال عدد صحيح لكل عنصر فيها.
في الأخير, يعرض للمستخدم ناتج جمع جميع قيم عناصرها.
الحل بلغة C++
#include <iostream>
int main() {
const int rows = 3;
const int cols = 3;
int matrix[rows][cols];
int s = 0;
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];
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
s += matrix[i][j];
}
}
std::cout << "\nThe sum of all elements: " << s << "\n";
char end; std::cin >> end;
return 0;
}
#include <iostream>
int main() {
const int rows = 3;
const int cols = 3;
int matrix[rows][cols];
int s = 0;
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];
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
s += matrix[i][j];
}
}
std::cout << "\nThe sum of all elements: " << s << "\n";
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: 45
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: 45