프로그래밍/자바(java) 융합개발자 2차

[자바 2일차] 21일차 - 반복문(for, while, do ~ while)

aSpring 2021. 1. 13. 14:56
320x100
728x90

 

2021/01/12 - [공부/자바(java) 융합개발자 2차] - [자바 기초] 20일차 일지 - Eclipse에서 Hello 출력, 변수, if문

 

com.day02

Exam01.java '안녕하세요'를 5번 출력하라

package com.day02;

public class Exam01 {

	public static void main(String[] args) {

		System.out.println("안녕하세요");
		System.out.println("안녕하세요");
		System.out.println("안녕하세요");
		System.out.println("안녕하세요");
		System.out.println("안녕하세요");
	}

}

안녕하세요
안녕하세요
안녕하세요
안녕하세요
안녕하세요

 

 

이렇게 쓰지 않고 반복문으로 써줄 수 있다.

0~4, 1~5, 10~6, 1 3 5 7 9 이런 식으로 해도 5번 반복할 수 있다.

for문을 사용할 수 있다.

package com.day02;

public class Exam01 {

	public static void main(String[] args) {
		
		for(int i = 0; i < 5; i++) {
		System.out.println("안녕하세요");
		}
	}
}

 

안녕하세요
안녕하세요
안녕하세요
안녕하세요
안녕하세요

 

package com.day02;

public class Exam01 {

	public static void main(String[] args) {
		
		for(int i = 0; i < 5; i++) {
		System.out.println("안녕하세요");
		}
		System.out.println(i);
	}
}

 

이렇게 적으면 에러가 나는데, int i는 for문 안에서만 쓸 수 있는 지역변수이기 때문에

main { } 영역에서는 i를 모른다고 한다!

 

구구단 2단 출력

package com.day02;

public class Exam01 {

	public static void main(String[] args) {
		
		for(int i = 1; i < 10; i++) {
		System.out.println("2 * " + i + " = "  + 2 * i);
		}
		
	}
}

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18

 

1부터 10까지 짝수만 출력

package com.day02;

public class Exam01 {

	public static void main(String[] args) {
		
		for(int i = 1; i < 11; i++) {
			if(i%2==0) {
				System.out.println(i);
			}
		}
		
	}
}

2
4
6
8
10

 

"\t"

해주면 tab키를 한 것만큼 띄워진다

package com.day02;

public class Exam01 {

	public static void main(String[] args) {
		
		for(int i = 1; i < 11; i++) {
			if(i%2==0) {
				System.out.print(i+"\t");
			}
		}
	}
}

2        4        6        8        10

 

package com.day02;

public class Exam01 {

	public static void main(String[] args) {
    
		for(int i = 2; i < 11; i+=2) {
			System.out.print(i+"\t");
            
		}
		
	}
}

2        4        6        8        10

 

 

for(초기값; 조건; 값변화) {

     조건에 맞는 동안 실행시킬 문장

}

 

Exam02 몇단을 할 지 입력받아서 그 단의 구구단을 출력하세요.

package com.day02;

import java.util.Scanner;

public class Exam02 {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		System.out.println("몇 단을 수행할까요?");
		int dan = sc.nextInt();
		
		for (int i = 1; i < 10; i++) {
			System.out.println(dan + " * " + i + " = " + dan * i );
		}
	}
}

몇 단을 수행할까요?
4
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20
4 * 6 = 24
4 * 7 = 28
4 * 8 = 32
4 * 9 = 36

 

구구단 합계 출력

package com.day02;

import java.util.Scanner;

public class Exam02 {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		System.out.println("몇 단을 수행할까요?");
		int dan = sc.nextInt();
		int total = 0;
		
		for (int i = 1; i < 10; i++) {
			System.out.println(dan + " * " + i + " = " + dan * i );
			total = total + dan * i;
		}
		System.out.println(dan + "단 결과의 총 합계는 "+total);
	}
}

몇 단을 수행할까요?
8
8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8단 결과의 총 합계는 360

 

지역변수는 초기값이 없으면 에러가 난다

 

total += dan * i;

이렇게 써줘도 됨

 

1부터 10까지의 합계를 구하라

package com.day02;

import java.util.Scanner;

public class Exam02 {

	public static void main(String[] args) {
    
    	int sum = 0;
		for(int i=1; i < 11; i++) {
			sum = sum + i;
		}
		System.out.println("1부터 10까지의 합 : " + sum);
	}
}

1부터 10까지의 합 : 55

 

1부터 50까지 짝수의 합을 출력하라

if 사용

package com.day02;

public class Exam02 {

	public static void main(String[] args) {
		
		int total = 0;
		
		for (int i = 1; i < 51; i++) {
			
			if(i%2 == 0) {
			total += i;
			}
		}
		System.out.println("1~50까지 짝수의 합 "+total);
	}
}

if 미사용

package com.day02;

public class Exam02 {

	public static void main(String[] args) {
		
		int h = 0;
		
		for (int i = 2; i < 51; i+=2) {
			h += i;
			}
		
		System.out.println("1~50까지 짝수의 합은 "+ h);
	}
}

1~50까지 짝수의 합 650

 

Exam03 몇 개를 입력받을 지 물어보고 그 수만큼 숫자를 입력하여 그 수들의 합계를 출력

package com.day02;

import java.util.Scanner;

public class Exam03 {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		System.out.println("몇 개의 숫자의 합을 구하실 건가요?");
		int no = sc.nextInt();
		int total = 0;
		System.out.println(no + "개의 숫자를 입력하세요");
		
		for(int i = 0; i < no; i++) {
		int no2 = sc.nextInt();
		total += no2;
		}
		System.out.println("숫자의 합 : " + total);
	}
}

몇 개의 숫자의 합을 구하실 건가요?
4
4개의 숫자를 입력하세요
2 3 7 8
숫자의 합 : 20

 

package com.day02;

import java.util.Scanner;

public class Exam03 {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		System.out.println("몇 개의 숫자의 합을 구하실 건가요?");
		int no = sc.nextInt();
		int total = 0;
		System.out.println(no + "개의 숫자를 입력하세요");
		
		for(int i = 0; i < no; i++) {
		total += sc.nextInt();
		}
		System.out.println("숫자의 합 : " + total);
	}
}
int no2 = sc.nextInt();
		total += no2;

이걸 한 줄로

total += sc.nextInt();

합쳐서 적어줘도 됨

 

1부터 100까지의 합을 구하는데

출력은

1~10까지의 합

1~20까지의 합

..

1~100까지의 합을 출력하라

package com.day02;

public class Exam03 {

	public static void main(String[] args) {

		int total = 0;
		
		for(int i = 1; i < 101; i++) {
		total += i;
		
		if (i%10==0) {
			System.out.println("1부터 "+ i +"까지의 합 " + total);
			}
		}
	}
}

1부터 10까지의 합 55
1부터 20까지의 합 210
1부터 30까지의 합 465
1부터 40까지의 합 820
1부터 50까지의 합 1275
1부터 60까지의 합 1830
1부터 70까지의 합 2485
1부터 80까지의 합 3240
1부터 90까지의 합 4095
1부터 100까지의 합 5050

 

1~10까지의 합을 구하는데 1+2+3+   +9+10 = 55 로 출력되게 하라

내 답

package com.day02;

public class Exam03 {

	public static void main(String[] args) {

		int total = 0;
		
		for(int i = 1; i < 11; i++) {
		total += i;
			System.out.print(i);
			
			if(i < 10) {
				System.out.print("+");
			}
		}
		System.out.println( "=" + total);
	}
}

1+2+3+4+5+6+7+8+9+10=55

 

선생님 답

package com.day02;

public class Exam03 {

	public static void main(String[] args) {

		int total = 0;
		
		for(int i = 1; i < 11; i++) {
		total += i;
			
			if(i != 10) {
				System.out.print(i + "+");
			} else {
            	System.out.print(i + "=");
            }
		}
		System.out.println(total);
	}
}

또는

package com.day02;

public class Exam03 {

	public static void main(String[] args) {

		int total = 0;

		for (int i = 1; i < 11; i++) {
			total += i;

			if (i == 1) {
				System.out.print(i);
			} else {
				System.out.print("+" + i);
			}
		}
		System.out.println("=" + total);
	}
}

1+2+3+4+5+6+7+8+9+10=55

 

프로그램을 짤 때 가독성이 중요

 

Ctrl + Shift + F 를 눌러주면 자동으로 정렬해준다.

 

Ctral + / 를 누르면 자동으로 주석처리를 해준다.

 

Exam04

1부터 10까지의 합 55
11부터 20까지의 합 155
21부터 30까지의 합 
..
91부터 100까지의 합 955
을 나타내어라

 

내 답

package com.day02;

public class Exam04 {

	public static void main(String[] args) {

		
		int i;
		int total = 0;
		
		for (i=1; i < 101; i++) {
			total += i;
			
			if (i%10 == 0) {
				System.out.println(i-9 + "부터" + i + "까지의 합" + total);
				total = 0;
			}
		}
	}
}

1부터10까지의 합 55
11부터20까지의 합 155
21부터30까지의 합 255
31부터40까지의 합 355
41부터50까지의 합 455
51부터60까지의 합 555
61부터70까지의 합 655
71부터80까지의 합 755
81부터90까지의 합 855
91부터100까지의 합 955

 

학생 수화 학줄에 앉을 학생 수를 입력받아 출력하시오(자리배치)

 ex)  학생이 10일 때 한 줄에는 1명씩만 앉을 것이다 라고 입력받으면

1 2 3

4 5 6

7 8 9

 

package com.day02;

import java.util.Scanner;

public class Exam04 {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		System.out.println("학생수, 한줄에 앉을 학생수 입력하시오");

		int student = sc.nextInt();
		int count = sc.nextInt();

		for (int i = 1; i <= student; i++) {
			System.out.print(i + "\t");
			if (i % count == 0) {
				System.out.println();
			}
		}
	}
}

학생수, 한줄에 앉을 학생수 입력하시오
10 4
1 2 3 4
5 6 7 8
9 10

 

총 몇 줄인지 출력하시오

package com.day02;

import java.util.Scanner;

public class Exam04 {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		System.out.println("학생수, 한줄에 앉을 학생수 입력하시오");

		int student = sc.nextInt();
		int count = sc.nextInt();
			
		int row = 0;
		if(student%count==0) {
			row = student/count;
		} else {
			row = (student/count) + 1;
		}
		System.out.println("총 라인 수 " + row);
		}
}

 if 대신 삼항연산자 사용

package com.day02;

import java.util.Scanner;

public class Exam04 {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		System.out.println("학생수, 한줄에 앉을 학생수 입력하시오");

		int student = sc.nextInt();
		int count = sc.nextInt();
		
		int r = (student%count==0) ? student/count : (student/count) +1;
		System.out.println("총 라인 수 " + r);
		}
	}

??

 

Exam6 while문 배우기

1) for문 이용 1~5까지 출력하라

package com.day02;

public class Exam05 {

	public static void main(String[] args) {
		
		int i;
		for(i=1; i<6; i++) {
			System.out.print(i+"\t ");
		}
	}
}

2) while을 이용 : 반드시 while문 안에 빠져나갈 수 있는 조건을 적어주어야 한다.

아니면 무한 루프.. -> 몇 번돌아가는지 모를 때 계속 돌리되 조건을 주고 조건에 맞으면 빠져나가게 한다.

package com.day02;

public class Exam05 {

	public static void main(String[] args) {
		
		int i=1;
		while (i<6) {
			System.out.println(i+"\t");
			i++;
		}
	}
}

3) do ~ while

package com.day02;

public class Exam05 {

	public static void main(String[] args) {
		
		int i=1;
		do  {
			System.out.println(i+"\t");
			i++;
		} while(i<6);
	}
}

while문과 do while의 결과 1 2 3 4 5 로 같았다. 하지만

조건을 i<1로 바꾸면

 

package com.day02;

public class Exam05 {

	public static void main(String[] args) {
		
		int m=1;
		while (m<1) {
			System.out.println(m+"\t");
			m++;
		}
		
		int i=1;
		do  {
			System.out.println(i+"\t");
			i++;
		} while(i<1);
	}
}

while문은 조건에 맞지 않아서 출력 X

do while문은 1번은 실행하고 조건을 확인하기 때문에 1이 출력됨

 

if문 안에 들어가는 문장이 1개일 때는 { } 없이 쓸 수 있다.

if(i==5) break;
for(i=1; i<10; i++) {
	if(i==5) break;
	System.out.println("i =" + i);

i =1
i =2
i =3
i =4

 

for로 1~10까지 돌게 해놨지만 i가 5일 때 빠져나오도록 break를 걸었으므로 4까지만 출력됨

 

for(i=1; i<10; i++) {
if(i==5) continue;
System.out.println("i =" + i);
}

i =1
i =2
i =3
i =4
i =6
i =7
i =8
i =9

 

-> 5가 출력이 되지않는 걸 볼 수 있다.

i가 5이면 for로 다시 돌아가서 i+1이 되기 때문!

 

==> 반복문을 제어할 수 있는 것 : break; continue;

 

Exam06 1~10까지 홀수를 구하라

package com.day02;

public class Exam06 {

	public static void main(String[] args) {
		// 1~10까지 홀수를 구하라
		
		for(int i=1; i<11; i++) {
			if (i%2==1)
			System.out.println(i);
		}
	}
}

 

홀수의 합을 구하라

package com.day02;

public class Exam06 {

	public static void main(String[] args) {
		// 1~10까지 홀수를 구하라
		
		int sum = 0;
		for(int i=1; i<11; i++) {
			if (i%2==1) {
			sum += i;
			}
		}
		System.out.println("1~10까지 홀수의 합 : " + sum);
	}
}

 

for, if, continue를 사용해서 1~10까지의 홀수의 합을 구하라

package com.day02;

public class Exam06 {

	public static void main(String[] args) {
		// 1~10까지 홀수를 구하라
		
		int sum = 0;
		for(int i=1; i<11; i++) {
			if (i%2==0) continue;
			sum += i;
		}
		System.out.println("1~10까지 홀수의 합 : " + sum);
	}
}

i/2의 나머지가 0인 짝수가 되면 아래 문장을 실행하지 않고 다시 for문으로 돌아가서 i+1을 함

-> 짝수는 빼고 홀수의 합만 더함

 

또는

package com.day02;

public class Exam06 {

	public static void main(String[] args) {
		// 1~10까지 홀수를 구하라
		
		int sum = 0;
		for(int i=1; i<11; i++) {
			if (i%2!==1) continue;
			sum += i;
		}
		System.out.println("1~10까지 홀수의 합 : " + sum);
	}
}

 

Exam07. 양수를 입력받는데 마지막은 -1. 입력한 수의 합계와 평균을 구하시오

ex) 10 5 6 9 -1

-1은 종료라는 뜻이며 10 5 6 9 만 합계와 평균을 구한다.

->  숫자 몇 개를 입력할지 모르니까 While문을 쓰고 -1이면 빠져나오게 해야 하니까 break

package com.day02;

import java.util.Scanner;

public class Exam07 {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		System.out.println("수를 입력해주세요. 마지막은 -1입니다.");
		int sum = 0;
		int cnt = 0;
		
		while(true) {
			int num = sc.nextInt();
			if(num==-1) break;
			sum += num;
			cnt++;
		}
		System.out.println("합계 : " + sum + " 평균 : " + sum/cnt);
	}
}

 

Exam08

2*1=2

2*2=4

2*3=6

출력

package com.day02;

public class Exam08 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		for(int i=1; i<4; i++) {
			System.out.println("2 * " + i + " = " + 2*i);
		}
	}
}

 

2*1=2

2*2=4

2*3=6

이런 식으로 3, 4단도 나오도록 -> 이중 for문

package com.day02;

public class Exam08 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
	for (int j=2; j<5; j++) {
		for(int i=1; i<4; i++) {
			System.out.println( j + " * " + i + " = " + j*i);
			}
		System.out.println();
		}
	}
}

 

3단, 5단, 7단 모두 출력

내 답

package com.day02;

public class Exam08 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
	for (int j=3; j<8; j+=2) {
		System.out.println( j+"단");
		for(int i=1; i<10; i++) {
			System.out.println( j + " * " + i + " = " + j*i);
			}
		System.out.println();
		}
	}
}

또는

package com.day02;

public class Exam08 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
	for (int j=3; j<8; j++) {
		if(j%2==0) continue;
		System.out.println( j+"단");
		for(int i=1; i<10; i++) {
			System.out.println( j + " * " + i + " = " + j*i);
			}
		System.out.println();
		}
	}
}

 

아래와 같이 출력하기

123456789

12345678

1234567

123456

12345

1234

123

12

1

 

내 답

package com.day02;

public class Exam08_1 {

	public static void main(String[] args) {
		
		for(int i=9; i>0; i--) {
			for(int j=1; j<10; j++) {
				System.out.print(j);
				if(j==i) break;
			}
			System.out.println();
		}
	}
}

 

 

선생님 풀이

package com.day02;

public class Exam08_1 {

	public static void main(String[] args) {
		
		for(int i=9; i>0; i--) {
			for(int j=1; j<=i; j++) {
				System.out.print(j);
			}
			System.out.println();
		}
	}
}

 

Exam08_2 이중 for문으로 아래와 같은 출력값

1부터10까지의 합 55 
11부터20까지의 합 155 
21부터30까지의 합 255 
31부터40까지의 합 355 
41부터50까지의 합 455 
51부터60까지의 합 555 
61부터70까지의 합 655 
71부터80까지의 합 755 
81부터90까지의 합 855 
91부터100까지의 합 955

package com.day02;

public class Exam08_2 {

	public static void main(String[] args) {
		
		
		for(int i=1; i<=100; i+=10) { //i= 1, 11, 21, 31 ,.. 91
			int sum=0;
			int j;
			for(j=i; j<i+10; j++) {
				sum += j;
			}
			System.out.println(i + "부터" + (j-1) + "까지의 합 " + sum);
		}
	}
}

두 가지 방법을 비교해보기

 

Exam09

2*1 = 2   3*1 = 3   4*1=4          9*1=9

..

2*9 = 18                                9*9=81

 

package com.day02;

public class Exam09 {

	public static void main(String[] args) {
		
		for(int i=1; i<10; i++) {
			for(int j=2; j<10; j++) {
				System.out.print(j + "*" + i + "=" + j*i + "\t");
			}
			System.out.println();
		}
	}
}
더보기

2*1=2   3*1=3  4*1=4   5*1=5   6*1=6  7*1=7   8*1=8  9*1=9
2*2=4   3*2=6  4*2=8   5*2=10 6*2=12 7*2=14 8*2=16 9*2=18
2*3=6   3*3=9  4*3=12 5*3=15 6*3=18 7*3=21 8*3=24 9*3=27
2*4=8   3*4=12 4*4=16 5*4=20 6*4=24 7*4=28 8*4=32 9*4=36
2*5=10 3*5=15 4*5=20 5*5=25 6*5=30 7*5=35 8*5=40 9*5=45
2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 7*6=42 8*6=48 9*6=54
2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 8*7=56 9*7=63
2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 9*8=72
2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81

 

아래와 같이 출력되도록 하여라

*********(7)
*****(5)
***(3)
*(1)

내 답

package com.day02;

public class Exam09 {

	public static void main(String[] args) {
		for(int i=7; i>0; i -= 2) {   // 7
			for(int j=1; j<=i; j++) {  // 1
				System.out.print("*");
			}
			System.out.println("("+ i +")");
		}
	}
}

안에 for는 7번, 밖의 for는 4번 돌아야 함

둘 다 okay

 


복습

Exam10_1

2*1=2
2*2=4
2*3=6

3*1=3
3*2=6
3*3=9

4*1=4
4*2=8
4*3=12

 

package com.day02;

public class Exam10 {

	public static void main(String[] args) {
		
		for(int i=2; i<5; i++) {
			for(int j=1; j<4; j++) {
				System.out.println(i + "*" + j + "=" + i*j );
			}
			System.out.println();
		}
	}
}

 

Exam10_2

*********(7) 
*****(5) 
***(3) 
*(1)

package com.day02;

public class Exam10 {

	public static void main(String[] args) {
		
		for(int i=7; i>0; i-=2) {
			for(int j=1; j<=i; j++) {
				System.out.print("*");
			}
			System.out.println("(" + i + ")");
		}
	}
}

또는

package com.day02;

public class Exam10 {

	public static void main(String[] args) {
		
		for(int i=7; i>0; i-=2) {
			for(int j=i; j>0; j--) {
				System.out.print("*");
			}
			System.out.println("(" + i + ")");
		}
	}
}

 


 

다음 시간 : p.126

배열, 클래스 할 예정

728x90
728x90