22.04.12_배열_(3)

Saparian·2022년 4월 12일
0

오늘의배움

목록 보기
47/53

배열의 활용방법에 대해서 공부했다.

총합과 평균

public static void main(String[] args) {
		int sum =0;			// 총점을 저장하기 위한 변수
		float average = 0f;	// 평균을 저장하기 위한 변수
		
		int[] score = {100, 88, 100, 100, 90};
		
		for (int i=0; i < score.length; i++) {
			sum += score[i];
		}
		average = sum / (float)score.length;	// 계산결과를 float로 얻기 위해서 형변환
		
		System.out.println("총점 : " + sum);
		System.out.println("평균 : " + average);

	}	// main의 끝

결과값

총점 : 478
평균 : 95.6

최대값과 최소값

public static void main(String[] args) {
		int[] score = {79, 88, 91, 33, 100, 55, 95};
		
		int max = score[0];	// 배열의 첫 번째 값으로 최대값을 초기화 한다.
		int min = score[0];	// 배열의 첫 번째 값으로 최소값을 초기화 한다.
		
		for(int i=0; i < score.length; i++) {
			if(score[i] > max) {
				max = score[i];
			} else if(score[i] < min) {
				min = score[i];
			}
		} // end of for
		
		System.out.println("최대값 : " + max);
		System.out.println("최소값 : " + min);

	}	// main의 끝

결과값

최대값 : 100
최소값 : 33

0개의 댓글