본문 바로가기
Java 개발자 수업 강의노트/Java 소스

1,2,3,4,5,4,3,2,1로 출력하기

by 캬캬백곰 2012. 4. 19.
728x90

#순차적으로 증가하다 어느 한 점에서 감소하는 값을 출력.

결과: 1    2    3    4    5    4    3    2    1

public class For5 {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // 1 2 3 4 5 4 3 2 1 출력
  
  //for문 두 개
  for(int i=1; i<=5; i++){
   System.out.print(i+"\t");
  }
  
  for(int j=4; j>0; j--){
   System.out.print(j+"\t");
  }
  
  System.out.println();// 한 줄 내리기
  
  //for문 및 if문 활용
  int a=1;
  
  for(int i=1; i<10; i++){
   
   if(i<5){
    System.out.print(a+"\t");
    a++;
   }else{
    System.out.print(a+"\t");
    a--;
   }
   
  }

  System.out.println(); // 한 줄 내리기
  

 // if를 또 다르게 활용
  int b=0;
  int num=1;
  
  for(int i=1; i<10; i++){
   
   a=a+num;
   System.out.print(a+"\t");
   
   if(i==5){
    num=num*-1;
   }
  }

 }

}

*세 가지 경우 모두 같은 값을 출력

 

728x90
반응형