본문 바로가기
Algorithm

[자바의 정석] Chapter5 배열 - 9번 예제(최대값과 최소값)

by Baest 2021. 5. 31.

[문제]

배열에 7개의 점수 값(score)을 초기화하고 최대값과 최소값 찾기

 

[간략한 풀이]

max, min 변수를 score 배열의 첫 번째 값으로 초기화

score 배열의 길이만큼 반복(for문)첫 번째 값으로 초기화되었으므로 두 번째 값부터 비교하여 최대값과 최소값 구하면됨

 

[코드]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package arrays;
 
public class Ex5_3 {
 
    public static void main(String[] args) {
        int[] score = {79,88,91,33,90,55,20 };
        
        int max = score[0];
        int min = score[0];
        
        for(int i=1;i<score.length; i++) {
            if(score[i]> max) {
                max = score[i];
            }else if(score[i]<min){
                min = score[i];
            }
        }
        System.out.println("max = " + max);
        System.out.println("min = " + min);
        
    }
 
}
 
 
cs