Chapter 4 C Program Control

Similar documents
4.8 Thedo while Repetition Statement Thedo while repetition statement

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

JavaScript: Control Statements I

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Chemistry I -- Final Exam

SHAU KEI WAN GOVERNMENT SECONDARY SCHOOL

Lecture 1 Introduction to Java

LC Paper No. PWSC269/15-16(01)

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Data Structures Chapter 4 Linked Lists

Two-way selection. Branching and Looping

Installation Guide 2-Port HD Cable KVM Switch with Audio GCS62HU PART NO. M1130

Sources: On the Web: Slides will be available on:

Market Access To Taiwan. By Jane Peng TÜV Rheinland Taiwan Ltd.

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Machine Translation for Academic Purposes

Chapter One Introduction to Programming

促 進 市 場 競 爭 加 強 保 障 消 費 者

EW-7438RPn Mini 安 裝 指 南 / v1.0

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

EFL Business Writing with Task-based Learning Approach: A Case Study of Student Strategies to Overcome Difficulties

The HKICPA Accounting and Business Management Case Competition Secondary School Group (Level 1)

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

余 雋 禧 仇 慧 琳 宣 教 士 夫 婦

Wi-Drive User Guide. (for use with Amazon s Kindle Fire) Document No. 480WID4KF-001.A01 Kingston Wi-Drive Page 1 of 15

How To Be The Legend In Hong Kong

UEE1302 (1102) F10 Introduction to Computers and Programming

Senem Kumova Metin & Ilker Korkmaz 1

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Case Study of a New Generation Call Center

REGULATIONS FOR THE DEGREE OF BACHELOR OF ARTS IN ARCHITECTURAL STUDIES (BA[ArchStud])

In this Chapter you ll learn:

广 东 培 正 学 院 2016 年 本 科 插 班 生 专 业 课 考 试 大 纲 基 础 英 语 课 程 考 试 大 纲

Installation Guide 2/4-Port DVI KVMP Switch with Cables

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

CS 241 Data Organization Coding Standards

China M&A goes global

Installation Guide Universal Wireless-n Adapter GWU627 PART NO. M1161

Visual Logic Instructions and Assignments

Moving from CS 61A Scheme to CS 61B Java

Flowchart Techniques

Protel DXP 2004 Schematic 開 始 所 有 程 式 Altium DXP 2004

While Loop. 6. Iteration

Kingston MobileLite Wireless. (ßeta Release) Document No. 480WD+MLW.ß01 Kingston MobileLite Wireless (ßeta) Page 1 of 12

Should lidocaine spray be used to ease nasogastric tube insertion? A double-blind, randomised controlled trial

Writing Control Structures

Microsoft SQL Server PDW 新世代 MPP 資料倉儲解決方案

LOOPS CHAPTER CHAPTER GOALS

VB.NET Programming Fundamentals

國 立 中 山 大 學 企 業 管 理 學 系 碩 士 論 文

Lecture 2 Notes: Flow of Control

Closure of the Landside Impermeable Wall (Ice Wall) Commencement

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Romeo and Juliet 罗 密 欧 与 茱 丽 叶

Tender Document for Procurement of the Security Screening Equipment at MIA (RFQ-151)

The While Loop. Objectives. Textbook. WHILE Loops

Conditionals (with solutions)

Chapter 9. Subprograms

Customers' Trust and Purchase Intention towards. Taobao's Alipay (China online marketplace)

歐 洲 難 民 潮 對 經 濟 的 影 響 The Economic Implications of Europe s Refugee Influx

Exploring the Relationship Between Critical Thinking and Active. Participation in Online Discussions and Essays

Data Structures Chapter 3 Stacks and Queues

weekly Our mission Our history Our footprint Our award-winning content 2015 Media Kit asian northwest

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Informatica e Sistemi in Tempo Reale

6. Control Structures

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Validity and reliability of the Chinese version of the Insulin Treatment Appraisal Scale among primary care patients in Hong Kong

The Government of The Hong Kong Special Administrative Region Procedures for Importation and Registration of Motor Vehicles & Motor Cycles

Spectrum: Studies in Language, Literature, Translation, and Interpretation, Vol. 2, 85-92

轎 車 機 場 接 送 及 往 返 澳 門 與 香 港 機 場 接 送 服 務 禮 遇 ( 推 廣 ) 之 條 款 及 細 則 :

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Unit 6. Loop statements

新 媒 體 傳 播 策 略 應 用 學 習 課 程

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Variables, Constants, and Data Types

A SERVER-LESS ARCHITECTURE FOR BUILDING SCALABLE, RELIABLE, AND COST-EFFECTIVE VIDEO-ON-DEMAND SYSTEMS

Introduction to Python

Iteration CHAPTER 6. Topic Summary

Notes on Algorithms, Pseudocode, and Flowcharts

(Chapter 218) APPLICATION FOR A LICENCE BY A BODY CORPORATE

2 SYSTEM DESCRIPTION TECHNIQUES

Wi-Fi SD. Sky Share S10 User Manual

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

2010/9/19. Binary number system. Binary numbers. Outline. Binary to decimal

1 Description of The Simpletron

So far we have considered only numeric processing, i.e. processing of numeric data represented

Procedures to file a request to the JPO for Patent Prosecution Highway Pilot Program between the JPO and the HPO

Q&As: Microsoft Excel 2013: Chapter 2

Pseudo code Tutorial and Exercises Teacher s Version

Ex. Either we must get in line early to buy the tickets, or only scalpers INDEPENDENT CLAUSE 1 INDEPENDENT tickets will be available.

Problem Solving Basics and Computer Programming

How To Write Portable Programs In C

Decision Logic: if, if else, switch, Boolean conditions and variables

Chapter 7: Software Development Stages Test your knowledge - answers

Transcription:

Chapter 4 C Program Control 1 Outline 4.1 Introduction 4.2 The Essentials of Repetition 4.3 Counter-Controlled Repetition 4.4 The for Repetition Statement 4.5 The for Statement: Notes and Observations 4.6 Examples Using the for Statement 4.7 The switch Multiple-Selection Statement 4.8 The do while Repetition Statement 4.9 The break and continue Statements 4.10 Logical Operators 4.11 Confusing Equality (==) and Assignment (=) Operators 4.12 Structured Programming Summary Objectives 2 In this chapter, you will learn: To be able to use thefor anddo while repetition statements. To understand multiple selection using the switch selection statement. To be able to use thebreak andcontinue program control statements To be able to use the logical operators. 1

3 This chapter introduces 4.1 Introduction Additional repetition control structures for Do while switch multiple selection statement break statement Used for exiting immediately and rapidly from certain control structures continue statement Used for skipping the remainder of the body of a repetition structure and proceeding with the next iteration of the loop 4 4.2 The Essentials of Repetition Loop ( 迴圈 ) Group of instructions computer executes repeatedly while some condition remainstrue Counter-controlled repetition Definite repetition: know how many times loop will execute Control variable used to count repetitions Sentinel-controlled repetition Indefinite repetition Used when number of repetitions not known Sentinel value indicates "end of data" 2

4.3 Essentials of Counter-Controlled Repetition Counter-controlled repetition requires The name of a control variable (or loop counter) The initial value of the control variable An increment (or decrement) by which the control variable is modified each time through the loop A condition that tests for the final value of the control variable (i.e., whether looping should continue) int i = 0; 5 while (i <= 10) { i = i + 1; } 4.3 Essentials of Counter-Controlled Repetition Example: int counter = 1; // initialization while ( counter <= 10 ) { // repetition condition printf( "%d\n", counter ); ++counter; // increment } The statement int counter = 1; Namescounter Defines it to be an integer Reserves space for it in memory Sets it to an initial value of1 6 3

The Flow Chart ofwhile 7 int counter = 1; // initialization while ( counter <= 10 ) { // repetition condition printf( "%d\n", counter ); ++counter; // increment } counter = 1 counter <= 10? no ++counter yes printf exit loop 1 /* Fig. 4.1: fig04_01.c 2 Counter-controlled repetition */ 3 #include <stdio.h> 4 5 /* function main begins program execution */ 6 int main() 7 { 8 int counter = 1; /* initialization */ 9 5 10 while ( counter <= 10 ) { /* repetition condition 6 */ 11 printf ( "%d\n", counter ); /* display counter */ 7 12 ++counter; /* increment */ 8 13 } /* end while */ 9 14 10 15 return 0; /* indicate program ended successfully */ 16 17 } /* end function main */ 1 2 3 4 4

4.3 Essentials of Counter-Controlled Repetition Condensed code C Programmers would make the program more concise 9 Int counter = 0; while ( ++counter <= 10 ) printf( %d\n, counter ); counter = 0 ++counter counter <= 10? yes no printf exit loop 10 Condensed Code (II) Int counter = 0; while (counter++ <= 9 ) printf( %d\n, counter ); counter = 0 printf counter <= 9? yes counter++ no counter++ exit loop 5

11 4.4 Thefor Repetition Statement counter = 1 counter <= 10? no ++counter yes Loop body exit loop 12 4.4 Thefor Repetition Statement Format when usingfor loops for ( initialization; loopcontinuationtest; increment ) statement Example: for( int counter = 1; counter <= 10; counter++ ) printf( "%d\n", counter ); Prints the integers from one to ten initialization Loop test no No semicolon (;) after last expression increment yes statement exit loop 6

13 Initialization and increment Can be comma-separated lists Example: for (int i = 0, j = 0; j + i <= 10; j++, i++) printf( "%d\n", j + i ); 14 4.4 Thefor Repetition Statement For loops can usually be rewritten as while loops: initialization; while ( loopcontinuationtest ){ statement; increment; } for ( int counter = 1; counter <= 10; counter++ ) printf( "%d\n", counter ); counter = 1; while ( counter <= 10 ) { printf( "%d\n", counter ); counter++; } 7

1 /* Fig. 4.2: fig04_02.c 2 Counter-controlled repetition with the for statement */ 3 #include <stdio.h> 4 5 /* function main begins program execution */ 6 int main() 7 { 8 int counter; /* define counter */ 9 10 /* initialization, repetition condition, and increment 11 are all included in the for statement header. */ 12 for ( counter = 1; counter <= 10; counter++ ) { 13 printf( "%d\n", counter ); 14 } /* end for */ 15 16 return 0; /* indicate program ended successfully */ 17 18 } /* end function main */ 16 Flowchart Establish initial value of control variable counter = 1 Determine if final value of control variable has been reached counter <= 10 false true printf( "%d", counter ); Body of loop (this may be many statements) counter++ Increment the control variable 8

17 練習一 設計一段程式, 要求使用者輸入一個整數 N, 輸出 1+2+3+ +N 的結果 提示 : 使用 for 敘述 1 /* Fig. 4.5: fig04_05.c 2 Summation with for */ 3 #include <stdio.h> 4 5 /* function main begins program execution */ Program Output 6 int main() Sum is 2550 7 { 8 int sum = 0; /* initialize sum */ 9 int number; /* number to be added to sum */ 10 11 for ( number = 2; number <= 100; number += 2 ) { 12 sum += number; /* add number to sum */ 13 } /* end for */ 14 15 printf( "Sum is %d\n", sum ); /* output sum */ 16 17 return 0; /* indicate program ended successfully */ 18 19 } /* end function main */ 9

19 練習二 設計一段程式, 要求使用者輸入一個整數 N, 輸出所有介於 1 與 N 間 ( 不大於 N) 的所有除以 6 餘 4 的數字, 並輸出這樣的數字有多少個 提示 : 使用 for 敘述 20 Practice 寫一個 C 語言程式, 讓使用者輸入一個介於 1 至 100 間的奇數 使用一個 for 或 while 迴圈計算並輸出下列結果 (1) 從 1 至此數字的全部奇數總和 (2) 從 1 至此數字總共有幾個奇數 執行範例 Input an odd number: 15 1 + 3 +... 15 = 64 There are total 8 odd numbers from 1 to 15. 10

1 /* Fig. 4.6: fig04_06.c 2 Calculating compound interest */ 3 #include <stdio.h> 4 #include <math.h> 5 6 /* function main begins program execution */ 7 int main() 8 { 9 double amount; /* amount on deposit */ 10 double principal = 1000.0; /* starting principal */ 11 double rate =.05; /* interest rate */ 12 int year; /* year counter */ 13 14 /* output table column head */ 15 printf( "%4s%21s\n", "Year", "Amount on deposit" ); fig04_06.c (Part 1 of 2) 16 17 /* calculate amount on deposit for each of ten years */ 18 for ( year = 1; year <= 10; year++ ) { 19 20 /* calculate new amount for specified year */ 21 amount = principal * pow( 1.0 + rate, year ); 22 23 /* output one table row */ = (1+rate) year 26 24 printf( "%4d%21.2f\n", year, amount ); 25 } /* end for */ fig04_06.c (Part 2 of 2) Program Output 27 return 0; /* indicate program ended successfully Year */ 28 29 } /* end function main */ Amount on deposit 1 1050.00 2 1102.50 3 1157.63 4 1215.51 5 1276.28 6 1340.10 7 1407.10 8 1477.46 9 1551.33 10 1628.89 11

練習三 23 設計一段程式, 要求使用者輸入一個整數 N, 輸出下列運算的結果 : 1 1 1 1 2 1 1 2 N 提示 : 使用兩層的 for 敘述 Thefor Statement : Notes and Observations Arithmetic expressions Initialization, loop-continuation, and increment can contain arithmetic expressions. Ifxequals2andyequals 10 for ( j = x; j <= 4 * x * y; j += y / x ) 24 is equivalent to for ( j = 2; j <= 80; j += 5 ) 12

25 Notes about thefor statement Increment may be negative (decrement) for ( int counter = 10; counter > 0; counter-- ) printf( "%d\n", counter ); 10 9 8 7 6 5 4 3 2 1 26 Notes about thefor statement If the loop continuation condition is initially false The body of thefor statement is not performed Control proceeds with the next statement after thefor statement for ( int counter = 10; counter < 0; counter++ ) printf( "%d\n", counter ); Control variable Often printed or used inside for body, but not necessary 13

4.7 Theswitch Multiple-Selection Statement switch Useful when a variable or expression is tested for all the values it can assume and different actions are taken Format Series ofcase labels and an optionaldefault case switch ( value ){ case '1': actions case '2': actions default: actions } break; exits from statement 27 Flowchart of theswitch statement 28 true case a case a action(s) break false true case b case b action(s) break false... true case z case z action(s) break false default action(s) 14

1 /* Fig. 4.7: fig04_07.c 2 Counting letter grades */ 3 #include <stdio.h> 4 5 /* function main begins program execution */ 6 int main() 7 { 8 int grade; /* one grade */ 9 int acount = 0; /* number of As */ 10 int bcount = 0; /* number of Bs */ 11 int ccount = 0; /* number of Cs */ 12 int dcount = 0; /* number of Ds */ 13 int fcount = 0; /* number of Fs */ 14 15 printf( "Enter the letter grades.\n" ); 16 printf( "Enter the EOF character to end input.\n" ); 17 18 /* loop until user types end-of-file key sequence */ 19 while ( ( grade = getchar() )!= EOF ) { fig04_07.c (Part 1 of 3) 20 21 /* determine which grade was input */ fig04_07.c (Part 2 of 22 switch ( grade ) { /* switch nested in while */ 3) 23 24 case 'A': /* grade was uppercase A */ 25 29 case case 'a': 'B': /* or /* lowercase grade wasa uppercase */ B */ 26 30 34 ++acount; case case 'b': 'C': /* /* increment or/* lowercase gradeacount wasb uppercase */ */ C */ 27 31 35 39 break; ++bcount; case /* case 'c': necessary 'D': /* /* increment or/* to lowercase grade exit bcount switch was c */ uppercase */ */ D */ 28 32 36 40 break; 44 ++ccount; case /* case 'd': exit/* 'F': switch /* increment or/* lowercase */ grade ccount wasd uppercase */ */ F */ 33 37 41 45 break; 49 ++dcount; case /* case exit 'f': /* '\n': switch /* increment or/* lowercase */ ignore dcount newlines, f */ */ */ 38 42 46 50 break; 54++fCount; case /* default: exit '\t': /* switch increment /* tabs, /**/ catch */ fcount all other */ characters */ 43 47 51 55 break; case '/* printf( ': exit /* "Incorrect and switch spaces */ letter in input grade */ entered." ); 48 52 56 printf( break; " Enter /* exit a new switch grade.\n" */ ); 53 57 break; /* optional; will exit switch */ 58 } /* end switch */ 59 60 } /* end while */ 61 15

62 /* output summary of results */ 63 printf( "\ntotals for each letter grade are:\n" ); 64 printf( "A: %d\n", acount ); /* display number of A grades */ 65 printf( "B: %d\n", bcount ); /* display number of B grades */ 66 printf( "C: %d\n", ccount ); /* display number of C grades */ 67 printf( "D: %d\n", dcount ); /* display number of D grades */ 68 printf( "F: %d\n", fcount ); /* display number of F grades */ 69 70 return 0; /* indicate program ended successfully */ 71 72 } /* end function main */ fig04_07.c (Part 3 of 3) Enter the letter grades. Enter the EOF character to end input. a b c C A d f C E Incorrect letter grade entered. Enter a new grade. D A 按 Ctrl-Z 會使 getchar() 傳回 EOF b ^Z Program Output Totals for each letter grade are: A: 3 B: 2 C: 3 D: 2 F: 1 16