알고리즘(Algorithm)
: 문제를 해결하기 위한 것으로, 명확하게 정의되고 순서가 있는 유한 개의 규칙으로 이루어진 집합
1. 최댓값
・최댓값을 구하는 과정
1)변수 max에 a 값을 넣는다.
2)b 값이 max보다 크면 max에 b 값을 넣는다.
3)c 값이 max보다 크면 max에 c 값을 넣는다.
-순차적(Concatenation) 구조: 여러 문장(프로세스)이 순차적으로 실행되는 구조
-선택(Select) 구조: if문과 같이 () 안에 있는 식의 평가 결과에 따라 프로그램의 실행 흐름을 변경하는 구조
・실습 1-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
|
public class Practice1_1 {
public static void main(String[] args) {
//3개의 정숫값 중 '최댓값' 구하기
Scanner stdIn = new Scanner(System.in);
System.out.println("세 정수의 최댓값을 구합니다");
System.out.println("a의 값: ");
int a = stdIn.nextInt();
System.out.println("b의 값: ");
int b = stdIn.nextInt();
System.out.println("c의 값: ");
int c = stdIn.nextInt();
int max = a;
if(b > max) max = b;
if(c > max) max = c;
System.out.println("최댓값은 : " + max + " 입니다.");
}
}
|
*System in: 키보드와 연결된 표준 입력 스트림(standard input stream)
・실습1-2
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 Practice1_2 {
//메소드를 작성해 여러 값에 대해서도 최댓값을 구할 수 있는지 확인하기
static int max3(int a, int b, int c) {
int max = a;
if(b > max)
max = b;
if(c > max)
max = c;
return max;
}
public static void main(String[] args) {
System.out.println("max3(3, 2, 1) = " + max3(3, 2, 1));
System.out.println("max3(3, 2, 2) = " + max3(3, 2, 2));
System.out.println("max3(3, 1, 2) = " + max3(3, 1, 2));
System.out.println("max3(2, 3, 1) = " + max3(2, 3, 1));
}
}
|
2. 중앙값
・중앙값을 구하는 절차는 매우 복잡해 수많은 알고리즘을 생각할 수 있다.
・실습1-3
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
29
30
31
32
33
34
|
public class Median {
static int med3(int a, int b, int c) {
if(a >= b)
if(b >= c)
return b;
else if(a <= c)
return a;
else
return c;
else if(a > c)
return a;
else if(b > c)
return c;
else
return b;
}
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.println("세 정수의 중앙값을 구합니다.");
System.out.println("a의 값: ");
int a = stdIn.nextInt();
System.out.println("b의 값: ");
int b = stdIn.nextInt();
System.out.println("c의 값: ");
int c = stdIn.nextInt();
System.out.println("중앙값은 " + med3(a, b, c) + " 입니다.");
}
}
|
3. 조건 판단과 분기
・실습1-4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class JudgeSign {
//입력한 정숫값이 양수인지 음수인지 0인지 판단
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.println("정수를 입력하세요.");
int n = stdIn.nextInt();
if (n > 0)
System.out.println("정수입니다.");
else if(n < 0)
System.out.println("음수입니다.");
else
System.out.println("0입니다.");
}
}
|
1)n이 0보다 크다
2)n이 0보다 작다
3)둘 다 아닌 경우
-> 총 세 가지로 분기
*만약 마지막 분기에서 else if문이 쓰인다면 세 개의 조건문이 쓰였더라도 분기는 네 개가 된다.
'Algorithm > 01. 기본 알고리즘' 카테고리의 다른 글
1-2. 반복(Repetition) (0) | 2020.08.30 |
---|