Programming Basics SQL HTML CSS JavaScript React Python C++ Java JavaFX Swing Problem Solving English English Conversations Computer Fundamentals Linux Learn Typing

تحديات برمجيةالتحدي الرابع - حل التمرين الرابع بلغة C++

المطلوب

أكتب برنامج يعرّف مصفوفة إسمها matrix تتألف من 3 أسطر و 3 أعمدة.
بعدها يطلب من المستخدم إدخال عدد صحيح لكل عنصر فيها.
في الأخير, يعرض للمستخدم ناتج جمع قيم العناصر الموجودة في كل عامود فيها.


الحل بلغة C++

#include <iostream>

int main() {

    const int rows = 3;
    const int cols = 3;
    int matrix[rows][cols];
    int s;

    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 j = 0; j < cols; j++)
    {
        s = 0;
        for (int i = 0; i < rows; i++)
        {
            s += matrix[i][j];
        }
        std::cout << "\nThe sum of all elements in column " << j << ": " << s;
    }

    std::cout << "\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 in column 0: 12
The sum of all elements in column 1: 15
The sum of all elements in column 2: 18