1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

2次元配列(多次元配列)合計値、平均値などの求め方-java

Last updated at Posted at 2019-10-07

*個人的な感覚でエクセルの行と列を基準としています

2次元配列では[]を二つ[][]と宣言する。

sample
                int[][] score = {
                { 1, 2, 3, 4, 5 },          // 0行目
                { 10, 20, 30, 40, 50 },     // 1行目
                { 100, 200, 300, 400, 500 } // 2行目
	        };
        System.out.println(score[行目][]);
        System.out.println(score[0][0]);    // 0行目の0列
        System.out.println(score[1][1]);    // 1行目の1列
        System.out.println(score[2][3]);    // 2行目の3列


	//0行目0列から始まることに注意する


		int[][] array = {
					{1,2,3,4},
					{10,20,30,40,50,60},
					{1000,10000}
				};

		// 2次元配列arrayに含まれるすべての整数要素を順に出力
for(int i=0; i<array.length; i++) { // 配列名.lengthで 列(縦方向)の要素数を取得
	for(int s=0; s<array[i].length; s++) { // 配列名[i].lengthで 行(横方向)の要素数を取得
		System.out.println(array[i][s]); //array[縦][横]
			}
		}

コンソール結果
1
2
3
4
10
20
30
40
50
60
1000
10000

*上記の配列の合計値の求め方

sample
		int sum = 0;
		for(int i=0; i<array.length; i++) {
			for(int s=0; s<array[i].length; s++) {
				sum += array[i][s];
			}
		}
		System.out.println(sum);
	}

コンソール結果
11220

*平均値を求めるとき

sample
		int sum = 0;
		int count = 0;
		for(int i=0; i<array.length; i++) {
			for(int s=0; s<array[i].length; s++) {
				sum += array[i][s];
				count++;
			}
		}
		System.out.println(sum/count);
	}

コンソール結果
935

1
4
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?