문제 9개의 서로 다른 자연수가 주어질 때, 이들 중 최댓값을 찾고 그 최댓값이 몇 번째 수인지를 구하는 프로그램을 작성하시오. 예를 들어, 서로 다른 9개의 자연수 3, 29, 38, 12, 57, 74, 40, 85, 61 이 주어지면, 이들 중 최댓값은 85이고, 이 값은 8번째 수이다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 29 38 12 57 74 40 85 61 85 8
풀이코드1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 public class Main { public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int max = 0 ; int i = 0 ; int [] arr = new int [9 ]; for (i=0 ; i<arr.length; i++){ arr[i] = Integer.parseInt(br.readLine()); max = Math.max(arr[i], max); } for (int j =0 ; j<arr.length; j++){ if (arr[j] == max){ i = j+1 ; } } System.out.println(max); System.out.println(i); } }
풀이코드2 : 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 public class Main { public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int max = 0 ; int i = 0 ; int [] arr = new int [9 ]; for (int j=0 ; j<arr.length;j++) { arr[j] = Integer.parseInt(br.readLine()); if (max < arr[j]) { max = arr[j]; i = j+1 ; } } System.out.println(max); System.out.println(i); } }
백준의 다른 문제 풀이가 보고싶다면?