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

تحديات برمجيةالتحدي الرابع - حل التمرين الثالث بلغة جافا

المطلوب

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


الحل بلغة جافا

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int[][] matrix = new int[3][3];
        int s;
  
        for (int i = 0; i < matrix.length; i++)
        {
            for (int j = 0; j < matrix[0].length; j++)
            {
                System.out.print("Enter matrix[" + i + "][" + j +"]: ");
                matrix[i][j] = input.nextInt();
            }
        }
        
        System.out.println();
        
        for (int i = 0; i < matrix.length; i++)
        {
            s = 0;
            for (int j = 0; j < matrix[0].length; j++)
            {
                s += matrix[i][j];
            }
            System.out.println("The sum of all elements in row " + i + ": " + s);
        }

    }

}

سنحصل على النتيجة التالية في حال تم إدخال نفس القيم التي تم تعليمها باللون الأصفر عند التشغيل.

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