웹개발 교육/Java

[30일] Java (11) - 연습 문제

ewok 2022. 9. 6. 13:23

문제 1

//문1)알파벳을 아래와 같이 한줄에 5개씩 출력하시오
/*
   ABCDE
   FGHIJ
   KLMNO
   PQRST
   UVWXY
   Z
*/
char c=65;
for(int a=0; a<6; a++) {			
	for(int b=0; b<5; b++) {
		System.out.print(c);
		c++;
		if(c==91) {
			break;
		}//if end
	}//for end
	System.out.println();
}//for end

// 다른 풀이
int count=0;
for(char ch='A'; ch<='Z'; ch++) {
	count++;
	System.out.print(ch);
	//System.out.print(count);
	if(count%5==0) {
		System.out.println();
	}
}//for end

 

문제 2

//문2)아래와 같이 출력하시오
/*
   ####
    ###
     ##
      #
*/

for(int i=0; i<4; i++) {
	for(int j=1; j<5; j++) {
		if(j<=i) {
			System.out.print(' ');
		} else {
			System.out.print('#');
		}			
	}
	System.out.println();
}

// 다른 풀이
for(int a=1; a<=4; a++) {
	for(int b=1; b<=4; b++) {
		if(a<=b) {
			System.out.print("#");
		}else {
			System.out.print(" ");
		}//if end
	}//for end
	System.out.println();
}//for end

 

문제 3

/* 문3) 다음식의 결과값을 구하시오
       1   2    3    4    5      99
       ─ - ─ + ─ - ─ + ─ ...     ──   = ?  결과값만 출력
       2   3    4    5    6      100
*/

double hap=0.0;
for (double i=1; i<100; i++) {
	if (i%2==1) {
		hap = hap + i/(i+1);
	} else {
		hap = hap - (i/(i+1));
	}//if end			
}//for end
System.out.println(hap);

// 다른 풀이
double happ=0.0;
boolean flag=false;
for(int a=1; a<100; a++) {
	if(flag) {
		happ = happ - (a/(double)(a+1));
		flag=false;
	} else {
		happ = happ + (a/(double)(a+1));
		flag=true;
	}//if end
}//for end
System.out.println(happ);

 

문제 4

//문4)아래와 같이 계산해서 출력하시오
/*    
   1+....+10=55
   11+....+20=155
   21+....+30=255

   81+....+90=
   91+....+100=955   
*/

int sum=0;
for(int a=10; a<=100; a+=10) {
	for(int b=a-9; b<=a; b++) {
		sum=sum+b;
	}//for end
	System.out.println((a-9) + "+...+" + a + "=" + sum);
	sum=0;
}//for end

 

문제 5

//문5)어느 달팽이는 낮에는 3cm 올라가고, 밤에는 2.5cm 내려온다고 할때
//   달팽이가 13cm의 나무 꼭대기에 올라가려면 며칠이 걸리는지 구하시오
int day=0;  //결과값
double snail=0.0;  //달팽이

while(true) {
	day++;
	snail=snail+3.0;
	if(snail>=13.0) {
		break;
	} else {
		snail=snail-2.5;
	}//if end
}//while end
System.out.println(day+"일");