반복문
주어진 조건이 참을 충족하는 동안 블록 안의 실행문을 반복해서 수행하는 문법.
#01. while문 (보통)
1) 기본 구문 형식
주어진 조건식이 참인 동안 블록 안을 반복적으로 수행한다.
whlie (조건) {
... 반복적으로 수행할 문구...
}
2) 반복문의 조건이 성립하기 위한 구성
초기식; // (1) 조건식을 판별하기 위한 기준값을 생성한다.
whlie (조건식) { // (2)(5) 조건을 판별한다.
... 반복적으로 동작할 구문 ... // (3) 명령을 수행한다
증감식; // (4)기준값에 변화를 주고 다시 조건식으로 이동한다.
}
예제
public class While1{
public static void main(String[] args) {
// 초기식
int x = 0;
// 조건식 -> x가 10보다 작은 동안 반복수행
while (x < 10) {
// 반복이 진행되는 동안 수행할 명령
// --> 여기서는 x의 변화 과정을 출력한다.
System.out.printf("x=%d\n", x);
// 증감식 -> 조건에 사용되는 값을 변경
x++;
}
System.out.println("----------");
System.out.printf("x의 최종값: %d\n", x);
}
}
출력결과
x=0
x=1
x=2
x=3
x=4
x=5
x=6
x=7
x=8
x=9
x의 최종값: 10
예제2
1~10까지의 합을 구하시오.
public class While2{
public static void main(String[] args) {
// 총합을 구하기 위해서는 값을 누적 합산할 변수를 0으로 초기화 하고 시작해여 한다.
int sum = 0;
// 초기식
int i = 1;
while (i < 11) {
// sum에 i의 값이 1부터 10까지 변하는 동안 누적합산 한다.
sum += i;
// 중간과정 출력
System.out.printf("i=%d, sum=%d\n", i, sum);
// i값을 1씩 증가한다.
i++;
}
}
}
출력결과
i=1, sum=1
i=2, sum=3
i=3, sum=6
i=4, sum=10
i=5, sum=15
i=6, sum=21
i=7, sum=28
i=8, sum=36
i=9, sum=45
i=10, sum=55
Whlie3.java
내 풀이
import java.util.Scanner;
public class Whlie3 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("숫자를 입력하세요.");
int x = reader.nextInt();
// 초기식
int y = 1;
while (y < 10) {
// sum에 i의 값이 1부터 10까지 변하는 동안 누적합산 한다.
int c = num * i;
// 중간과정 출력
System.out.printf("%d x %d= %d\n", num, i, c);
// i값을 1씩 증가한다.
i++;
}
}
}
강사님 풀이
import java.util.Scanner;
public class Whlie3 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("숫자를 입력하세요.");
int x = reader.nextInt();
int y = 1;
while (y < 10) {
System.out.printf("%d x %d= %2d\n", x, y, x * y);
// %2d 는 9x1=9 나오는 것을 두자리 채워 9x1= 9로 채워서 출력
// i값을 1씩 증가한다.
y++;
}
}
}
출력결과
9를 입력시
9 x 1= 9
9 x 2= 18
9 x 3= 27
9 x 4= 36
9 x 5= 45
9 x 6= 54
9 x 7= 63
9 x 8= 72
9 x 9= 81
While4.java
내 풀이
import java.util.Scanner;
public class While4 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("x의 값 입력하시오.");
int x = reader.nextInt();
System.out.print("y의 값을 입력하시오.");
int y = reader.nextInt();
int i = 0;
while (y > x) {
i += x;
x++;
}
System.out.printf("x부터 y의 까지의 총 합 : %d", i);
}
}
강사님 풀이
// 반복을 몇 번해야 할 지 결정하는 값
// -> x부터y까지 1씩 증가하면서 반복해야 하므로
// 반복은 y와 x의 차이 횟수만큼 반복하면 된다.
// ex) x=1 y=5일때 1,2,3,4,5, 총 5회 반복 -> 즉 y-x+1 회 반복
import java.util.Scanner;
public class While4 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("x의 값 입력하시오.");
int x = reader.nextInt();
System.out.print("y의 값을 입력하시오.");
int y = reader.nextInt();
int count = y - x + 1;
int i = 0; // 초기식
int sum = 0; // 합계를 저장할 값
{
while (i < count) {
// x부터 y까지 1씩 증가하는 값들의 합이므로 x에 1씩 증가하는 i를 더해서 새로운 변수를 만든다
int j = x + i;
// 합계 계산
sum += j;
System.out.printf("%d + %d\n", sum, j);
//증감식
i++
}
System.out.printf("%d부터 %d까지의 총 합은 %d 입니다.", x, y, sum);
}
#02. do-while문 (안중요)
while문이 조건의 성립 여부에 반복 수행을 결정하므로 만약 조건이 처음부터 거짓이라면 한번도 수행하지 않는다.
int a = 10;
while (a < 10) {
// 이 블록은 한번도 실행되지 않는다
}
do-while문은 선실행, 후판별 형태로 구성된다.
일단 {}
안의 구문을 1회 실행하고 나서 조건을 판별하여 계속 수행할지 여부를 판단한다.
int i = 0; //초기식
do {
/* ... 반복 실행될 구문 ... */
i++; // 증감식
} while (i < 10); // 조건식
만약 아래와 같이 조건이 거짓이더라도 우선 한번은 실행한 후 조건을 판별하기 때문에 do-while문은 최소 한 번은 실행된다.
int a = 10;
do {
// 블록은 한번만 실행된다.
} while (a < 10);
강사님 개인적으로 한번도 사용 안해보심 do-while문이 존재하지 않는 언어도 많다.
#03. for문 (매우중요)
초기식, 조건식, 증감식을 하나의 괄호안에 모두 명시하는 형태. while이나 do-while보다 반복에 필요한 요건을 한눈에 파악할 수 있기 떄문에 훨씬 간결하다.
for (초기식; 조건식; 증감식) {
/* 반복 실행할 구문 */
}
for1.java
0부터 10보다 작은 동안 1씩 증가하는 변수값의 변화과정 확인하는 예제
public class For1 {
public static void main(Stirng[] args) {
for (int i=0; i < 10; i++) {
System.out.printf("i=%d\n", i);
}
}
}
For2.java
1부터 10까지의 총 합을 구하는 프로그램
public class For2 {
public static void main(String[] args) {
// 총합을 구하기 위해서는 값을 누적 합산할 변수를 0으로 초기화 하고 시작해야 한다
int sum = 0;
for (int = 1; i <= 10; i++) {
// sum에 i의 값이 1부터 10까지 변하는동안 누적합산 한다.
sum += i;
//중간과정 출력
System.out.printf("i=%d, sum=%d\n", i, sum);
}
}
}
For3.java
구구단 출력
import java.util.Scanner;
public class For3 {
public static void main(String [] args) {
Scanner reader = new Scanner(System.in);
System.out.print("숫자를 입력하세요");
int x = reader.nextInt();
for (int y = 1; y < 10; y++) {
System.out.printf("%d x %d = %2d\n", x, y, x * y);
}
}
}
출력결과
숫자를 입력하세요 3 <-- 3입력해줌 (2를 입력시 2부터 9까지의 구구단이 나옴)
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
For4.java
강사님 답안
import java.util.Scanner;
public class For4 {
public static void main(String [] args) {
Scanner reader = new Scanner(System.in);
System.out.print("x의 값을 입력하시오");
int x = reader.nextInt();
System.out.print("y의 값을 입력하시오");
int y = reader.nextInt();
int sum = 0;
// 초기식; 조건문; 증감식;
for (int i=x; i<=y; i++) {
System.out.printf("%d + %d\n", sum, i);
sum += i; // 반복될 구문
}
System.out.printf("%d부터 %d까지의 총합 : %d", x, y, sum);
}
}
결과출력
x의 값을 입력하시오1
y의 값을 입력하시오10
0 + 1
1 + 2
3 + 3
6 + 4
10 + 5
15 + 6
21 + 7
28 + 8
36 + 9
45 + 10
1부터 10까지의 총합 : 55