본문 바로가기
Programing/JAVA (& 혼공자Java)

자바(Java) - ★찍기1

by a.k.a DUKI 2020. 9. 16.
728x90
반응형

책을 보거나, 구글링을 하다보면, 반복문 연습에는 ★찍기 연습이 제일 좋은 것같다.

그 만큼 예제도 많고, 연습하기 좋은 것같다.

 

★찍기 연습을 하면 기본적으로 반복되는 코드를 간결하게 줄일 수 있으니, 연습을 해두면 좋을 것 같다.

반복문과 조건제어문을 제대로 이해하고 넘어가도록 하자.

 

그런 의미에서 ★찍기 예제를 풀어보자.

 

 

ex1) ★★★★★ 이렇게 나오려면?

//while문 이용하여 ★찍기
	int i = 0;
	while(i<5) {
		System.out.print("★");
		i++;
	}
	
    System.out.println();
	System.out.println("---");

//for문 이용하여 ★찍기
	for(int j =0; j<5; j++) {
		System.out.print("★");
	}

while문과 for문 둘 다 같은 값이 나올 수 있다. 아무래도 for문이 코드가 더 간결해보여서 적응 되면 for문을 더 많이 쓸 것같다. 

앞서 공부한 것 처럼

  • for문: 지정된 횟수만큼 반복할 때 사용

  • while문: 조건식에 따라 반복할 때 사용

 

ex2) ★★☆★★ 이렇게 나오려면?

//while문 이용	
    int i = 0;
	while(i<5) {
		i++;
		if(i==3) {
			System.out.print("☆");
		}
		else{
			System.out.print("★");
		}
		
	}
	
    System.out.println();
	System.out.println("---");

//for문 이용
	for(int j =0; j<5; j++) {
		if(j==2) {
			System.out.print("☆");
		}
		else{
			System.out.print("★");
		}
	}

 

ex3) ☆☆★○☆ 이렇게 나오려면?

for(int i=0; i<5; i++) {
	if(i==2) {
		System.out.print("★");
	}else if(i==3) {
		System.out.print("○");
	}else {
		System.out.print("☆");
	}
}	

 

ex3) 이렇게 나오려면?

☆☆★☆☆
☆☆★☆☆
☆☆★☆☆

for (int i = 0; i < 3; i++) { //3단
	for (int j = 0; j < 5; j++) { //5개별
		if (j == 2) {
			System.out.print("★");
		} else {
			System.out.print("☆");
		}
	}
	System.out.println(); //한 단이 끝났을때 줄바꿈
}

 

 

ex4) 그럼 이 코드는 별이 몇개 찍힐까?

for (int y=0; y<10; y++) {
	for (int x=0; x<5; x++) {
		 System.out.print("★");
	 }
}

정답: 50개 (아마 이중 반복문을 이해했으면, 바로 나왔을 것이다.)

 

 

ex5) 이렇게 나오려면?

★ 

 

 

for (int i=0; i<5; i++) { //5단
	for (int j=0; j<i+1; j++) { //5개 별찍기이나, 
			//j<i+1을 해서 i수보다 1크게 증감되게 설정
		 System.out.print("★");
	 }
	System.out.println(); //단 끝날때 줄바꿈
}​
728x90
반응형

댓글