728x90
반응형
사전 판단 반복과 사후 판단 반복의 차이점
- 사전 판단 반복문인 while문 for문은 처음에 제어식을 평가한 결과가 0이면 루프 본문은 한번도 실행되지 않는다.
- 사후 판단 반복문인 do문은 루프 본문이 반드시 한번은 실행된다.
*Q10 두 변수 a, b에 정수를 입력하고 b-a를 출력하는 프로그램을 작성하세요
- 단, 변수 b에 입력한 값이 a 이하면 변수 b의 값을 다시 입력하세요.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
package algorithm;
import java.util.Scanner;
public class Training1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// int n;
//
// System.out.println("1부터 n까지의 합을 구합니다.");
//
// //사전판단반복 : while, for
//
// //사후판단반복 : do~while
// do{
// System.out.println("n의 값 : ");
// n = sc.nextInt();
// }while(n <= 0);
//
// int sum = 0;
//
// for(int i = 1; i <=n; i++)sum +=i;
//
// System.out.println("1부터 " + n + "까지의 합은 " + sum + "입니다.");
System.out.print("a의 값 : ");
int a = sc.nextInt();
System.out.print("b의 값 : ");
int b = sc.nextInt();
while(a > b) {
System.out.println("a보다 큰 값을 입력하세요");
System.out.print("b의 값 : ");
b = sc.nextInt();
}
System.out.println("b-a는 " + (b-a) + "입니다.");
}
}
|
cs |
* 결과
*Q11 양의 정수를 입력하고 자릿수를 출력하는 프로그램을 작성하세요. 예를 들어 135를 입력하면
'그 수는 3자리입니다.' 라고 출력하고, 1314를 입력하면 '그 수는 4자리입니다.'라고 출력하면 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package algorithm;
import java.util.Scanner;
public class Training2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("양의 정수 입력 : ");
int a = sc.nextInt();
while(a <= 0) {
System.out.print("양의 정수 입력 : ");
a = sc.nextInt();
}
String [] strArr = String.valueOf(a).split("");
System.out.println("그 수는 " + strArr.length + "자리입니다.");
}
}
|
cs |
* 결과
728x90
반응형
'알고리즘' 카테고리의 다른 글
Do it! 자료구조와 함께 배우는 알고리즘 입문 : 소수의 나열 (0) | 2021.09.13 |
---|---|
Do it! 자료구조와 함께 배우는 알고리즘 입문 (자바편) - 배열, 난수 (Q1) (0) | 2021.09.05 |
Do it! 자료구조와 함께 배우는 알고리즘 입문 (자바편) - 직각 이등변 삼각형 출력(Q15~17) (0) | 2021.09.04 |
Do it! 자료구조와 함께 배우는 알고리즘 입문 (자바편) - 다중 루프 (Q12~14) (0) | 2021.09.04 |
Do it! 자료구조와 함께 배우는 알고리즘 입문 (자바편) - 반복 (Q7~9) (0) | 2021.09.02 |