백준 10818번, 2562번

🐾 10818 : 최소, 최대

① for 구문 사용

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		
		
		Scanner scanner = new Scanner(System.in);
		
//		System.out.print("배열 길이를 입력하세요 : ");
		int len = scanner.nextInt();
		int[] num = new int[len];
		
//		System.out.print("숫자를 입력하세요 : ");
		for (int i = 0; i < num.length; i++) {
			num[i] = scanner.nextInt();
		}
		
		scanner.close();
		
		int max = -1000000;
		int min = 1000000;
		
		for (int i = 0; i < num.length; i++) {
			if (min > num[i]) {
				min = num[i];
			}
			if (max < num[i]) {
				max = num[i];
			}
		}
		System.out.println(min+" "+max);

	}

}

② Arrays.sort(); 사용

import java.util.Arrays;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		
//		System.out.print("배열 길이를 입력하세요 : ");
		int len = scanner.nextInt();
		int[] num = new int[len];
		
//		System.out.print("숫자를 입력하세요 : ");
		for (int i = 0; i < num.length; i++) {
			num[i] = scanner.nextInt();
		}
		
		scanner.close();
		
		Arrays.sort(num);
		System.out.println(num[0] + "  " + num[len-1]);
	}

}




🐾 2562 : 최댓값

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		
		int[] num = new int[9];
//		System.out.print("숫자 9개를 입력하세요 : ");
		for (int i = 0; i < num.length; i++) {
			num[i] = scanner.nextInt();
		}
		
		scanner.close();
		
		int max = num[0];
		int cnt = 1;
		
		for (int i = 0; i < num.length; i++) {
			if (num[i] > max) {
				max = num[i];
				cnt = i + 1;
			}
		}
		
		System.out.println(max);
		System.out.println(cnt);
		
	}

}

좋은 웹페이지 즐겨찾기