Lecture/컴퓨터프로그래밍및실습/조교/Ch4

Retired DISLab
< Lecture | 컴퓨터프로그래밍및실습 | 조교
Swpark (토론 | 기여) 사용자의 2014년 1월 26일 (일) 09:52 버전
(비교) ← 이전 판 | 현재 판 (비교) | 다음 판 → (비교)
이동: 둘러보기, 찾기

목차

홀수 더하기

문제 3

정수 하나를 입력받아 그 개수 만큼의 홀수를 더한 값을 출력한다.

예를 들어 4를 입력하면 4개의 홀수를 더해야 하므로 1 + 3 + 5 + 7 이므로 16을 출력한다.

숫자 뒤집기

Figure 4-6

/*
 * File: DigitSum.java
 * -------------------
 * This program sums the digits in a positive integer.
 * The program depends on the fact that the last digit of
 * a integer n is given by n % 10 and the number consisting
 * of all but the last digit is given by the expression n / 10.
 */
 
import acm.program.*;
 
public class DigitSum extends ConsoleProgram {
    public void run() {
        println("This program sums the digits in an integer.");
        int n = readInt("Enter a positive integer: ");
 
        int dsum = 0;
        while (n > 0) {
            dsum += n % 10;
            n /= 10;
        }
 
        println("The sum of the digits is " + dsum);
    }
}

문제 7

숫자를 입력받고 그 숫자를 뒤집어 출력한다. 예를 들어 1729를 입력하면 화면에 9271을 출력한다.


반복문 연습

Figure 4-8

/*
 * File: Countdown.java
 * --------------------
 * This program counts backwards from the value START
 * to zero, as in the countdown preceding a rocket
 * launch.
 */
 
import acm.program.*;
 
public class Countdown extends ConsoleProgram {
    /* Specifies the value from which to start counting down */
    private static final int START = 10;
 
    /* Runs the program */
    public void run() {
        for (int t = START; t >= 0; t--) {
            println(t);
        }
        println("Liftoff!");
    }
}

문제 8

Figure 4-8과 동일한 결과를 출력하는 것을 for가 아닌 while 문으로 작성하시오.

개인 도구
이름공간
변수
행위
둘러보기
구성원
연구
연구실
기타
도구모음
인쇄/내보내기