프로그래밍 기초

36
강강강강강 강강강강강 강강 강 5 강 2014 강 1 강강 강강강강강 강강강강강 강강강강 : 강강강 강강강강강 강강 1/36

description

프로그래밍 기초. 제 5 주 2014 년 1 학기 강원대학교 컴퓨터학부 담당교수 : 정충교. 5 장 반복. 반복. while 문 do-while 문 for 문. while 문. int sum = 0; int count = 0; while(count < 50) { sum = sum + input.nextInt(); count++; } System.out.print(“Sum is ” + sum);. 예제. 몇 개의 수를 더하겠습니까 ? 3 - PowerPoint PPT Presentation

Transcript of 프로그래밍 기초

Page 1: 프로그래밍 기초

강원대학교

프로그래밍 기초

제 5 주

2014 년 1 학기강원대학교 컴퓨터학부

담당교수 : 정충교

프로그래밍 기초 1/36

Page 2: 프로그래밍 기초

강원대학교

5 장 반복

프로그래밍 기초 2/36

Page 3: 프로그래밍 기초

반복

while 문

do-while 문

for 문

 

프로그래밍 기초 강원대학교 3/36

Page 4: 프로그래밍 기초

while 문

int sum = 0;int count = 0;while(count < 50) { sum = sum + input.nextInt(); count++;}System.out.print(“Sum is ” + sum);

프로그래밍 기초 강원대학교 4/36

Page 5: 프로그래밍 기초

예제

몇 개의 수를 더하겠습니까 ? 3 3 개의 수를 입력하세요 : 5 7 9 Sum: 21

프로그래밍 기초 강원대학교 5/36

Page 6: 프로그래밍 기초

import java.util.*;public class AddUp {public static void main (String[] args) { Scanner input =new Scanner(System.in);

int sum = 0; // 정수들의 합 int count = 0; // 차례로 세기 위한 변수 int size ; // 정수 개수

// 프롬프트 출력 size = input.nextInt(); // 프롬프트 출력

while (count < size) { sum = sum + input.nextInt(); count++; } System.out.println("Sum: "+ sum); } }

프로그래밍 기초 강원대학교 6/36

Page 7: 프로그래밍 기초

플래그 (flag)

루프를 종료하기 위해 사용하는 다른 방법으로 플래그(flag) 나 감시 문자 (sentinel) 가 있다 .  플래그 또는 감시 문자는 데이터의 끝을 알려주기 위하여 데이터 끝에 추가된 값이다 .  

프로그래밍 기초 강원대학교 7/36

Page 8: 프로그래밍 기초

예제

사용자가 제공하는 정수들의 합을 계산하는 프로그램

데이터의 끝을 나타내기 위해 -999 를 입력한다 .

이 값은 단지 플래그로만 사용되고 합에는 포함시키지 않는다 .

데이터에는 -999 가 나타나지 않는다고 가정한다 . 

프로그래밍 기초 강원대학교 8/36

Page 9: 프로그래밍 기초

실행 예

Enter the numbers. End with -9995 6 7 -999Sum: 18

Enter the numbers. End with -999-999Sum: 0

프로그래밍 기초 강원대학교 9/36

Page 10: 프로그래밍 기초

 import java.util.*;public class AddEmUpAgain { public static void main (String[] args) { Scanner input =new Scanner(System.in);

final int FLAG = -999; // 데이터의 끝 신호 int sum = 0; // 정수들의 합 int number; // 더해질 다음 정수 값 저장

System.out.println("Enter the numbers. End with "+FLAG);

number = input.nextInt();

while (number != FLAG) { // FLAG 는 데이터의 끝을 나타냄 sum += number; // 현재 정수 값을 sum 에 더함 number = input.nextInt(); // 다음 정수를 읽기 }

System.out.println("Sum: "+ sum); }}

프로그래밍 기초 강원대학교 10/36

Page 11: 프로그래밍 기초

반복문 : 힘의 원천이자 버그의 원천

두 가지 일반적인 버그 :

무한 루프 (infinite loop)

“ 하나 차이 " 로 인한 오류 (“off by one” error)

프로그래밍 기초 강원대학교 11/36

Page 12: 프로그래밍 기초

무한 루프 (Infinite Loop)

무한 루프는 영원히 계속 실행되는 루프이다 . 루프의 종료 조건이 거짓이 되지 않으면 무한 while 루프가 됨

while (count < size) { sum = sum + input.nextInt();

count++; }

문장 count++ 가 실수로 생략되면 ? 

프로그래밍 기초 강원대학교 12/36

Page 13: 프로그래밍 기초

루프가 아예 실행되지 않는 오류

루프가 절대 실행되지 않는 경우 :

  count = 0;

while (count > size) {

number = input.nextInt(); sum += number; count++;

}

 사용자가 size 를 양수로 설정면 ?

프로그래밍 기초 강원대학교 13/36

Page 14: 프로그래밍 기초

“ 하나 차이 (Off by One)" 로 인한 오류

올바른 경우에 비해 루프가 한 번 더 , 또는 한 번 덜 실행되어 생기는 오류

프로그래밍 기초 강원대학교 14/36

Page 15: 프로그래밍 기초

(1+2+3+ ... +n) 을 계산

n 값은 사용자가 입력import java.util.*;public class AddUpToN { // 오류 발생 !public static void main (String[] args) { Scanner input =new Scanner(System.in);

int sum = 0; // 누적 합 int number; // 1+2+3+ ... +number 의 값 int count = 1; // 1 부터 number 까지의 수 세기

System.out.print("Enter a positive integer: "); number = input.nextInt(); // 정수형 값 읽기

while (count < number) { // 여기가 버그 sum += count; count++; } System.out.println("The sum of the first "+number+ " positive integers is "+ sum); }}

 

프로그래밍 기초 강원대학교 15/36

Page 16: 프로그래밍 기초

입력된 수들의 평균 계산감시문자 -999

public class Average { // 잘못된 프로그램 ! public static void main (String[] args) { Scanner input =new Scanner(System.in);

final int FLAG = -999; double sum = 0; // 합 double number; // 더해질 다음 정수 int count = 0; // 데이터의 수 세기 double average; // 평균

System.out.println("Enter the numbers end with "+FLAG); number = input.nextDouble(); // 값 읽기 while (number != FLAG) { count++; number = input.nextDouble(); // 다음 수 읽기 sum += number; // sum 에 현재 정수 더하기 } average = sum/count; System.out.println("Average: "+ average); }}

프로그래밍 기초 강원대학교 16/36

Page 17: 프로그래밍 기초

( 오류 ) 출력

Enter the numbers end with -999123-999Average: -331.3333333333333

프로그래밍 기초 강원대학교 17/36

Page 18: 프로그래밍 기초

do-while 문

do-while 루프는 루프의 끝부분에서 조건을 확인한다 .

int x;do{ System.out.println("Enter a number > 0"); x = input.nextInt();} while (x <= 0); // 만약 음수이면 반복 .

프로그래밍 기초 강원대학교 18/36

Page 19: 프로그래밍 기초

예제

몇 개의 정수를 더하시겠습니까 ? 0몇 개의 정수를 더하시겠습니까 ? -3몇 개의 정수를 더하시겠습니까 ? 33 개의 정수를 입력하세요 .579Sum: 21

프로그래밍 기초 강원대학교 19/36

Page 20: 프로그래밍 기초

import java.util.Scanner;public class DoWhileAdd {

public static void main (String[] args) {Scanner input =new Scanner(System.in);

int size; // 덧셈할 정수들의 개수 do { // size 가 양수일 때까지 반복

System.out.print(" 몇 개의 정수를 더하시겠습니까 ? ");size = input.nextInt();

} while (size <= 0);

System.out.println(size+" 개의 정수를 입력하세요 . ");int sum = 0; int count = 0;while (count <size) {

sum = sum + input.nextInt(); // 다음 정수를 읽어 sum 에 더함

count++; // 카운터 증가}System.out.println("Sum: "+ sum);

}}

프로그래밍 기초 강원대학교 20/36

Page 21: 프로그래밍 기초

while vs do-while

while 루프조건이 거짓이면 , 루프는 한 번도 실행되지 않는다 .

do-while 루프적어도 한 번은 언제나 실행된다 .

프로그래밍 기초 강원대학교 21/36

Page 22: 프로그래밍 기초

for 문

루프 실행 회수를 지정할 경우에 사용

프로그래밍 기초 강원대학교 22/36

Page 23: 프로그래밍 기초

int count = 0; int i;for (i = 0; i < 10; i++)

count++;

프로그래밍 기초 강원대학교 23/36

Page 24: 프로그래밍 기초

for (initialization; loop condition; update statement) {

statement-1:statement-2;…statement-n:

}  

프로그래밍 기초 강원대학교

initialization: 초기화loop condition: 루프 조건statement: 문장update: 증감문 ( 갱신문 )

24/36

Page 25: 프로그래밍 기초

int count = 0; int i;for (i = 0; i < 10; i++)

count++;

프로그래밍 기초 강원대학교

int count = 0; for (int i = 0; i < 10; i++)

count++;

변수 i 가 for 문장 안에서만 유효하다 .

25/36

Page 26: 프로그래밍 기초

예제몇 개의 정수를 더하시겠습니까 ? 44 개의 정수를 입력하세요 .3579Sum: 24

프로그래밍 기초 강원대학교 26/36

Page 27: 프로그래밍 기초

import java.util.Scanner;public class ForAddUp {

public static void main (String[] args) {Scanner input =new Scanner(System.in); 

int sum = 0; int size; // 더할 정수의 개수int number; // 더할 다음 정수

System.out.print(" 몇 개의 정수를 더하시겠습니까 ? ");size = input.nextInt();System.out.println(size+"4 개의 정수를 입력하세요 . "); 

for (int count = 1; count <= size; count++) {number = input.nextInt(); sum += number;

} System.out.println("Sum: "+ sum);

}}

프로그래밍 기초 강원대학교 27/36

Page 28: 프로그래밍 기초

for 문의 동작 특징

• 초기화는 정확하게 한 번만 실행된다 .

• 루프 조건은 문장 블록을 실행하기 전에 항상 테스트된다 .

• 증감문은 문장 블록 실행 후에 항상 실행된다 .

프로그래밍 기초 강원대학교 28/36

Page 29: 프로그래밍 기초

중첩 루프

프로그래밍 기초 강원대학교 29/36

Page 30: 프로그래밍 기초

break 문의 사용switch 문 내부에서 실행될 때

switch 문을 종료하고 switch 문 다음의 첫 번째 문장으로 이동

루프 내부에서 실행될 때 (while 문 , for 문 )루프를 “탈출”하여 루프 다음 문장으로 이동

프로그래밍 기초 강원대학교 30/36

Page 31: 프로그래밍 기초

예제

• 유효하지 않은 신용카드 번호 찾기

1. 가장 오른쪽에서 두 번째 숫자부터 시작하여 왼쪽으로 하나씩 거른 숫자를 두 배로 만든다 . 만약 두 배로 만든 숫자의 값이 9 보다 크면 그 값에서 9 를 뺀다 .

2. 1 단계에서 계산한 새 값들과 변하지 않은 자리의 값들을 모두 합한다 .

3. 만약 2 단계의 합이 0 으로 끝나지 않으면 (10 의 배수가 아니면 ) 카드 번호는 유효하지 않다 .

프로그래밍 기초 강원대학교 31/36

Page 32: 프로그래밍 기초

5113 4765 1234 8002

1.오른쪽에서 두 번째 숫자부터 하나씩 거른 숫자들을 두 배로 만든다 . 9 를 초과하는 값은 9 를 빼준다 .

하나씩 거른 숫자들에 두 배를 하고 , 결과가 9 보다 크면 9 를 뺀다 .

2.합을 계산한다 .: 1+1+2+3+8+7+3+5+2+2+6+4+7+0+0+2 = 53.

3.합 53 의 끝자리 값이 0 이 아니다 . 따라서 이 번호는 유효한 카드 번호가 아니다 .

프로그래밍 기초 강원대학교 32/36

Page 33: 프로그래밍 기초

실행 예출력 1:Enter Credit Card Number: 5113476512348002Invalid number 출력 2:Enter Credit Card Number: 123456789876543Credit card number passes test

프로그래밍 기초 강원대학교 33/36

Page 34: 프로그래밍 기초

import java.util.*;

public class CheckCreditCard

{

public static void main (String[] args) {

Scanner input =new Scanner(System.in);

final int MAX_DIGITS = 16; // 신용 카드 번호 숫자의 최대 개수 long number; // 신용 카드 번호 long sum = 0; // 최종 합의 값은 끝자리가 0 이 되어야 함 long digit; 

System.out.print("Enter Credit Card Number:" );

number = input.nextLong();

 

프로그래밍 기초 강원대학교 34/36

Page 35: 프로그래밍 기초

import java.util.Scanner;public class CheckCreditCard {

public static void main (String[] args) {

Scanner input =new Scanner(System.in);final int MAX_DIGITS = 16;// 신용 카드 번호 자리 수long number; // 신용 카드 번호long sum = 0; // ( 매우 큰 수 이므로 long 타입 )

long digit; // 작업을 위한 변수 ( 단단위 수 )

System.out.print("Enter Credit Card Number:" );number = input.nextLong();

프로그래밍 기초 강원대학교 35/36

Page 36: 프로그래밍 기초

 for (int i = 1; i <= MAX_DIGITS; i++) {digit = number % 10; // 가장 오른쪽 숫자 추출if (i % 2 == 0) { // 2 를 곱해줄 숫자인가 ?

digit = digit*2;if (digit > 9) // 결과가 9 보다 크면 9 를 빼기

digit -= 9;}sum += digit; // digit 을 누적하기number =number/10; // 가장 오른쪽 숫자 제거

}

if (sum % 10 != 0) // 합의 끝자리가 0 이 아닌가 ?System.out.println("Invalid number");

elseSystem.out.println("Credit card number passes test");

}}

프로그래밍 기초 강원대학교 36/36