✍🏻~ 11.10

[0613] 조건문과 반복문(if, while, for) + 예제

Nsso 2023. 6. 15. 00:02

🧀 if문 (조건문)


구조  =>  if ( 조건식 ) { 수행문 } ;

  • 조건식의 결과는 반드시 true, false여야 함
  • if문을 사용하면 중첩 블록을 유지하지 않아도 되기 때문에 코드를 깔끔하게 짤 수 있음
  • 주어진 조건에 따라 각각 다른 실행이 이루어지도록 구현이 가능함

 

+  if - else문 

구조 => if ( 조건식 ) { 수행문 1 }  else { 수행문 2 } ; 

 

 

🧀 while문과 for문 (반복문)


  1. while문
    • 구조 => while ( 조건식 ) { 조건식의 연산결과가 true일 동안, 반복될 문장들 작성 } ;
    • 주어진 조건이 true일 동안 반복 수행
    • 조건식 생략이 불가능함
    • 조건식의 결과나 변수가 true, false 값인 경우 주로 사용
  2. for문
    • 구조 => for ( 초기화; 조건식; 증감식 ) { 조건식이 true인 동안 수행될 문장들 작성 } ;
    • 특정 수와 범위, 횟수와 관련하여 반복되는 경우 주로 사용

 

🧀 예제


  1. Scanner를 이용해 사용자에게 입력 받은 값이 5보다 크고 10보다 작을 때 출력하는 코드 작성
import java.util.Scanner;

public class Loop {
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();

		if (5 < num && num < 10) {
			System.out.println(num);
		}
		sc.close();
	}
}

 

2. 사용자에게 입력 받은 값이 2 또는 3의 배수인 수 일 때 출력하는 코드 작성

import java.util.Scanner;

public class Loop {
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int num2 = sc.nextInt();
		if (num2 % 2 == 0 || num2 % 3 == 0) {
			System.out.println(num2);
		}
	}
}

 

3. 삼항 연산자를 이용하여 x+y가 홀수라면 변수 isOdd에 true를 할당하는 코드 작성

import java.util.Scanner;

public class Loop {
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		int x = sc.nextInt();
		int y = sc.nextInt();
		
		boolean isOdd = ((x+y) %2 == 1) ? true : false ;
		System.out.println(isOdd);
		
		sc.close();
	}
}

 

4. for문을 이용하여 정수 1부터 10 이하의 정수 합 출력

public class Loop {
	public static void main(String[] args) {

		int sum=0;
		for(int i=0; i<=10; i++) {
		sum+= i;	}
		System.out.println(sum);
		
		sc.close();
	}
}

 

5.  for문을 이용하여 정수 1부터 10이하의 정수 중 짝수만 작은 수부터 출력

import java.util.Scanner;

public class Loop {
	public static void main(String[] args) {
    
		for(int i=1; i<= 10; i++) {
			if(i%2==0) {
				System.out.println(i);
			}
		}
	}
}

 

6.  for문을 이용하여 정수 1부터 10이하의 정수 중 홀수만 큰 수부터 작은 순으로 출력

public class Loop {
	public static void main(String[] args) {

		for (int i = 10; i >= 1; i--) {
			if (i % 2 == 1) {
				System.out.printf("%d ", i);
			}
		}
	}
}

 

7.  while문을 이용하여 정수 1부터 10이하의 정수를 출력

public class Loop {
	public static void main(String[] args) {

		int i = 0;
		
		while (i < 10) {
			i++;
			System.out.printf("%d ", i);
		}
	}
}

 

8.  while문을 이용하여 정수 1부터 100 이하의 정수 중 3의 배수만 출력

public class Loop {
	public static void main(String[] args) {
    
		int i = 0;
        
		while (i < 100) {
			i++;
			if (i % 3 == 0) {
				System.out.println(i);
			}
		}
	}
}