Contents
접기
Do While
조건에 대한 판단을 문장의 마지막에 실시하므로 최소 1회에 실행
초기식;
do{
반복할 문장;
증감식;
} while ( 조건식) ;
For
- 초기값, 조건식, 증감식이 한줄에 파악되므로 가독성이 좋은 문장
- 조건식이 참일 경우 { } 내의 문장을 실행
- 조건식이 처음부터 거짓일 경우 문장을 한 번도 실행하지 못 할 수 있다.
for (초기식 ; 조건식 ; 증감식) {
반복할 문장;
}
[Q] 구구단
import java.util.Scanner;
public class ForGugudan {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int dan;
int i = 0;
System.out.print("출력할 단:");
dan = scanner.nextInt();
for(i =1 ; i < 10 ; i++) {
System.out.println(dan + "*" + i + "=" + (dan * i));
}
scanner.close();
}
}
[Q] 10 아래의 짝수만 * 출력
public class ForTest01 {
public static void main(String[] args) {
for (int i = 2; i < 10; i += 2) {
// for문 바깥에서는 i를 쓸 수 없다.
// 만약 바깥에서 사용하고 싶다면 선언을 for 문에서가 아닌 바깥에서
System.out.println(i + ": *");
}
}
}
2: *
4: *
6: *
8: *
[Q] a 부터 z 까지 일자로 출력하기
public class ForTest02 {
public static void main(String[] args) {
for(char ch = 'a' ; ch <= 'z' ; ++ch ) // ch++ 도 상관 없다.
// char : ' ', String : " "
System.out.print(ch);
System.out.println();
}
}
abcdefghijklmnopqrstuvwxyz
[Q] 이중 for문
public class ForTest02 {
public static void main(String[] args) {
for( int i = 0; i<10; ++i) {
for(char ch = 'a' ; ch <= 'z' ; ++ch ) // ch++ 도 상관 없다.
// char : ' ', String : " "
System.out.print(ch);
System.out.println();
}
}
}
문제
[Q] 1 부터 100까지의 자연수 중에서 3 과 5의 배수만 출력. 반드시 continue 사용
public class ForTest03 {
public static void main(String[] args) {
for (int i = 1; i <= 100; ++i) {
if (!(i%3 == 0 && i% 5 ==0)) continue;
// 비트연산, 논리 연산 같이 쓰임. short circuit 을 하지 않는 &
System.out.print(i + " ");
}
}
}
15 30 45 60 75 90
continue 무조건 쓰는 건 헷갈렸다..
[Q] for 문을 이용해서 0 부터 127까지 해당하는 문자를 출력하시오.
실행예시
0 : __ 1 : __ 2 : __ 3 : __ 4 : __
5 : __ ...
public class ForTest04 {
public static void main(String[] args) {
int cnt = 0;
for ( char ch = 0 ; ch <128 ; ch++) {
System.out.printf("%d : %c " , cnt, ch);
cnt ++;
if (cnt % 5 == 0)
System.out.println();
}
/*
for (int i = 0; i<128; ++i) {
System.out.print(i + ":" + (char) i + " " );
if((i+1)%5 == 0) System.out.println();
}
*/
}
}
Escape Sequence (문자) |
\n : new line (ASCII :10) ==> java : enter = \r + \n 이다. |
\t : tab (ASCII : 13) |
\r : carriage return (현재있는 곳에서 맨 앞으로 가라) |
\a : , \f : |
A <-> a
'A' + ' ' ===> 'a' (* ' ' : ASCII : 32 = space) | a = ASCII : 97 |
'a' - ' ' ===> 'A' | A = ASCII : 65 |
[Q] 세 명의 학생의 이름, 2과 목의 점수를 입력받아 평균을 구하여 출력하는 코드를 작성하시오.
<실행예시>
이름: 홍길동
국어: 90
영어: 90
홍길동 : 90 90 90.0
이름: 손오공
국어: 85
영어: 85
손오공 : 85 85 85.00
import java.util.Scanner;
public class Exam18 {
public static void main(String[] args) {
String name; // 단어가 아닌 문자를 담는 건 ,,,?
int kor, eng;
double result;
for(int i = 0; i < 2; i++) {
Scanner scanner = new Scanner(System.in);
System.out.print("이름: ");
name = scanner.next();
System.out.print("국어: ");
kor = scanner.nextInt();
System.out.print("영어: ");
eng = scanner.nextInt();
result = (kor + eng) / 2.0;
System.out.printf("> %s : %d % d %.2f \n" ,name,kor,eng,result);
// 앞에 하는 거 하려면 배열이 필요한데 없이 하는 방법은 없는듯?
scanner.close();
}
}
}
[Q] 반쪽 트리 그리기
public class ForTest04 {
public static void main(String[] args) {
for(int i =0; i<5; ++i) {
for(int j = 0; j <(i+1) ; ++j) // i = 0, j = 0
// 안 쪽에 for문은 바깥쪽의 변수를 받아서 할 수 있다.
System.out.print("*"); // 반복문을 25번 돈다.
System.out.println();
}
}
}
*
**
***
****
*****
이중 반복문 로직이 갑자기 이해가 안됐었다.. 나중에 까먹지 않게 적는 칸 |
이중 반복문에서 바깥(위의 코드에서 변수 i)은 몇 줄을 출력할지 정해준다. 이중 반복문에서 안(위의 코드에서 변수 j)은 몇 개의 별을 출력할지 정해준다. |
[Q] 알파벳으로 삼각형 그리기
A
AB
..
ABCDE.... XYZ
public class Exam20 {
public static void main(String[] args) {
for(int i = 0; i < 26; i++) {
for(int j = 0 ; j <= i; j++) {
System.out.print((char)('a' + j));
}
System.out.println();
}
/* 교수님 코드
for(char ch = 'A'; ch <= 'Z'; ++ch){
for(char c = 'A'; c<= ch; ++c){
System.out.print(c);
System.out.println();
*/
}
}
[Q] 알파벳 삼각형 오른쪽으로 출력
public class Exam21 {
public static void main(String[] args) {
for(char ch = 'A'; ch <= 'Z'; ++ch){
for(char c = 'Z'; c > ch; --c) // = 을 지우면 마지막 줄 공백 지울 수 있음
System.out.print(' ');
for(char c = 'A'; c <= ch; ++c)
System.out.print(c);
System.out.println();
}
}
}
[Q] 이중 for문 - 기본 구구단
public class ForTest05 {
public static void main(String[] args) {
for(int dan = 2; dan <=9; ++dan) {
for(int i =1; i<=9; ++i)
System.out.printf("%d * %d = %2d\n",dan, i, dan*i);
System.out.println();
}
}
}
[Q] 삼중 for문 - 구구단 세로
실행 예시
2 * 1 = 2 3 * 1 = 3 4 * 1 = 4 5 * 1 = 5
2 * 2 = 4 3 * 2 = 6 ...
public class Exam22 {
public static void main(String[] args) {
for(int j =2; j<=9; j+=4){
for(int i = 1; i<=9; i++) {
for(int dan = j; dan< j+4; dan++)
System.out.printf("%d * %d = %2d\t",dan, i, dan*i);
System.out.println();
}
System.out.println();
}
}
}
코드 | 역할 |
for(int j =2; j<=9; j+=4) | 4단을 첫 줄에 적을 것이라고 정해준다. |
for(int i = 1; i<=9; i++) | n * i 에서 i 부분 = 1 ~ 9 까지 곱하는 숫자를 정해준다. |
for(int dan = j; dan< j+4; dan++) | j에 해당하는 단부터 + 4 단까지 정해준다. |
[Q] 두 개의 for문으로 - 이중 아님
구구단
2 * 1 = 2 3 * 1 = 3 4 * 1 = 4 5 * 1 = 5
2 * 2 = 4 3 * 2 = 6 ...
for(int i = 1; i<=9; i++) {
for(int dan = 2; dan<=5; dan++)
System.out.printf("%d * %d = %2d\t",dan, i, dan*i);
System.out.println();
}
System.out.println();
for(int i = 1; i<=9; i++) {
for(int dan = 6; dan<=9; dan++)
System.out.printf("%d * %d = %2d\t",dan, i, dan*i);
System.out.println();
[Q] 정수를 입력받아 그 정수가 소수인지 판단하여 아래와 같이 출력하시오.
소수: 1과 자기 자신으로만 나누어떨어지는 수
System.exit(0) 사용 불가
입력: 3
3은 소수 입니다.
입력: 6
6은 소수가 아닙니다.
import java.util.Scanner;
public class Exam23 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n;
boolean isPrimeNumber = true; // for문을 다 돌았는지 아닌지
System.out.print("정수 입력:");
n =scanner.nextInt();
for(int i = 2; i<n/2; i++) {
if(n%i == 0) {
isPrimeNumber = false;
break;
}
}
// value의 절반만 나눠서 그 안에서 나누어 떨어질때 소수가 아닌 것.
if(isPrimeNumber) System.out.println(n + "은 소수입니다.");
else System.out.println(n + "은 소수가 아닙니다.");
scanner.close();
}
}
코드 | 역할 |
boolean isPrimeNumber = true; for(int i = 2; i<n/2; i++) { if(n%i == 0) { isPrimeNumber = false; break; } } |
소수는 1과 자기 자신만 가진 숫자이기 때문에 하나라도 나뉘어지면 소수가 아니게 된다. => 때문에 2로 나눠지면 소수가 아닌것이다. boolean isPrimeNumber : for 문을 돌 때 소수여서 for문을 나왔는지 , 소수가 아니어서 break에 걸려 for 문을 나왔는지 알기위한 플래그 역할이다. |
[Q] 정수를 입력받아 그 정수까지 존재하는 모든 소수를 출력하고 소수가 몇 개 인지 출력하시오. (개수까지 출력)
입력: 10
2, 3, 5, 7 소수는 4개 입니다.
import java.util.Scanner;
public class Exam24 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n;
int cnt = 0; // 소수의 개수를 세는 변수
boolean isPrimeNumber = true;
System.out.print("정수 입력:");
n =scanner.nextInt();
for(int i = 2; i<=n; i++) {
for(int j = 2; j<i ;j++) {
// j <= (i/2)
if(i % j == 0 ) {
isPrimeNumber = false;
break;
}
}
if(isPrimeNumber) {
++ cnt;
System.out.print(i + " ");
}
isPrimeNumber = true;
// 정수 입력: 100
// 2 3
// 2 ~ 100까지의 소수 개수는 2개 이다.
// __ isPrimeNumber 가 변경되어있지 않았기 때문
}
System.out.printf("\n2 ~ %d까지의 소수 개수는 %d개 이다.", n, cnt);
scanner.close();
}
}
코드 | 역할 |
for(int i = 2; i<=n; i++) { for(int j = 2; j<i ;j++) { // j <= (i/2) if(i % j == 0 ) { isPrimeNumber = false; break; } } isPrimeNumber = true; |
위의 코드와 다르게 isPrimeNumber 를 한 번 더 선언한 이유 정수 입력: 100 2 3 2 ~ 100까지의 소수 개수는 2개 이다. isPrimeNumber = false 가 유지 되어 더이상 돌아가지 않는다. |
'국비 교육 > 백엔드(Java, Spring)' 카테고리의 다른 글
[자바] 클래스 Class (0) | 2024.01.22 |
---|---|
[자바] 배열 Array (0) | 2024.01.22 |
[자바] 입력 버퍼 (Buffer) (0) | 2024.01.18 |
[자바] 반복문 -1 (While) (0) | 2024.01.17 |