반응형
for문(반복적으로 실행하는 반복문)
1
2
3
4
5
for(초기화식; 조건식; 증감식){
 
    실행문;// 조건식이 true일때 실행된다.
            // 증감식만큼 반복적으로 실행된다.
 }// 조건식이 false일때 종료된다.
cs

 

 

1~10까지 출력
1
2
3
4
5
6
7
8
public class example01 {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
    }
 
}
cs

● 실행결과

i가 10만큼 반복되어 출력된다.

 

1~100까지의 합을 출력
1
2
3
4
5
6
7
8
9
10
public class example2 {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i &lt;= 100; i++) {
            sum += i; // sum = sum + i
        }
        System.out.println(sum);
    }
 
}
cs

● 실행결과

sum이란 변수를 두고, for반복문을 돌면서 sum에 더하기를 한다.

조건식이 종료된뒤 합계를 출력한다.

 

 

구구단 출력하기
1
2
3
4
5
6
7
8
9
10
public class example3 {
    public static void main(String[] args) {
        for (int i = 2; i &lt; 10; i++) {
            System.out.println(i + "단");
            for (int j = 1; j &lt; 10; j++) { // 이중 for 문
                System.out.println(i + "*" + j + "=" + (i*j)); 
            }
        }
    }
}
cs

● 실행결과

이중for문을 이용하여 2단 ~ 9단까지의 구구단을 출력하였다.

.

.

.

 

별 그리기(2차원 별찍기)
1
2
3
4
5
6
7
8
9
10
public class example4 {
    public static void main(String[] args) {
        for (int i = 0; i &lt; 5; i++) {
            for (int j = 0; j &lt; 5; j++) {
                System.out.print("*");
            }
            System.out.println("");
        }
    }
}
cs

● 실행결과

 

삼각형 별 그리기
1
2
3
4
5
6
7
8
9
10
public class example5 {
    public static void main(String[] args) {
        for (int i = 1; i &lt; 6; i++) {
            for (int j = 0; j &lt; i; j++) {
                System.out.print("*");
            }
            System.out.println("");
        }
    }
}
cs

● 실행결과

 

역삼각형 별 그리기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class example4 {
    public static void main(String[] args) {
        for (int i = 1; i &lt; 6; i++) {
            for (int j = 5; j &gt; 0; j--) {
                if(i &lt; j){
                    System.out.print(" ");
                }else{
                    System.out.print("*");
                }
            }
            System.out.println("");
        }
    }
}
cs

● 실행결과

반응형

+ Recent posts