YSHUSH

For 본문

Coding/Java

For

코딩; 2021. 12. 8. 22:48

 

˙loop문 = 순환문 = 반복문
 
˙for : 지정 회수에 따라서 반복하는 제어문
 
˙형식 :
변수선언 //함수 안에서 선언하지 않을 경우 밖에서 변수선언
 
for( 변수의(선언)초기화; 조건식; 연산식; ) { 

 

처리


  }
 
  변수의 선언(1)
 
  for(  (3)  ;  (2)(6)(9)  ;  (5)(8)  ) {
 
  처리(4)(7)


  }

 

(9)에서 false일 경우 (10)밖으로 빠짐

 

		int n;	// 변수 n을 정의
		
		for( n = 0; n < 2; n++ ) {		// n = 1 n = 2
                                        // 변수 n이 2보다 작으므로 loop 0을 출력한 후 1을 더해
                                        // 1이 되고 2보다 작으므로 loop 1을 출력한 후 1을 더해
                                        // 2가 되고 2보다 작지 않게 되므로 반복이 끝나게 된다.
			System.out.println("for loop" + n);
		}

 

˙블록괄호 에서 선언한 변수는 괄호 안에 개입할 수 있으나
    블록괄호 에서 선언한 변수는 괄호 밖에 개입할 수 없다.

    for( int i = 0; i < 10; i++ ) {		// i의 초기값은 0, i가 10보다 작으므로 0을 출력하고
    System.out.print(i + " ");    		// 1이 더해져 반복문으로 가며 9가 될때까지 반복한다.
    }						// result = 0 ~ 9까지 출력
    System.out.println();

    for( int i = 1; i <= 100; i++) {	// 변수 i의 초기값은 1, i가 100보다 작거나 같으므로
    System.out.print(i + " ");		// 1을 출력하고 1이 더해져 반복문으로 가며 100이 될
    }                                   // 때까지 반복한다. result = 1 ~ 100까지 출력
    //변수 i는 이름만 같을 뿐 서로 다른 함수 내에서 정의되었으므로 계속 사용할 수 있음
    System.out.println();

    for(int i = 10; i > 0; i--) {		// 변수 i의 값은 10, i가 0보다 크므로 10을 출력하고
    System.out.print(i + " ");		    	// 1을 빼고 9가 되어 같은 과정을 1이 될때까지 반복.
    }						// result = 10 ~ 1까지 출력
    System.out.println();

    for(int i = 0; i < 10; i=i+2) {		// 변수 i의 초기값은 0, i가 10보다 작으므로 0을 출력,
    System.out.print(i + " ");			// 2가 더해져 2가되어 10보다 작을때까지 반복한다.
    }						// result = 0, 2, 4, 6, 8
    System.out.println();

 

˙무한루프

	// endless loop
	for(int i = 0;	; i++) {	//조건문을 빼면 무한루프
	System.out.println(i + " ");

 

˙1 ~ 100까지 숫자를 더한 값을 구하라

	int sum = 0;					// i의 초기값은 1, i가 100보다 작거나 같을 때 1씩 더 
	for(int i = 1; i <= 100; i++) {			// 하며 i의 값이 100될때까지 반복한다.
		sum = sum + i;				// result = 5050
	// sum += i; 위와 같은 값
	}
	System.out.println("sum: " + sum);

 

˙학생 6명의 국어성적의 합계와 평균
90, 85, 95, 100, 85, 75

    int[] numArr = new int[6];
        numArr[0] = 90;
        numArr[1] = 85;
        numArr[2] = 95;
        numArr[3] = 100;
        numArr[4] = 85;
        numArr[5] = 75;

    sum = 0;	
    for(int i = 0; i < numArr.length; i++) {
    sum += numArr[i];
    }
    System.out.println("sum: " + sum);
    double avg = (double)sum / numArr.length;

    // 성적의 평균
    System.out.println("avg: " + avg);
    
    // 1. 행이 6개인 배열 numArr을 정의한다.
    // 2. sum의값을 초기화, i의 초기값은 0, 배열의 길이인 6 미만으로 1씩 더하며
    //    반복하고 배열의 길이인 6개의 값을 0번째부터 모두 더한다. 그리고 나서 출력. 
    // 3. 점수의 총 합과 배열의 길이인 6을 나누어 평균값을 출력한다.

 

˙이름과 번호찾기

	String names[] = {"홍길동", "일지매", "성춘향", "홍두깨"};
		// 성춘향을 찾아라
		// 번호도 찾아라
	int number = 0;
	for(int i = 0; i < names.length; i++) {
		number++;
		if(names[i].equals("성춘향")) {
			System.out.println("찾았습니다!");
			System.out.println("번호는" + (i + 1) + "번입니다.");				
		}
	}
    
    // 1. name배열을 정의한 후, 번호를 정의한 number의 값을 초기화한다. 
    // 2. i의 초기값은 0, 0부터 배열의 길이인 4미만으로 1씩 더하며 반복
    // 3. 번호 number의 값도 1씩 더해진다.
    // 4. name 배열의 i번째 값이 성춘향과 일치하면 찾았습니다와 번호를 출력
    // 5. result = 찾았습니다! 번호는 3번입니다.

 

˙최고점수 출력하기

	int max = numArr[0]; //numArr[0]의 값을 넣어 값이 도망가지 않도록 함
	for(int i = 1; i < numArr.length; i++ ) { // int i = 1인 이유는 0번째 순서부터 비교하기 때문에
		if(max < numArr[i]) {
			max = numArr[i];	// max는 0에서 90이 되고 1번째에 들어와 조건이 성립되지 않고 넘어가 2번째에 들어가 95가 되고  
		}
	}
	System.out.println("max: " + max);
    
    // 1. 배열의 0번째 값을 정의하여 0번째부터 찾기 때문에 i의 값을 1로 정의한다.
    // 2. 배열의 길이인 6미만으로 1씩 더하며 반복하고 값이 변수 max보다 작을때 까지 찾는다.
    // 3. 최대값보다 작은 값이 나오지 않을 경우 그 값을 최대값으로 정의하며 출력한다.
    // 4. result -> max: 100

 

˙for each문

	for(int i = 0; i < names.length; i++) {
		System.out.println(names[i]);
	}
		
	for(int num : numArr) {		// [0] ~ [n-1]	JS에서는 for( n in arr )
		System.out.print( num + " ");
	}
	System.out.println();
		
	for(String name : names) {
		System.out.print(name + " ");
	}
	System.out.println();

 

˙for문 안에 for문 -> 2중 for문

	for(int i = 0; i < 10; i++) {
		System.out.println("i = "+ i);
			
		for(int j = 0; j < 5; j++) {
			System.out.println("\tj = "+ j);
		}
	}

 

˙2중 for문 - 구구단

	for(int i = 1; i < 10; i++) {
			
		for(int j = 1; j < 10; j++) {
				
		System.out.print(i + "x" + j + "=" + (i * j) + " ");
		}
		System.out.println();
	}

 

˙2차원배열

	int array2[][] = {
			{11, 12, 13, 14,},	// array2[0].length
			{21, 22, 23, 24,},
			{31, 32, 33, 34,}
	};
		
	for(int i = 0; i < array2.length; i++) {			// array2.length = 덩어리의 개수
		for(int j = 0; j < array2[i].length; j++) {		// array2[i].length = i행의 덩어리의 개수
			System.out.print(array2[i][j] + " ");
		}
		System.out.println();
	}

'Coding > Java' 카테고리의 다른 글

Break  (0) 2021.12.08
While  (0) 2021.12.08
거스름돈 구하기  (0) 2021.12.07
Switch  (0) 2021.12.07
If  (0) 2021.12.07