for 문을 알아보자 ! !
for(초기화식; 조건식; 증감식) {
// 조건식이 참인경우 실행블럭
}
for문을 이용해 1~5까지를 출력해보자 ! !
package interationex;
public class ForEx {
public static void main(String[] args) {
int k = 0;
for(int i=0; i<5; i++) {
k++;
System.out.println(k);
}
}
}
결과값 :

1부터 5까지의 합을 구해보자 ! !
- sum 변수에 누적산하여 for문을 이용하여 값을 누적 시킬 수 있다.
package interationex;
public class ForEx4 {
public static void main(String[] args) {
int sum = 0;
for (int i=1; i<6; i++) {
sum +=i;
System.out.printf("i = %s, sum = %s\n", i,sum);
}
}
}
결과값 :

2차원배열의 좌표값을 2중 for문을 이용하여 출력해보자 ! !
- 첫번째 값은 0이고 x나 y축으로 이동할때마다 1씩 추가된다.
package interationex;
public class ForEx5 {
public static void main(String[] args) {
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
System.out.printf("(%s,%s)",i, j);
}
System.out.println();
}
}
}
결과값 :

for문을 이용해 구구단을 만들어보자!!
- 단의 수가 될 dan 변수에 숫자를 담아 원하는 단을 선정할 수 있다.
package interationex;
public class ForEx {
public static void main(String[] args) {
int dan = 3;
for(int i=1; i<10; i++) {
System.out.printf("%s * %s = %s \n", dan, i, dan*i);
}
int i = 10;
System.out.println(i);
}
}
결과값 :

각 줄에 5개씩 번호 매기기
package interationex;
public class ForEx5 {
public static void main(String[] args) {
int k=0;
for(int i=0; i<5; i++) {
k++;
for(int j=0; j<5; j++) {
System.out.print(k);
}
System.out.println();
}
}
}
결과값 :

한번에 구구단 9단까지 출력해보자 ! !
- 2중 for문을 이용하여 구구단을 한번에 출력 할수 있다.
package interationex;
public class ForEx {
public static void main(String[] args) {
for (int j=2; j<10; j++) {
System.out.printf("========= %s 단 시작 ==========\n", j);
for(int i=1; i<10; i++) {
int rs = j*i;
System.out.printf(" %s * %s = %s \n", j, i, rs);
}
System.out.printf("========= %s 단 종료 ==========\n", j);
System.out.println();
}
}
}
결과값 :


do ~ while문
- 최초의 do는 무조건 실행되고 이후에 while문이 실행된다.
public class DoWhileEx {
public static void main(String[] args) {
int i = 10;
do {
System.out.println("i = "+i);
}while (i < 10);
}
}
결과값 :
