JAVA

[Eclipse] for문 예제

kangjisoo 2021. 6. 18. 09:33

1. 1~10까지 출력

System.out.println("1. 1~10까지 출력");
for(int i = 1; i <=10; i++) {
	System.out.print(i + " ");
}
        
//결과
1. 1~10까지 출력
1 2 3 4 5 6 7 8 9 10 

 

2. 10~1까지 출력

System.out.println("2. 10~1까지 출력");
for(int i = 10; i >= 1; i--) {
System.out.print(i+ " ");
}

//결과
2. 10~1까지 출력
10 9 8 7 6 5 4 3 2 1 

 

3. 1~10 짝수만 출력

System.out.println("3. 1~10 짝수만 출력");
for(int i = 1; i <= 10; i++) {
	if(i%2 == 0) {
	System.out.print(i+ " ");
		}
}

//결과
3. 1~10 짝수만 출력
2 4 6 8 10 

 

4. "1+2+3+...10=55"  출력 (1~10까지)

System.out.println("4. \"1+2+3+...10=55\"  출력 (1~10까지)");
int sum = 0;
	for(int i = 1; i <= 10; i++) {
	sum+=i;
	if(i==10) {
		System.out.print(i + "=");
		break;
	}
	System.out.print(i + "+");
}
System.out.println(sum);

//결과
4. "1+2+3+...10=55"  출력 (1~10까지)
1+2+3+4+5+6+7+8+9+10=55

 

5. 1~10 짝수는 *, 홀수는 숫자로 출력

//	 1 * 3 * 5 * 7...*
System.out.println("5. 1~10 짝수는 *, 홀수는 숫자로 출력");
for(int i = 1; i <=10; i++) {
	if(i%2 == 0) {
	System.out.print(" * ");
	}else {
		System.out.print(i);
	}
}

//결과
5. 1~10 짝수는 *, 홀수는 숫자로 출력
1 * 3 * 5 * 7 * 9 * 

 

6. 아래 주석과 같이 출력

//	11111
//	22222
//	33333
//	44444
//	55555
System.out.println("6.");
for(int i = 1; i <= 5; i++) {
	for(int j = 1; j <= 5; j++) {
		System.out.print(i);
	}
	System.out.println();
}

//결과
6.
11111
22222
33333
44444
55555

 

7. 아래 주석과 같이 출력

//	55555
//	44444
//	33333
//	22222
//	11111
System.out.println("7.");
for(int i = 5; i >= 1; i--) {
	for(int j = 1; j <= 5; j++) {
		System.out.print(i);
	}
	System.out.println();
}

//결과
7.
55555
44444
33333
22222
11111

 

8. 아래 주석과 같이 출력

//	1 2 3 4 5
//	6 7 8 9 10
//	11 12 13 14 15
//	16 17 18 19 20

System.out.println("8.");
for(int i = 0; i <= 3; i++) {
	for(int j = 1; j <= 5; j++) {
		System.out.print((j+5*i)+ "\t");
				
	}
	System.out.println();
}

//결과
8.
1	2	3	4	5	
6	7	8	9	10	
11	12	13	14	15	
16	17	18	19	20