最新C程式語言 蔡明志 編著.

Slides:



Advertisements
Similar presentations
Fundamental of C programming
Advertisements

Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
For loops For loops are controlled by a counter variable. for( c =init_value;c
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS
LOOP (Part 2) for while do-while 1. TK1913-C Programming2 TK1913-C Programming 2 Loop : for Loop : for Condition is tested first Loop is controlled by.
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
Beginning C for Engineers Fall 2005 Lecture 2 – Section 2 (9/7/05) Section 4 (9/8/05)
Conditional Statement
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
CP104 Introduction to Programming Selection Structures_3 Lecture 11 __ 1 The Switch Statement The switch statement provides another means to select one.
UniMAP Sem II-09/10EKT120: Computer Programming1 Week 3 – Selection Structures.
IF-ELSE IF-ELSE STATEMENT SWITCH-CASE STATEMENT Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
CHAPTER 5: Decision Making and Looping CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (Sept 2013)
Real World Applications: Generating Prime Numbers  Problem Write a program that prints all positive prime integers less than or equal to n. A positive.
Introduction to Computer Algorithmics and Programming Ceng 113 Program Control Statements.
Basic Concepts – Conditionals Conditionals are used for making decisions. The conditionals available in C are if and if-else statements the switch statement.
CS140: Intro to CS An Overview of Programming in C (part 3) by Erin Chambers.
Review the following: if-else One branch if Conditional operators Logical operators Switch statement Conditional expression operator Nested ifs if –else.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
Chapter 5: Structured Programming
COP 3275 COMPUTER PROGRAMMING USING C Instructor: Diego Rivera-Gutierrez
C Programming Lecture 7 : Control Structures. Control Structures Conditional statement : if, switch Determine a block of statements to execute depending.
CS140: Intro to CS An Overview of Programming in C by Erin Chambers.
Dr. Soha S. Zaghloul2 Let arr be an array of 20 integers. Write a complete program that first fills the array with up to 20 input values. Then, the program.
Problems Reads a letter grade from user and displays the corresponding range for that letter grade (A  , B  80-89, C  70-79, D  60-69, otherwise.
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
CSCI 171 Presentation 3. Operators Instructs C to perform some operation Assignment = Mathematical Relational Logical.
LESSON 4 Decision Control Structure. Decision Control Structures 1. if statement 2. if-else statement 3. If-else-if statement 4. nested if statement 5.
CS115 FALL Senem KUMOVA-METİN1 CHAPTER 4 FLOW OF CONTROL-1 Operators, If and switch statements.
Dr. Sajib Datta Jan 23,  A precedence for each operator ◦ Multiplication and division have a higher precedence than addition and subtraction.
 Real numbers representation - Floating Point Notation  First C Program  Variables Declaration  Data Types in C ◦ char, short, int, long, float, double,
CHAPTER 4 REPETITION STRUCTURES 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi.
Dr. Sajib Datta Sep 3,  A new operator used in C is modulus operator: %  % only used for integers, not floating-point  Gives the integer.
BY ILTAF MEHDI(MCS,MCSE, CCNA) 1. INSTRUCTOR: ILTAF MEHDI (MCS, MCSE, CCNA, Web Developer) BY ILTAF MEHDI(MCS,MCSE, CCNA) 2 Programming Fundamentals Chapter.
Tutorial #4 Summer 2005.
ECE Application Programming
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
LESSON 4 Decision Control Structure
Decisions Chapter 4.
CMPT 201 if-else statement
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
The if Statement Format or No Condition satisfied? Yes
Week 3 C Program Structures (Selection Structures)
ECE Application Programming
Chapter 4 (Conditional Statements)
Week 3 – Selection Structures
Week 4 – Repetition Structures / Loops
Condition Statements.
DKT121: Fundamental of Computer Programming
CSE1320 INTERMEDIATE PROGRAMMING Operators+Conditionals+Loop
مبانی کامپیوتر و برنامه سازی
Introduction to Programming
Looping.
C Programming Variables.
Chapter 5 Decision Making and Branching
Điều kiện Chương 5.
Basic Concepts – Conditionals
Conditions and Boolean Expressions
Week 2 Variables, flow control and the Debugger
Relational, Logical, and Equality Operators
Introduction to Computer Organization & Systems
CPS125 Week 5.
Week 3 – Program Control Structure
Control Structures Lecture 6.
EECE.2160 ECE Application Programming
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
ICS103: Programming in C 5: Repetition and Loop Statements
Control Structure គោលបំណងនៃមេរៀន អ្វីជា Control structure ?
Presentation transcript:

最新C程式語言 蔡明志 編著

5 選擇敘述 5.1 if敘述與關係運算子 5.2 if.....else敘述 5.3 巢狀if敘述 5.4 真值與假值 5.5 邏輯運算子 5.4 真值與假值 5.5 邏輯運算子 5.6 條件運算子 5.7 else if多重選擇 5.8 switch敘述 5.9 goto敘述

5.1 if敘述與關係運算子 if敘述又稱為“分支敘述 (branching statement)” if後面至少有個小括號,小括號裡面乃為一般的運算式,譬如(a>b)(a大於b)或是(x == y)(x等於y)等等。

#include <stdio.h> #include <stdlib.h> int main() { /* ch5 ifl.c */ #include <stdio.h> #include <stdlib.h> int main() { int num; printf("Please input a number between 1 to 100 : "); scanf("%d", &num); if (num < 50) printf("The number is less than 50 !\n"); if (num == 50) printf("The number is equal to 50 !\n"); if (num > 50) printf("The number is greater to 50 !\n"); system("PAUSE"); return 0; } 4

執行的結果: Please input a number between 1 to 100 : 14 The number is less than 50 ! Please input a number between 1 to 100 : 50 The number is equal to 50 ! Please input a number between 1 to 100 : 62 The number is greater to 50 !

關係運算子便可組成關係運算式(relational expression)。C語言共提供有六種關係運算子,它們都是二元運算子;基於兩數值間的所有關係,可歸納為下表: 表 5-1 關係運算子 運算子 意義 < 小於 <= 小於等於 = = 等於 >= 大於等於 > 大於 != 不等於 6

#include <stdio.h> #include <stdlib.h> int main() { /* ch5 if2.c */ #include <stdio.h> #include <stdlib.h> int main() { int num; int flag = 0; num = 14; if (num < 50){ flag++; printf("Message 1...\n"); } if (num > 50) printf("Message 2...\n"); if (num == 50) printf("Message 3...\n"); printf("\nflag is %d\n",flag); system("PAUSE"); return 0; 7

程式輸出如下: 根據結果顯示,我們可畫出下列流程: Message 1... Message 2... Message 3... flag is 1

5.2 if.....else敘述

#include <stdio.h> #include <stdlib.h> int main() { /* ch5 if_else.c */ #include <stdio.h> #include <stdlib.h> int main() { char ch; printf("Play again ? [Y/y] "); scanf("%c", &ch); if (ch = = 'y') ch = 'Y'; if (ch = = 'Y'){ printf("Play again !\n"); printf("I like this game...\n"); } else{ printf("Exit the game !\n"); printf("I don't like this game.\n"); printf("Test over !\n"); system("PAUSE"); return 0; 11

/* ch5 nest1.c */ #include <stdio.h> #include <stdlib.h> int main() { int num; printf("Please input a number between 1 to 100 : "); scanf("%d", &num); if(num >= 1) if(num <= 100) printf("Valid number %d\n", num); else printf("Invalid number %d.\n", num); printf("Bye Bye !\n"); system("PAUSE"); return 0; }

else屬於第一個 if else屬於第二個 if

從執行結果來推導: Please input a number between 1 to 100 : 5060 Invalid number 5060 Bye Bye ! Please input a number between 1 to 100 : 14 Valid number 14 Please input a number between 1 to 100 : -62

#include <stdio.h> #include <stdlib.h> int main() { /* ch5 nest2.c */ #include <stdio.h> #include <stdlib.h> int main() { int num; printf("Please input a number between 1 to 100 : "); scanf("%d", &num); if (num >= 1){ if (num <= 100) printf("Valid number %d\n", num); else printf("Invalid number %d\n", num); } printf("Bye Bye !\n"); system("PAUSE"); return 0; 15

執行範例為: Please input a number between 1 to 100 : 123 Invalid number 123 Bye Bye ! Please input a number between 1 to 100 : 100 Valid number 100

/* ch5 t_f1.c */ #include <stdio.h> #include <stdlib.h> int main() { printf(" 10 > 100 ===> %d\n",10 > 100); printf(" 10 < 100 ===> %d\n",10 < 100); printf(" 10 = = 100 ===> %d\n",10 = = 100); printf(" 10 != 100 ===> %d\n",10 != 100); system("PAUSE"); return 0; }

由輸出結果應能得出真假值的確實數值: 10 > 100 ===> 0 10 < 100 ===> 1 10 = = 100 ===> 0 10 != 100 ===> 1

19 /* ch5 t_f2.c */ #include <stdio.h> #include <stdlib.h> int main() { if (1) printf("1 is TRUE.\n"); else printf("1 is FALSE.\n"); if (0) printf("0 is TRUE.\n"); printf("0 is FALSE.\n"); if (14) printf("14 is TRUE.\n"); printf("14 is FALSE.\n"); if (-62) printf("-62 is TRUE.\n"); printf("-62 is FALSE.\n"); system("PAUSE"); return 0; } 19

輸出結果 1 is TRUE. 0 is FALSE. 14 is TRUE. -62 is TRUE.

5.5 邏輯運算子 表5-2 邏輯運算子 運算子 意義 ! 非(NOT) && 且(AND) || 或(OR)

/* ch5 logical1.c */ #include <stdio.h> #include <stdlib.h> int main() { printf("NOT (3 > 5) ===> %d\n", !(3 > 5)); printf("(3 > 5) OR (10 > 6) ===> %d\n", (3 > 5) || (10 > 6)); printf("(3 > 5) AND (10 > 6) ===> %d\n", (3 > 5) && (10 > 6)); printf("(3 > 5) AND (10 > 6) OR 10 ===> %d\n", (3 > 5) && (10 > 6) || 10); printf("(5 > 3) OR (10 > 6) AND 0 ===> %d\n", (5 > 3) || (10 > 6) && 0); system("PAUSE"); return 0; }

輸出的結果是這樣的: NOT (3 > 5) ===> 1 (3 > 5) OR (10 > 6) ===> 1 (3 > 5) AND (10 > 6) ===> 0 (3 > 5) AND (10 > 6) OR 10 ===> 1 (5 > 3) OR (10 > 6) AND 0 ===> 1

前面三條式子沒有問題。最後兩個運算式則要考慮和優先順序高低的影響: (3 > 5) AND (10 > 6) OR 10 =>((3 > 5) AND (10 > 6 )) OR 10 =>(False AND True) OR True => False OR True => True (5 > 3) OR (10 > 6) AND 0 =>(5 > 3 )OR((10 > 6) AND 0) =>True OR (True AND False) =>True OR False =>True

#include <stdio.h> #include <stdlib.h> int main() { /* ch5 logical2.c */ #include <stdio.h> #include <stdlib.h> int main() { int num; printf("Please input a number between 1 to 100 : "); scanf("%d", &num); if ((num >= 1) && (num <= 100)) printf("Valid number %d !\n", num); else printf("Invalid number %d.\n", num); printf("Bye Bye !\n"); system("PAUSE"); return 0; } 25

執行結果 Please input a number between 1 to 100 : 114 Invalid number 114. Bye Bye ! Please input a number between 1 to 100 : 1 Valid number 1 ! Please input a number between 1 to 100 : -5060 Invalid number -5060.

#include <stdio.h> #include <stdlib.h> int main() { /* ch5 if_else.c */ #include <stdio.h> #include <stdlib.h> int main() { char ch; printf("Play again ? [Y/y] "); scanf("%c", &ch); if ((ch = = 'y') || (ch = = 'Y')) { printf("Play again !\n") printf("I like this game...\n"); } else{ printf("Exit the game !\n"); printf("I do'nt like this game.\n"); printf("Test over !\n"); system("PAUSE"); return 0; 27

執行結果如下: Play again ? [Y/y] y Play again ! I like this game... Test over !

#include <stdio.h> #include <stdlib.h> int main() { /* ch5 logical3.c */ #include <stdio.h> #include <stdlib.h> int main() { int num; printf("Input a number : "); scanf("%d", &num); if((num != 0) && ! (24 % num)) printf("Number %d is a factor of 24.\n", num); else printf("Number %d is not a factor of 24.\n", num); system("PAUSE"); return 0; } 29

程式logical3.c的執行結果如下: Input a number : 10 Number 10 is not a factor of 24. Input a number : 0 Number 0 is not a factor of 24. Input a number : 6 Number 6 is a factor of 24.

/* ch5 cond.c */ #include <stdio.h> #include <stdlib.h> int main() { int x,y; int abs, max; int year; printf("\nInput x : "); scanf("%d", &x); abs = (x >= 0) ? x : -x; printf("|x| = %d\n", abs);

scanf("%d", &y); abs = (y >= 0) ? y : -y; printf("|y| = %d\n", abs); max = (x > y) ? x : y; printf("\nMaximum value of %d and %d is %d.\n", x, y, max); printf("\nHow old are you ? "); scanf("%d", &year); printf(" You are %d year%sold.\n",year,(year > 1) ? "s " : " "); system("PAUSE"); return 0; }

執行結果如下: Input x : -14 |x| = 14 Input y : -62 |y| = 62 Maximum value of -14 and -62 is -14. How old are you ? 23 You are 23 years old.

34

/* ch5 else_if.c */ #include <stdio.h> #include <stdlib.h> int main() { char grade; int score; printf("What's your score ? "); scanf("%d", &score); if(score > 100 || score < 0) printf("It's impossible !\n"); else if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else printf("You are down !\n"); if( score >= 60 && score <=100) printf("Score %d ===> %c\n", score, grade); system("PAUSE"); return 0; } 35

執行情形 What's your score ? 114 It's impossible ! What's your score ? 91 Score 91 ===> A What's your score ? 14 You are down !

/* ch5 switch1.c */ #include <stdio.h> #include <stdlib.h> int main() { char grade; printf("What's your score grade (A-E) ? "); scanf("%c", &grade); if ((grade >= 'A') && (grade <= 'Z')) grade = 'a' + (grade - 'A');

switch (grade){ case 'a' : printf("Score 90 to 100.\n"); break; case 'b' : printf("Score 80 to 89.\n"); case 'c' : printf("Score 70 to 79.\n"); case 'd' : printf("Score 60 to 69.\n"); case 'e' : printf("Score under 60.\n"); default : printf("Wrong grade !\n"); } system("PAUSE"); return 0;

程式中的測試運算式為grade,它是char型態的變數,我們還要注意到,標記採用的形式均為字元常數,最後也有default:標記。 執行結果: What's your score grade (A-E) ? A Score 90 to 100. What's your score grade (A-E) ? d Score 60 to 69. What's your score grade (A-E) ? e Score under 60. What's your score grade (A-E) ? y Wrong grade !

40 /* ch5 switch2.c */ #include <stdio.h> #include <stdlib.h> int main() { char grade; printf("What's your score grade (A-E) ? "); scanf("%c", &grade); switch (grade){ case 'A' : case 'a' : printf("Score 90 to 100.\n"); case 'B' : case 'b' : printf("Score 80 to 89.\n"); case 'C' : case 'c' : printf("Score 70 to 79.\n"); case 'D' : case 'd' : printf("Score 60 to 69.\n"); case 'E' : case 'e' : printf("Score under 60.\n"); default : printf("Wrong grade !\n"); } system("PAUSE"); return 0; 40

What's your score grade (A-E) ? B Score 80 to 89. Score 70 to 79. Score 60 to 69. Score under 60. Wrong grade ! What's your score grade (A-E) ? d

/* ch5 goto1.c */ #include <stdio.h> #include <stdlib.h> #include <conio.h> int main() { int left, right; int mid; char echo; printf("Choose a number (1-100) !\n"); printf(" And I will guess it.\n"); left = 1; right = 100;

43 loop : if (left > right){ printf("You cheat me !\n"); goto quit; } mid = (left + right) / 2; again : printf("\nYour number is %d.\n", mid); printf("match(m), greater(g), or smaller(s) ? "); scanf("%c", &echo); switch (echo){ case 'M' : case 'm' : printf("I just know it !\n"); case 'G' : case 'g' : right = mid - 1; goto loop; case 'S' : case 's' : left = mid + 1; default : goto again; quit : getch(); system("PAUSE"); return 0; 43

程式中以goto敘述做出許多控制效果,像是迴圈(loop)、跳離(quit)、中斷(break)等等,事實上這些效果都可經由C語言的控制敘述來完成;譬如上一節介紹的break敘述,還有下一章將要討論的while與for等迴圈結構。

Choose a number (1-100) ! And I will guess it. Your number is 50. match(m), greater(g), or smaller(s) ? s Your number is 75. match(m), greater(g), or smaller(s) ? Your number is 88. match(m), greater(g), or smaller(s) ? g Your number is 81.

Your number is 84. match(m), greater(g), or smaller(s) ? match(m), greater(g), or smaller(s) ? s Your number is 86. match(m), greater(g), or smaller(s) ? g Your number is 85. match(m), greater(g), or smaller(s) ? m I just know it !

/* ch5 goto2.c */ #include <stdio.h> #include <stdlib.h> #include <conio.h> int main() { int left = 1, right = 100; int mid; char echo; printf("Choose a number (1-100) !\n"); printf(" And I will guess it.\n"); loop : if (left > right){ printf("\nYou cheat me !\n"); goto quit; } mid = (left +right) / 2; again :

printf("\n\nYour number is %d.\n", mid); printf("Match, Greater, or Smaller ? "); echo = getche(); switch (echo){ case 'M' : case 'm' : printf("\nI just know it !\n"); goto quit; case 'G' : case 'g' : right = mid - 1; goto loop; case 'S' : case 's' : left = mid + 1; default : goto again; } quit : getche(); system("PAUSE"); return 0; 48

執行結果 49 Choose a number (1-100) ! And I will guess it. Your number is 50. Match, Greater, or Smaller ? s Your number is 75. Your number is 88. Match, Greater, or Smaller ? g Your number is 81. Your number is 84. Your number is 86. Your number is 85. You cheat me ! 49

/* ch5 goto3.c */ #include <stdio.h> #include <stdlib.h> int main() { int left, right; int mid; char echo; printf("Choose a number (1-100) !\n"); printf(" And I will guess it.\n"); left = 1; right = 100; while (left <= right) {

printf("\nYour number is %d.\n", mid); mid = (left + right) / 2; printf("\nYour number is %d.\n", mid); printf("Match, Greater, or Smaller ? "); scanf("%c",&echo); while(getchar() != '\n') ; if(echo == 'M' || echo == 'm') { printf("I just know it !\n"); break; } switch (echo){ case 'G' : case 'g' : right = mid - 1; case 'S' : case 's' : left = mid + 1; if(echo != 'M' && echo != 'm') 51

執行結果如下: 52 Choose a number (1-100) ! And I will guess it. Your number is 50. Match, Greater, or Smaller ? s Your number is 75. Your number is 88. Match,Greater, or Smaller ? g Your number is 81. Your number is 84. Match,Greater, or Smaller ? s Your number is 86. Match, Greater, or Smaller ? g Your number is 85. Match, Greater, or Smaller ? m I just know it ! 52