문제를 해결하기 위한 것으로, 명확하게 정의되고 순서가 있는 유한 개의 규칙으로 이루어진 집합.
package com.practiceExample.Doit;
import java.util.Scanner;
public class Max3 {
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();
int max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println("최대값은 " + max + "입니다.");
stdIn.close();
}
}
최대값을 구하는 과정
세 문장이 나란히 있다면 이 문장은 순서대로 실행된다. 이렇게 여러 문장(process)이 순차적으로 실행되는 구조를 순차(concatenation)구조라고 한다.
if : ()안에 있는 식의 평가 결과에 따라 프로그램의 실행 흐름을 변경한다. 이런 구조를 선택(selection)구조라고 한다.
package com.practiceExample.Doit;
public class Min3 {
static int min3(int a, int b, int c) {
int min = a;
if(b < min)
min = b;
if(c < min)
min = c;
return min;
}
public static void main(String[] args) {
System.out.println(min3(9, 4, 2));
}
}
최대값, 최소값과 달리 중앙값을 구하는 절차는 매우 복잡하다. 그래서 수많은 알고리즘을 생각할 수 없다.
package com.practiceExample.Doit;
import java.util.Scanner;
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.print("a의 값 : ");
int a = stdIn.nextInt();
System.out.print("b의 값 : ");
int b = stdIn.nextInt();
System.out.print("c의 값 : ");
int c = stdIn.nextInt();
System.out.println("중앙값 : " + med3(a, b, c));
}
}
어떤 조건이 성립하는 동안 처리를 반복하여 실행하는것을 반복구조라고 하며 일반적으로 루프(loop)라고 부른다.
package com.practiceExample.Doit;
import java.util.Scanner;
public class SumWhile {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("1 ~ n 까지의 합");
System.out.print("n의 값 : ");
int n = s.nextInt();
int sum = 0;
int i = 1;
while(i <= n) { // i가 n 이하면 반복
sum += i; // sum에 i를 더한다.
i++; // i 값을 1만큼 증가시칸다.
}
System.out.println("합계 : " + sum);
}
}
일반적으로 하나의 변수를 사용하는 반복문은 while문보다 for문을 사용하는 것이 좋다.
package com.practiceExample.Doit;
import java.util.Scanner;
public class SumForPos {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n;
System.out.println("1~n까지의 합");
// n이 0보다 클 때까지 반복한다.
do {
System.out.print("n의 값 : ");
n = s.nextInt();
} while(n <= 0);
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("합계 : " + sum);
}
}
do 문은 일단 루프 본문을 한번 실행한 다음에 계속 반복할 것인지를 판단하는 사후 판단 반복문이다.
while문과 마찬가지로 ()안의 제어식을 평가한 값이 0이 아니면 루프 본문의 명령문이 반복된다.
사전 판단 반복문인 while과 for문은 처음에 제어식을 평가한 결과가 0이면 루프 본문은 한번도 실행되지 않는다. 이와 달리 사후 판단 반복문인 do문은 루프 본문이 반드시 한번은 실행된다. 이것이 사전 판단 반복과 사후 판단 반복의 차이점이다.
하나의 입구와 하나의 출구를 가진 구성 요소만을 계층적으로 배치하여 프로그램을 구성하는 방법을 구조적 프로그래밍(structured programming)이라고 한다. 구조적 프로그래밍은 순차, 선택, 반복이라는 3종류의 제어 흐름을 사용한다.
드모르간 법칙
x && y와 !(!x || !y)
는 같다x || y 와 !(!x && !y)
는 같다.