การหาผลรวมแต่ละคอลัมน์ในอาเรย์ 2 มิติ
โจทย์
You are given the array with size of n x m. Write the program to calculate the summation of each column in a 2D array.
Input:
- The first line contains two integers n and m, representing the number of rows and columns of the array.
- The next n lines each contain m integers, representing the elements of the array.
Output:
- A single line containing m integers, where each integer represents the sum of the corresponding column.
| Input | Output |
|---|---|
| 3 3 1 2 3 4 5 6 7 8 9 | 12 15 18 |
โค้ด
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int [][] numbers = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
numbers[i][j] = scanner.nextInt();
}
}
for (int i = 0; i < m; i++) {
int sumColumn = 0;
for (int j = 0; j < n; j++) {
sumColumn += numbers[j][i];
}
System.out.println(sumColumn);
}
}
}คำอธิบาย
1. การประกาศคลาสและรับขนาดอาเรย์
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // จำนวนแถว
int m = scanner.nextInt(); // จำนวนคอลัมน์- ใช้ Scanner สำหรับรับข้อมูล
- รับค่า n และ m เป็นขนาดของอาเรย์
2. การสร้างและเก็บข้อมูลในอาเรย์
int[][] numbers = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
numbers[i][j] = scanner.nextInt();
}
}- สร้างอาเรย์ 2 มิติขนาด
- ใช้ loop ซ้อนเพื่อรับค่าข้อมูล:
- loop นอก (i) วนตามจำนวนแถว
- loop ใน (j) วนตามจำนวนคอลัมน์
3. การคำนวณผลรวมแต่ละคอลัมน์
for (int i = 0; i < m; i++) { // วนตามคอลัมน์
int sumColumn = 0; // เริ่มผลรวมใหม่สำหรับแต่ละคอลัมน์
for (int j = 0; j < n; j++) { // วนตามแถว
sumColumn += numbers[j][i]; // บวกค่าในคอลัมน์เดียวกัน
}
System.out.println(sumColumn); // แสดงผลรวมของแต่ละคอลัมน์
}- loop นอกวนตามจำนวนคอลัมน์ (m)
- สร้างตัวแปร sumColumn เก็บผลรวมของแต่ละคอลัมน์
- loop ในวนตามจำนวนแถว (n)
- สังเกตการสลับ index:
numbers[j][i]เพื่อเข้าถึงข้อมูลในแนวตั้ง - แสดงผลรวมทันทีเมื่อคำนวณแต่ละคอลัมน์เสร็จ
แผนภาพการทำงาน
ตัวอย่างการทำงาน
สมมติว่ามีอาเรย์ขนาด :
1 2 3
4 5 6
7 8 9การคำนวณ:
- คอลัมน์ที่ 1:
- คอลัมน์ที่ 2:
- คอลัมน์ที่ 3:
Output: 12 15 18
ปรับปรุงล่าสุด