while문은 조건식을 검사하여 참일 경우 블록 내부의 코드를 실행하며 실행이 끝날 때마다 반복적으로 조건식을 검사하여 false가 나올 때까지 반복한다.
while문도 if와 마찬가지로 논리값이 도출되는 조건식이나 함수를 사용한다.
while문은 반복 횟수를 제어하기 위한 증감식이나 탈출문이 필요하다.
public class WhileExample1 {
public static void main(String[] args) {
int n = 1;//제어변수: 반복문의 횟수를 제어할 변수. (begin)
while (n <= 10) {//논리형 조건식: 반복문의 끝을 지정. (end)
System.out.println("안녕하세요. 반갑습니다.");
n++;//증감식: 반복문의 종료를 위해 제어변수의 값을 조정. (step)
}
System.out.println("-------------------------------------");
//1 ~ 10의 누적합을 구하는 로직
int i = 1; //begin
int total = 0; //누적합을 기억해줄 변수
while (i <= 10) {
total += i;
i++;//step
}
System.out.println("1 ~ 10의 누적합: " + total);
}
}
while문의 진행 순서 1. 제어변수를 선언한다. (시작 값이 정해짐) 2. 조건식을 검사해서 true면 반복문이 진행한다. false가 되면 반복문 종료한다. 3. while문 블록 내부가 한 번 진행되면, 다시 조건식을 검사하여 true면 반복문이 계속 진행한다. false가 되면 반복문 종료. 4. 반복문 내에는 증감식을 배치해서 제어 변수의 값을 조정한다.
public class WhileExample2 {
public static void main(String[] args) {
//48 ~ 150사이의 정수 중 8의 배수만 가로로 출력하라.
//48부터 숫자를 하나씩 올려가면서 8의 배수를 판복 반복
int n = 48;
while (n <= 150) {
if(n % 8 == 0) {
System.out.print(n + " ");
}
//System.out.print(n % 8 == 0 ? n + " ": "");
n++;
}
System.out.println(); //단순 줄 개행
//1 ~ 100까지의 정수 중 4의 배수이면서
//8의 배수는 아닌 수를 가로로 출력
int i = 1;
while (i <= 100) {
if (i % 4 == 0 && i % 8 != 0) {
System.out.print(i + " ");
}
// if (i % 4 == 0) {
// if (i % 8 != 0) {
// System.out.print(i + " ");
// }
// }
i++;
}
System.out.println();
//1~30000까지의 정수 중 258의 배수의 개수를 출력.
int j = 1;
int count = 0; //배수의 개수를 기억해 줄 변수.
while (j <= 30000) {
if (j % 258 == 0) {
count++;
}
j++;
}
System.out.println("1~30000중의 258의 배수의 개수: " + count + "개");
//1000의 약수의 개수를 구하라.
//1부터 1000까지 하나씩 올려가면서 1000이랑 나누고
//나누어 떨어진 값이 약수이다.
int k = 1;
int cnt = 0;
while (k <= 1000) {
if (1000 % k == 0) {
cnt++;
}
k++;
}
System.out.println("1000의 약수의 개수: " + cnt + "개");
}
}
While Quiz01
문제) 사용자에게 구구단 단수를 입력 받아서 해당 단수의 구구단을 출력한다.
예시) 구구단을 입력하세요 : 4
*** 구구단 4 단 *** 4 x 1 = 4 4 x 2 = 8 4 x 3 = 12 4 x 4 = 16 ... 4 x 9 = 36
import java.util.Scanner;
public class WhileQuiz01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("구구단을 입력하세요 : ");
int dan = sc.nextInt();
System.out.println("*** 구구단 " + dan + "단 ***");
int hang = 1;
while(hang <= 9) {
// System.out.printf("%d x %d = %d\n", dan, hang, dan * hang);
System.out.println(dan + " x " + hang + " = " + dan * hang);
hang++;
}
sc.close();
}
}
While Quiz02
문제) 입력 받은 수의 약수의 총합을 구한다.
예시) 입력 받은 값: 12 -> 1 2 3 4 5 6 12 -> 28
import java.util.Scanner;
public class WhileQuiz02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("정수를 입력하세요: ");
int num = sc.nextInt();
int i = 1;// beginint total = 0;//누적합을 담을 변수
while (i <= num) {
if (num % i == 0) {
total += i;
}
i++;
}
System.out.println("입력받은 값: " + num + " -> " + total);
sc.close();
}
}
import java.util.Scanner;
public class WhileExample3 {
public static void main(String[] args) {
/*
- 정수 1개를 입력 받아 해당 정수가 소수(prime number)인지 판별
*/
Scanner sc = new Scanner(System.in);
System.out.print("정수를 입력하세요: ");
int num = sc.nextInt();
int i = 1; //소수의 판별을 위해 입력받은 정수 num을 지속적으로 나눌 변수
int count = 0; //나누어 떨어진 횟수를 기억할 변수
while (i <= num) {
if (num % i == 0) {
count++;
}
i++;
}
if (count == 2) {
System.out.println(num + " 은(는) 소수입니다.");
} else {
System.out.println(num + " 은(는) 소수가 아닙니다.");
}
System.out.println("------------------------");
int j = 2;//1은 모든 수의 약수이기 때문에 배제
while (num % j != 0) {
j++;
}
System.out.println(num == j ? "소수입니다." : "소수가 아닙니다.");
sc.close();
}
}
While Quiz03
문제) 1. 정수를 두개 입력받는다. (x, y) 2. x부터 y까지의 누적합계를 while을 사용하여 구하는 코드 작성
예시) ex) 입력 3, 7 -> "3부터 7까지의 누적합계: 25"
Hint) 처음에는 x에 무조건 작은 값을 들어올 것이라고 예상하고 작성한다. 완료 후 x에 큰 값이 들어왔을 경우 어떻게 대처할지 생각하라. (x에 큰 값이 들어와도 정삭적으로 출력이 되어야 한다. 입력: 7, 3 -> "3부터 7까지의 누적합계: 25") ※ while문을 if else 로 나눠서 두 번 쓰는 것을 지양
import java.util.Scanner;
public class WhileQuiz03 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("첫 번째 정수를 입력하세요: ");
int num1 = sc.nextInt();
System.out.print("두 번째 정수를 입력하세요: ");
int num2 = sc.nextInt();
if (num1 > num2) {
int temp = num2;
num2 = num1;
num1 = temp;
}
int total = 0;
int start = num1;
while (start <= num2) {
total += start;
start++;
}
System.out.println(num1 + "부터 " + num2 + "까지의 누적합계: " + total);
sc.close();
}
}
반복문 for
for문은 반복제어조건을 한꺼번에 지정한다는 점이 다른 반복문과 다르다.
정확한 반복 횟수를 알고 있을 경우 for문이 while문보다 효율적이다.
import java.util.Scanner;
public class ForExample {
public static void main(String[] args) {
/*
int i = 1;
int total = 0;
while(i <= 10) {
total += i;
i++;
}
System.out.println(total);
*/
int total = 0;
for (int i = 1; i <= 10; i++) {
total += i;
}
//1~200까지의 정수 중 6의 배수이면서 12의 배수는 아닌 수를 가로로 출력 (for)
for (int i = 1; i <= 200; i++) {
if(i % 6 == 0 && i % 12 != 0) {
System.out.print(i + " ");
}
}
System.out.println();
//1~60000까지의 정수 중 177의 배수의 개수를 출력 (for)int count = 0;
for (int i = 1; i <= 60000; i++) {
if(i % 177 == 0) {
count++;
}
}
System.out.print("1~60000 중 177의 배수의 개수: " + count + "개");
System.out.println();
//입력 받은 정수까지의 팩토리얼 값을 구하라.//팩토리얼) 5! -> 5 x 4 x 3 x 2 x 1
Scanner sc = new Scanner(System.in);
System.out.print("정수 입력: ");
int num = sc.nextInt();
int fac = 1;//팩토리얼 최종 결과를 담을 변수
for (int i = 1; i <= num; i++) {
fac = fac * i;
}
// for (int i = num; i >= 1; i--) {// fac *= i;// }
System.out.println(num + "! -> " + fac);
sc.close();
}
}
for Quiz01
문제) 2~19까지의 난수를 생성하여 구구단을 출력 (for) 19행까지 출력
public class ForQuiz01 {
public static void main(String[] args) {
int dan = (int) ((Math.random() * 18) + 2);
for(int hang = 1; hang <= 19; hang++) {
System.out.println(dan + " x " + hang + " = " + dan * hang);
}
}
}
댓글