Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3 Flow of Control

Similar presentations


Presentation on theme: "Chapter 3 Flow of Control"— Presentation transcript:

1 Chapter 3 Flow of Control
프로그래밍 기초와 실습 Chapter 3 Flow of Control

2 Contents Relational, Equality, and Logical Operators
Short-Circuit Evaluation The Compound Statement The Empty Statement The if and if-else Statements Nested Flow of Control The switch Statement The Conditional Operator

3 Contents The while Statement The for Statement The Comma Operator
The do Statement The goto Statement The break and continue Statements Nested Flow of Control

4 Relational, Equality, and Logical Operators
Relational operators (관계 연산자) less than < greater than > less than or equal to <= greater than or equal to >= Equality operators (등가 연산자) equal to == not equal to != Logical operators (논리 연산자) (unary) negation ! logical and && logical or ||

5 Relational, Equality, and Logical Operators
Associativity Precedence 가 동일한 연산자가 서로 만났을 때 연산 되어지는 순서 방향 Operators Associativity ( ) ++ (postfix) -- (postfix) left to right + (unary) - (unary) ++ (prefix) -- (prefix) right to left * / % + - < <= > >= == != && || ? : = += -= *= /= etc , (comma operator)

6 Relational Operators and Expressions
관계연산자 Syntax 틀린 사용의 예 < : less than > : greater than <= : less than or equal to >= : greater than or equal to [Ex] a =< b /* out of order */ a < = b /* space not allowed */ a >> b /* this is a shift expression */

7 Relational Operators and Expressions
i = 3 , j = 2 , k = 1 /* but different interpret */ if ( i > j > k ) → ( i > j ) > k /* 결과는 F */ int i =1, j = 2, k = -7 ; i < i + j; /* i < (i + j) → */ 3 < j < 5; /* ( 3 < j ) < 5 → 1 */ (- i) - 5 * j >= k + 1; /* (( -i)→( 5 * j )) >= ( k + 1 ) → 0 */ i가 j보다 크므로 true 는 1이므로 1 > k가 되어 결과는 False 수학적인 표현의 의미로, j 가 가진 값이 i , k 가 가진 값의 중간 값이라고 표현하려면 ( i < j ) && ( j < k ) → true

8 Relational Operators and Expressions
관계식에서의 우선순위와 결합법칙의 사용 예 Declarations and initializations int i = 1, j = 2, k = 3; double x = 5.5, y = 7.7; Expression Equivalent expression Value i < j - k i < ( j – k ) -i + 5 * j >= k + 1 ( ( -i ) + ( 5 * j ) ) >= ( k + 1 ) 1 x – y <= j – k – 1 ( x – y ) <= ( ( j – k ) – 1 ) x + k + 7 < y / k ( ( x + k ) + 7 ) < ( y / k )

9 Equality Operators and Expressions
등가 연산자 Syntax lower precedence than relational operators 등가식에서의 우선순위와 결합법칙의 사용 예 = : assignment operator == : equality operator != : not equality operator Declarations and initializations int i = 1, j = 2, k = 3; Expression Equivalent expression Value i == j j == i i != j j != i 1 i + j + k == - 2 * - k ((i + j) + k ) == (( -2) * (-k))

10 Logical Operators and Expressions
논리 연산자 Syntax 부정 연산자의 값 ! : logical negative && : logical and || : logical or not operator T && T ? T , otherwise F F || F ? F , otherwise T Values of negation expressions 긍정 부정 a !a zero 1 nonzero

11 Logical Operators and Expressions
C언어에서 !연산자는 일반적 논리에서의 ‘not’ 연산자와 다르다. [Ex] s가 논리 문 : not ( not s) = s 의 결과값. C 언어: !( !5 ) = !( 0 ) = 1 의 값을 생성 C언어에서는 0이 아닌 모든 값은 true로 인식한다. !5는 !(true)와 같으므로 !5 = 0 의 값을 가진다. [Ex] char c = ‘A’ ! c !c = !(A) 으로 나타낼 수 있다. 여기서 A는 0이 아닌 값이므로 true의 값을 가진다. !c는 결국 not true이므로 결과는 0 (false) 이다.

12 Logical Operators and Expressions
논리식에서의 우선순위와 결합법칙의 사용 예 Declarations and initializations int i = 7, j = 7; double x = 0.0, y = 999.9; Expression Equivalent expression Value ! (i – j) + 1 ( ! (i – j)) + 1 2 ! i – j + 1 (( ! i ) – j ) + 1 -6 ! ! ( x ) ! ( ! ( x )) 1 ! x * ! ! y (! x) * (! (! y))

13 Logical Operators and Expressions
Binary logical operators && 와 ||는 식에 적용되면 0이나 1의 값을 생성한다. Value of bitwise expressions a b a && b a || b zero nonzero 1 Truth table for && and || a b a && b a || b F T

14 Logical Operators and Expressions
이항 논리식에서의 우선순위와 결합법칙의 사용예 Declarations and initializations int i = 3, j = 3, k = 3; double x = 0.0, y = 2.3; Expression Equivalent expression Value i && j && k ( i && j ) && k 1 x || i && j -3 x || ( i && ( j -3 ) ) i < j && x < y ( i < j ) && ( x < y ) i < j || x < y ( i < j ) || ( x < y )

15 Logical Operators and Expressions
Short-Circuit Evaluation &&와 ||의 연산에서 true와 false의 값이 결정됨과 동시에 계산과정은 멈추게 된다. expr1 && expr2 expr1의 결과가 F이면, expr2 연산 할 필요 없이 결과는 F no need to evaluate expr2 expr1 || expr2 expr1의 결과가 T이면, expr2 연산 할 필요 없이 결과는 T

16 Logical Operators and Expressions
Short-Circuit Evaluation의 예 [Ex] int i, j; i = 2 && ( j = 2 ); printf(“%d %d\n”, i, j); /* 1 2 is printed */ ( i = 0 ) && ( j = 3 ); printf(“%d %d\n”, i, j); /* 0 2 is printed */ i = 0 || ( j = 4 ); printf(“%d %d\n”, i, j); /* 1 4 is printed */ ( i = 2 ) || ( j = 5 ); printf(“%d %d\n”, i, j); /* 2 4 is printed */

17 Logical Operators and Expressions
구간 확인 하는 경우 여러 개의 변수의 구간을 확인하는 경우 [Ex] if ( i > -5 && i < 10 ) printf(“ 구하는 수는 -5와 10의 범위 내에 있습니다. “); else printf(“구하는 수는 -5와 10의 범위 내에 있지 않습니다. “); [Ex] if( ( ( age >= 10 ) && ( age < 20 ) ) && ( height >= 170 ) ) printf(“ %s은 10대이고, 키가 170 이상인 사람입니다.”, name ); if( ( ( age >= 10 ) && ( age < 20 ) ) || ( height >= 170 ) ) printf(“ %s은 10대이거나, 키가 170 이상인 사람입니다.”, name );

18 Logical Operators and Expressions
윤년을 확인하는 예제 윤년이란? : 2월 29일까지 있는 해로, 4로 나누어지는 수 중 100으로 나누어지는 수는 평년, 아니면 윤년, 하지만 400으로 나누어지는 수는 윤년! [Ex] if (year % 4 == 0 ) { if (year % 400 == 0) printf(“윤년”); else if( year % 100 == 0) printf(“평년”); else printf(“윤년”); } else printf(“평년”); [Ex] 하나의 조건절로 나타냄 if (((year%4 == 0) && (year%100 != 0)) || ( year%400 == 0)) printf(“윤년”); else printf(“평년”);

19 Logical Operators and Expressions
연산자 우선순위의 예 [Ex] a = b += c++ - d + --e / -f ;  (a = ( b += (c++) – d + ( (--e) / (-f) ) ) ) a < -b || a < c && c + 2 < d  (( a < -b ) || (( a < c ) && ( (c + 2) < d ))) c값의 증가는 모든 계산이 끝나고 이루어진다. (++c 일 경우는 c값부터 증가시킨 후 계산) 8 7 1 5 6 2 4 3 3 1 2 5 7 4 6

20 The Compound Statement
복합문 중괄호 {}로 묶여진 선언문과 실행문이다. 실행문을 실행 가능한 단위로 그룹화 하는 것이다. 선언문이 복합문의 시작 부위에 왔을 때, 그 복합문을 block 이라고 한다. [Ex] { int a = 1; int b = 2; printf(“a=%d, b=%d \n”); } printf(“a=%d, b=%d, c=%d\n”); /* compile error */

21 The Empty Statement 공백문 공백문은 하나의 세미콜론을 사용하여 나타낸다.
공백문은 문법 상으로 필요하지만 의미상으로는 아무 동작도 요구하지 않는 곳에서 사용된다. if-else와 for같은 제어의 흐름에 영향을 주는 구조에서 유용하게 사용된다. [Ex] a = b; /* an assignment statement */ a + b + c; /* legal, but no useful work done */ ; /* an empty statement */ printf("%d\n", a); /* a function call */

22 The if and if-else Statements
if statement Syntax expression이 true라면 statement가 실행된다. 그렇지 않으면 statement를 실행되지 않고 다음 문장으로 제어순서가 넘어가게 된다. Evaluate logical expression If an expression is T → Execute statement(s) F → Do nothing if (expression) statement if (expression){ statement statement : }

23 The if and if-else Statements
[Ex] if ( x > y ) y = x; /* x>y일 때, x의 값이 y로 대입 */ if ( j > 10 ){ /* j가 10보다 클때만 block이 실행 */ j = 1 ; level = level + 1 ; printf(“clear step!\n”); } if ( grade >= 90 ) printf("Congratulations! \n"); printf("Your grade is %d.\n", grade ); /* grade값이 90 이상일 때만 Congratulations!가 표시되고 , 두 번째 printf()문은 항상 실행된다. */

24 The if and if-else Statements
If... else Syntax if (expression) { statement1; statement2; : } else { statement1; statement2; [Ex] if (x == y) { printf(“x is equal to y”); e_count += 1 ; } else { printf(“x is not equal to y”); ne_count += 1 ;

25 The if and if-else Statements
[Ex] if ( j < k ) min = j; printf(“ j is smaller than k \n”); 위의 code를 다음과 같이 쉽게 고쳐 쓸 수 있다. if ( j < k ) { } if ( n < 0 ) printf(“n is less than 0\n”); else if ( n == 0 ) printf(“n is equal to 0\n”); else printf(“n is greater than 0\n”);

26 find_min Program [Ex] /* find the minimum of three values. */
#include <stdio.h> int main(void) { int x, y, z, min; printf( “Input three integers: “ ); scanf( “%d%d%d”, &x, &y, &z ); if (x < y) min = x; else min = y; if ( z < min) min = z; printf( “The minimum value is %d\n”, min ); return 0; } 최소값을 찾는 if. else문. Input three integers: ꎠ The minimum value is 5

27 Nested Flow of Control Nested if statement if ( expr1) statement1;
else if ( expr2) statement2; else if ( expr3) statement3; ….. else if ( exprN) statementN; else default statement1; next statement

28 Nested Flow of Control Nested if statement [Ex] if (age < 18)
printf(“children”); else if (age < 65) printf(“adult”); else printf(“senior”); age가 18미만인 경우 children출력 age가 18과 65사이 adult출력 age가 65보다 많은 경우 senior출력

29 Nested Flow of Control Nested if statement [Ex] if (c == ‘ ’)
++blank_cnt ; else if (c >=‘0’ && c <= ‘9’) ++digit_cnt ; else if (c >=‘A’ && c <= ‘Z’) ++upper_cnt ; else if (c >=‘a’ && c <= ‘z’) ++lower_cnt ; else if (c ==‘\n’) ++nl_cnt ; else ++other_cnt ; c가 space인 경우 c가 0과 9사이인 경우 c가 A와 Z사이인 경우 c가 a와 z사이인 경우 c가 new line인 경우 c가 그외인 경우

30 The switch Statement switch문은 if-else문을 일반화한 다중 조건문
switch ( expression ){ case constant-expression : statements ……………….. default : statements } [Ex] switch (grade) { case 4 : case 3 : case 2 : case 1 : printf(“Passing”); break; case 0 : pritnf(“Failing”); break; default : printf(“Illega grade”); break; }

31 The switch Statement switch에서 break의 역할 [Ex] switch (grade){
case 4 : printf(“A”) ; break; case 3 : printf(“B”) ; break; case 2 : printf(“C”) ; break; case 1 : printf(“D”) ; break; default : printf(“Illegal grade”); break; } grade = 4  A grade = 3  B grade = 2  C grade = 1  D grade = 0  illegal grade [Ex] switch (grade){ case 4: printf(“A”) ; case 3: printf(“B”) ; case 2: printf(“C”) ; case 1: printf(“D”) ; default : printf(“illegal grade”); } grade = 4  ABCDillegal grade grade = 3  BCDillegal grade grade = 2  CDillegal grade grade = 1  Dillegal grade grade = 0  illegal grade

32 The switch Statement 날짜를 표시하는 예제 [Ex] switch (day) {
case 1: case 21: case 31: printf(“st”); break; case 2: case 22: printf(“nd”); break; case 3: case 23: printf(“rd”); break; default: printf(“th”); break; }

33 The switch Statement 앞의 예제를 if-else로 변환 [Ex]
if ( day == 1 || day == 21 || day ==31 ) printf(“st”); else if ( day == 2 || day = 22 ) printf(“nd”); else if ( day == 3 || day = 23 ) printf(“rd”); else printf(“th”);

34 The switch Statement 숫자를 영문으로 표시하는 예제 #include <stdio.h> main()
{ int number; printf( "Enter number(1~99): “ ); scanf( "%d", &number ); if ( number < 1 || number > 99 ) printf( "Enter numbers between 1 and 99“ ); printf( "Try again“ ); } 1~99 숫자만 입력 받는다

35 The switch Statement 숫자를 영문으로 표시하는 예제
else if ( number >= 10 && number <= 19 ) switch(number) { case 11: printf("eleven\n");break; case 12: printf("twelve\n");break; case 13: printf("thirteen\n");break; case 14: printf("fourteen\n");break; case 15: printf("fifteen\n");break; case 16: printf("sixteen\n");break; case 17: printf("seventeen\n");break; case 18: printf("eighteen\n");break; case 19: printf("nineteen\n");break; default: break; } 1~19 숫자의 출력 구문

36 The switch Statement 숫자를 영문으로 표시하는 예제 1의 자리의 숫자 else {
switch( number / 10 ) { case 2: printf("twenty "); break; case 3: printf("thirty "); break; case 4: printf("forty "); break; case 5: printf("fifty "); break; case 6: printf("sixty "); break; case 7: printf("seventy "); break; case 8: printf("eighty "); break; case 9: printf("ninety "); break; default:printf(" ");break; } /* end switch */ switch( number % 10 ){ case 1: printf("one\n");break; case 2: printf("two\n"); break; case 3: printf("three\n"); break; case 4: printf("four\n"); break; case 5: printf("five\n"); break; case 6: printf("six\n"); break; case 7: printf("seven\n"); break; case 8: printf("eight\n"); break; case 9: printf("nine\n"); break; default:break; }/* end switch */ }/* end else */ } 10의 자리의 숫자

37 The Conditional Operator
Conditional Operator Syntax 조건식 연산자 ? : 는 삼항 연산자이다. expr1이 먼저 계산된 후, 참이면 expr2가 실행, 거짓이면 expr3이 수행된다. if-else 문 Conditional Operator expr1 ? expr2 : expr3 if ( y < z) x = y; else x = z x = ( y < z ) ? y : z

38 The while Statement while Syntax while (expr) statement next statement
먼저 expr이 계산된다. 만일 expr의 결과가 true이라면 statement가 실행되고, 제어는 while 루프의 시작 부분으로 다시 전달 된다. expr의 값이 true일 경우에만 statement가 실행된다. expr의 값이 false일 경우에는 next statement가 실행된다. while (expr) statement next statement [Ex] /* 1~10까지의 합을 구하는 statement*/ i = 1; while ( i <= 10 ) { sum += i; ++i; }

39 Finding Maximum Values
[Ex] /* Find the maximum of n real calues. */ #include <stdio.h> int main(void) { int cnt = 0, n; float max, x; printf("The maximim value will be computed.\n"); printf("How many numbers do you wish to enter?"); scanf("%d", &n); while( n <= 0 ) { printf("\nERROR: Positive integer required.\n\n"); }

40 Finding Maximum Values
printf("\nEnter %d real numbers: ", n); scanf("%f", &x); max = x; while (++cnt < n) { if (max < x) } printf("\nMaximum value: %g\n", max); return 0; The maximim value will be computed. How many numbers do you wish to enter? 3 ꎠ Enter 3 real numbers: ꎠ Maximum value: 10

41 The for Statement for statement Syntax for ( expr1; expr2;expr3 )
위의 statement는 다음 statement와 동일하다. expr1은 for loop를 초기화 하는데 사용. for ( expr1; expr2;expr3 ) statement next statement statement를 실행한 후에 expr3의 조건을 실행한다. expr2의 조건이 계산이 된다. 그 조건이 true가 되면 for loop안에 있는 statement를 실행 expr1; while (expr2) { statement expr3; } next statement

42 The for Statement Counting up from 0 to n-1 Counting up from 1 to n
Counting up from n-1 to 0 Counting up from n to 1 10부터 1까지 count하는 예제 for ( i = 0; i < n; i++ ); for ( i = 1; i <= n; i++ ); for ( i = n -1; i >= 0; i-- ); for ( i = n; i > 0; i-- ); [Ex] for ( i = 10; i > 0; --i) printf(“ T minus %d and counting\n”, i );

43 The for Statement 제곱근을 나타내는 Program [Ex]
/* Prints a table of squares using a for statement */ #include <stdio.h> main() { int i, n; printf(“Enter number of entries in table: “); scanf(“%d”, &n); for ( i = 1; i <= n; i++ ) printf(“%10d%10d\n”, i, i * i ); return 0; } Enter number of entries in table : 5 ꎠ

44 The for Statement 1에서 100사이의 숫자 중 5의 배수를 한 line에 4개씩 출력 [Ex]
#include <stdio.h> main() { int i=1,j=0; for ( i = 1; i <= 100; i++ ) { if( ( i%5 ) == 0 ) { printf(“ %d ",i ); j++; if( ( j % 4 ) == 0 ) printf("\n"); }

45 The Comma Operator Comma Operator Syntax C의 모든 연산자중에 가장 낮은 우선순위를 가짐.
expr1 , expr2 [Ex] a = 0, b = 1; Declarations and initializations int i, j, k = 3; double x = 3.3; Expression Equivalent expression value i = 1, j = 2, ++k + 1 ((i = 1), (j=2)), ((++ k) +1) 5 k != 7, ++x * ( k != 7 ), ((( ++x) * 2.0 ) + 1 ) 9.6

46 The do Statement do { statement; } while(expression) ; do 문 Syntax
양의 정수만을 읽는 프로그램 do { statement; } while(expression) ; next statement; [Ex] do { printf(“Input a positive integer: “); scanf(“%d”, &n); if (error = ( n <= 0 )) printf(“\nERROR: Negative value not allowed!\n\n”); } while (error);

47 #include <stdio.h>
main(){ int n, error; do { printf("Input a positive integer: "); scanf("%d", &n); if (error = ( n <= 0 )) printf("\n ERROR: Negative value not allowed! \n\n"); }while (error); printf("\n A positive value is inserted! \n"); }

48 The do Statement do 문과 while문의 비교 ( do statements )
[Ex] /* 정수의 자릿수를 출력하는 프로그램 */ #include <stdio.h> main(void) { int digits = 0, n; printf(“Enter a nonnegative integer: “); scanf(“%d”, &n); do { n /= 10; digits++; } while ( n > 0 ); printf(“The number has %d digit(s).\n”, digits); return 0; } 입력 받은 수를 반복적으로 10으로 나누어서 자릿수를 계산한다. Enter a nonnegative integer : 0 ꎠ The number has 1 digit(s).

49 The do Statement do 문과 while문의 비교 ( while statements )
[Ex] /* 정수의 자릿수를 출력하는 프로그램 */ #include <stdio.h> main(void) { int digits = 0, n; printf(“Enter a nonnegative integer: “); scanf(“%d”, &n); while ( n > 0 ) { n /= 10; digits++; } printf(“The number has %d digit(s).\n”, digits); return 0; 입력 받은 수를 반복적으로 10으로 나누어서 자릿수를 계산한다. Enter a nonnegative integer : 0 ꎠ The number has 0 digit(s).

50 The goto Statement goto문은 현재 함수에서 label이 붙은 문장으로 무조건 분기할 수 있게 한다. (가능한 사용하지 않는다.) [Ex] goto error; …. error: { printf(“An error has occurred – bye!\n”); exit(1); } [Ex] while (scanf(“%lf”, &x) == 1 ) { if ( x < 0.0 ) goto negative_alert; printf(“%f %f\n”, sqrt(x), sqrt(2 * x)); } negative_alert: printf(“Negative value encountered!\n”);

51 The break and continue Statements
break문은 가장 내부의 루프나 switch문으로부터 빠져 나오는데 사용된다. 입력 받은 수가 음수이면 loop를 빠져 나오는 코드 [Ex] while(1) { scanf(“%lf” , &x); if ( x < 0.0 ) break; /* exit loop if x is negative */ printf(“%f\n”, sqrt(x)); } /* break jumps to here */

52 The break and continue Statements
[Ex] for( i = 2 ; i < n ; i++ ) if (n % i == 0) break; if (i == n) printf(“n is a prime number\n”); for( ; ; ) { scanf(“%d”, &n); if( n == 0 ) break; } i가 2에서 1씩 증가하면서 n이 될 때까지 n을 i로 나누어지는 지 check. i로 나누어 지면 가장 가까운 반복문 for문을 종료 즉, for문의 exit -> i < n : n은 소수 아님 또는 i=n이 되어 exit -> i = n : n은 소수 For문의 경우 항상 true로 무한 loop를 돌게 됨 그러나 read한 n의 값이 0라면 break, for문을 exit

53 The break and continue Statements
cotinue문은 루프의 현재 반복 동작을 멈추게 하고 즉시 루프의 다음 반복 동작을 하게 한다. ±0.01 사이의 숫자가 입력되면 continue문이 실행되는 코드 [Ex] while ( cnt < n ) { scanf(“%lf”, &x ); if( x > && x < +0.01) continue; /* disregard small values */ ++cnt; sum += x; /* continue transfers control here to begin next iteration */ }

54 The break and continue Statements
if 조건절을 바꾸면 continue문을 사용하지 않아도 되는 예제 [Ex] n = 0; sum = 0; while ( n < 10) { scanf( “%d”, &i ); if ( i == 0 ) continue; sum += i; n++; /* continue jumps to here */ } /* end of while */ if ( i != 0 ) { } /* end of if */ } /* end of while */

55 The break and continue Statements
break 사용시 결과와 continue 사용시 결과의 차이 [Ex] break #include <stdio.h> main() { int n = 0, i = 1; int sum = 0; for ( ; i <= 10; i++ ) { if ( i == 5 ) break; sum += i; n++; } printf(“Sum=%d\n”, sum); [Ex] continue for ( ; i <= 10; i++ ){ if ( i == 5 ) continue; = 10 = 50 sum = 10 sum = 50

56 Nested Flow of Control Nested for statement
[Ex] for ( expr1; expr2; expr3) { statement1; for ( expr4; expr5; expr6 ) { statement2; for ( expr7; expr8; expr9) { statement3; } 1 2 3

57 Nested Flow of Control Nested for statement [Ex]
int i , k , count = 0 ; for ( i=1 ; i <= 10 ; i+=2) for ( k=1 ; k <= i ; k++) { if ( k%2 == 0 ) count++ ; } printf(“ Count = %d \n”, count); 1 2 Count = 10

58 다중 for 문 구구단을 출력하자. #include <stdio.h> void main(void){ int i, j, result; for (i=2; i<=9; i++) { for (j=1; j<=9; j++) result = i * j; printf(" %d * %d = %d \n", i, j, result); }

59 #include <stdio.h>
main(){ int i , k , count = 0 ; for ( i=1 ; i <= 10 ; i+=2){ for ( k=1 ; k <= i ; k++){ if ( k%2 == 0 ){ printf(" \n i=%d , k = %d ", i,k); count++ ; } printf(" \n\n Count = %d ", count);

60 2로 나누어서 나머지가 0인 경우는 총 10번이다. i k , 2 , 3 , 2 , 3 , 4 , 5 , 2 , 3 , 4 , 5 , 6 , 7 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9

61 Nested Flow of Control Nested for statement [Ex] int i, k, count = 0 ;
for ( i = 1 ; i <= 10 ; i++ ) for ( k = 1 ; k <= i ; k++ ) { if ( k % 4 == 0 ) break; count++; } printf( “Count = %d\n”, count ) ; 1 2 Count = 27

62 Nested Flow of Control Nested for statement [Ex]
for ( j = 1 ; j <= 5 ; j++ ) { for ( k = 1, sum = 0 ; k <= 3 ; k++ ) if ( j != k ) sum += j + k ; printf (“%5d\t%5d\t%5d\n”, sum, j, k ) ; }

63 add_to_n Program /* Find triples of integers that add up to N. */
#include <stdio.h> #define N 7 int main(void) { int cnt = 0, i, j, k, n; for ( i = 0; i <= N; ++i ) for( j = 0; j <= N; ++j ) for ( k = 0; k <= N; ++k ) if ( i + j + k == N ) { ++cnt; printf("%3d%3d%3d\n", i, j, k); } printf( "\nCount: %d\n", cnt ); return 0; } 0 0 7 0 1 6 0 2 5 0 3 4 5 0 2 5 1 1 6 1 0 7 0 0 Count : 36

64 수고하셨습니다. Flow of Control


Download ppt "Chapter 3 Flow of Control"

Similar presentations


Ads by Google