본문 바로가기
국비 학원 가서 개발새발

국비학원 2일차) 반복문(for, while) Array(배열)

by 휴일이 2022. 9. 27.

for문

 

for(초기화식;조건식;증감식) {

실행문;

}

으로 구성

 

 

예)

for(int i=0;i<5;i++) {

System.out.prinltn("hello world");

}

 

for(int i=0, j=100; i<=50 && j>=50; i++,j--) { }

초기화식,조건식,증감식이 여러개도 가능

 

 

2중 for문

 

for() {

실행문;

   for() {

   실행문;

     }

}

이런 식으로 for문 안에 for문이 있을 수도 있다

 

예) 구구단을 만드는 식

package step1;

public class For5 {

	public static void main(String[] args) {
		int i, j;
		for(i=0;i<10;i++) {
			for(j=2;j<10;j++) {
				if(i==0) {
					System.out.print(j+"단\t");
				} else {
					System.out.print(j+"*"+"i"+"="+j*i+"\t");
				}
			}
			System.out.println();
		}
	}

}

 

 

while문

 

while(조건식) {

실행문;

}

 

조건이 false일 경우 실행하지 않고

true일 경우 실행하며 안의 내용을 반복한다

 

 

int i=1;

while(i<=10) {

System.out.println(i+" ");

i++;

}

 

위 코드는 아래 for문과 동일하다

 

for(int i=1;i<=10;i++) {

System.out.println(i+" ");

}

 

for문이 더 간결하고 쉬우므로

while문은 거의 사용하지 않는다

 

조건문 if와 반복문 for가 주로 이용된다

 

 

break문

switch문을 종료할 때 쓰이고

반복문 for, while, do-while 문을 실행 중지할 때도 쓰인다

 

반복문에 이름이 붙어있다면

Label : for(...) {

 

break Label;

}

 

한다면 반복문도 종료된다

 

continue문

반복문 for, while, do-while에서 사용되는데

continue문이 실행되면 for문이나 while문의 처음으로 돌아간다

 

 

예)

 

for(int i=1;i<=10;i++) {
	if(i%2 != 0) {
    continue;
    }
    System.out.println(i+" ");
 }

 

이런 식으로 사용 된다

 

 

배열Array

 

변수는 하나의 값만 저장할 수 있으나

배열로 생성하면 하나의 변수에 여러가지 값을 넣을 수 있다

 

int[] score = {100,20,30,40};

배열의 순서대로

score[0] == 100

score[1] == 20

score[2] == 30 ....

을 나타내게 된다

 

배열은 같은 타입의 값만 관리하며

배열의 길이는 늘이거나 줄일 수 없다

 

변수는 처음에 선언한 후로 값 목록을 대입할 수 없으니

선언한 시점과 목록이 대입되는 시점이 다르다면

 

String[] names = null;

names = new String[] {"감자칩","떡볶이","돈까스"};

이런 식으로 만들어줘야 한다

 

배열을 미리 생성한 후

값을 지정할 수는 있다

 

int[] arr1 = new int[3];

arr1[0] = 10;

arr2[1] = 20;

arr3[2] = 30;

 

이런 식으로는 가능하다

 

변수의 배열은

배열변수.length; 를 읽으면 된다

위의 배열변수를 읽을 땐

arr1.length

라고 읽으면 된다

 

 

타입[][] 변수 = {

{},

{}

};

 

이런 식으로 하면 다차원 배열도 생성 가능하다

 

 

변수와 for문으로 만든

평균내기 예시

 

package step2;

import java.util.Arrays;
import java.util.Scanner;

public class GO2 {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		String name;
		String num;
		int[] score = new int[3];
		int total = 0;
		double ave = 0.0;
		
			System.out.println("이름입력하세요");
			name = sc.next();
			System.out.println("번호 입력하세요");
			num = sc.next();
			System.out.println("국어");
			score[0] = sc.nextInt();
			System.out.println("수학");
			score[1] = sc.nextInt();
			System.out.println("영어");
			score[2] = sc.nextInt();
			
			for(int i=0;i<score.length;i++) {
				total += score[i];
				ave = (double)total/i;

				System.out.println("이름:"+name);
				System.out.println("번호"+num);
				System.out.println("국어"+score[0]);
				System.out.println("수학"+score[1]);
				System.out.println("영어"+score[2]);
				System.out.println("총점"+total);
				System.out.println("평균"+ave);
				
			
			}
	}

}

 

 

for문과 while문은 같은 반복문이기에

약간 다른 내용으로 같은 값을 출력할 수 있다

 

		int i = 1, sum=0;
		while(i<=10) {
			System.out.println((i++)+" \t");
		}
		//== 둘 다 같은 식
		for(int j=1;j<=10;j++) {
			System.out.println(j);
		}

 

for을 while로, while을 for로 바꿔보는 것도 도움이 될 거 같다

 

 

배열[5] 를 선언하고

배열에 해당하는 값을 넣지 않으면

그 자리는 비워둔다

 

 

for문으로 array의 list를 뽑아올 수 있고

배열의 빈자리를 볼 수 있는 예시

 

package step2;

public class ArrayStudy {

	public static void main(String[] args) {
		
		int[] arr = new int[5];
		arr[0] = 10;
		arr[1] = 20;
		arr[3] = 30;
		
		for(int i=0;i<arr.length;i++) {
			System.out.println(arr[i]);
		}

	}

}

 

 

결과값은

10
20
0
30
0

 

String 이라면?

 

package step2;

public class ArrayStudy {

	public static void main(String[] args) {
		
		String[] arr = new String[5];
		arr[0] = "가";
		arr[1] = "나";
		arr[3] = "다";
		
		for(int i=0;i<arr.length;i++) {
			System.out.println(arr[i]);
		}

	}

}

 

 

결과는

 



null

null

 

이 뜬다

 

 

배열은 한번 생성하면 길이를 변경할 수 없어서

더 많은 저장 공간이 필요하다면

더 큰 길이 배열에 이전 배열의 항목들을 복사해야 한다

 

3개                  5개

123     ->     12300(0은 비어있는거)

 

이런 식으로

 

 

유용한 for 문으로

배열 복사가 가능하다

		int[] oldInt = {1,2,3};
		int[] newInt = new int[5];
		
		for(int i=0;i<oldInt.length;i++) {
			newInt[i] = oldInt[i];
		} //복사for문
		for(int i=0;i<newInt.length;i++) {
			System.out.println(newInt[i]);
		} //배열 출력 for문

 

결과는?

1

2

3

0

0

 

이 나온다

 

 

 

728x90