본문 바로가기
스마트인재개발원/자바

[자바]반복문 / for문 / 예제-구구단 만들기

by 죠졍니 2022. 9. 14.
728x90
반응형
SMALL

반복문

FOR

: 주로 반복횟수가 정해진 경우

 

 

 

 

 


 

구조

 

FOR(초기화구문; 검사조건; 반복후작업){

검사조건이 TRUE일 동안 실행될 로직;

}

 

 

 

 

 


문제1. 21부터 57까지 출력

문제2. 96부터 53까지 출력

문제3. 21부터 57까지 출력

 

 

 

 

public class Ex03_for문1 {

	public static void main(String[] args) {

		//for문 사용
		
		//1. 21~57까지 출력
		for(int i=21;i<=57;i++) {
			System.out.print(i+" ");
		}
		
		System.out.println();
		
		//2. 96~53까지 출력
		for(int j=96;j>=53;j--) {
			System.out.print(j+" ");
		}
		
		System.out.println();
		
		//3. 21~57까지 출력(단, 홀수만 출력)
		for(int k=21;k<=57;k+=2) {
			System.out.print(k+" ");
		}
	}

}

 

 

 

 

 

 

 

 


 

 

예제2.

100 이하의 두 개의 정수를 입력받아 작은수부터 큰수까지 차례대로 입력

첫 번째 정수 : 2

두 번째 정수 : 15

2 3 4 5 6 7 8 9 10 11 12 13 14 15

 

 

 

import java.util.Scanner;

public class Ex04_for문2 {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		
		//두 정수 입력받기
		System.out.print("첫 번째 정수 : ");
		int x = sc.nextInt();

		System.out.print("두 번째 정수 : ");
		int y = sc.nextInt();
		
		
		if(x<y) {
			for(int i=x;i<=y;i++) {
				System.out.print(i+" ");
			}
		}
		else {
				for(int j=y;j<=x;j++) {
					System.out.print(j+" ");
				}
			}
		
		
	}

}

 

 

 

 


예제3. 숫자 2개를 입력받아 두 수 사이의 총 합을 출력

첫 번째 정수 : 2

두 번째 정수 : 5

총 합 : 14

 

 

import java.util.Scanner;

public class Ex05_for문3 {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		
		System.out.print("첫 번째 정수 : ");
		int x = sc.nextInt();

		System.out.print("두 번째 정수 : ");
		int y = sc.nextInt();
		
		int sum=0;
		for(int i=x;i<=y;i++) {
			sum+=i;
		}
		System.out.println("총 합 : " + sum);
		
	}
}

 

 

 

 

 


예제4. 구구단 출력하기

for문 이용하여 구구단 2단출력

 

import java.util.Scanner;

public class Ex06_for문4 {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		
		for(int i=1;i<=9;i++) {
			System.out.println("2*" + i + "=" + 2*i);
		}
	}

}

 

 

 

 


예제5. 구구단 출력

for문 이용하여 원하는 단 입력해 구구단 출력

 

 

import java.util.Scanner;

public class Ex07_for문5 {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		
		System.out.print("단 입력 : ");
		int x = sc.nextInt();
		for(int i=1;i<=9;i++) {
			System.out.println(x +"*"+ i + "=" + x*i);
		}
		
	}

}

 

 

 


예제6. 구구단 출력

단과 곱해지는 수 입력받아서 출력

 

 

import java.util.Scanner;

public class Ex08_for문6 {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		System.out.print("단 입력 : ");
		int x = sc.nextInt();
		System.out.print("곱해지는 수 입력 : ");
		int y = sc.nextInt();
		
		for(int i=1;i<=y;i++) {
			System.out.println(x +"*"+ i + "=" + x*i);
		}
	}

}

 

 

 

 

 

728x90
반응형
LIST