A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming.

Slides:



Advertisements
Similar presentations
ICS103: Programming in C 4: Selection Structures Muhamed F. Mudawar.
Advertisements

1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Chapter 4 Selection Structures: if and switch Statements Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering.
1 ICS103 Programming in C Ch4: Selection Structures.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS
Chapter 4 Selection Structures: if and switch Statements Instructor: Alkar / Demirer.
Control Structures 4 Control structures control the flow of execution of a program 4 The categories of control structures are: –Sequence –Selection –Repetition.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Lab 6 rOperators l Relational Operators l Equality Operators l Logical Operators rIf statement l One Alternative l With Compound Statement l Nested If.
1 TDBA66, VT-03, Lecture - Ch. 4 Control structures Conditions (expr1 op expr2 op expr3..) Choise (if statements) Repetition (loops) see Chap. 5.
CS 201 Selection Structures (2) and Repetition
1 CS 201 Selection Structures (1) Debzani Deb. 2 Error in slide: scanf Function scanf(“%lf”, &miles); function name function arguments format string variable.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
C++ for Engineers and Scientists Third Edition
1 ICS103 Programming in C Lecture 6: Selection Structures.
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
Selection. Structured Components There are three basic constructs that can be used to build programs Sequence One statement follows another. Selection.
Chapter 4 Selection Structures: if and switch Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Programming Logic and Design Sixth Edition
Conditional Statement
CPS 125: Digital Computation and Programming Selection Structures: if and switch Statements.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4 Selection Structures: if and switch Statements Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
UniMAP Sem II-09/10EKT120: Computer Programming1 Week 3 – Selection Structures.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CPS120: Introduction to Computer Science Decision Making in Programs.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Selection Structures: if and switch Statements Problem Solving,
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Flow of Control Part 1: Selection
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Chapter 05 (Part III) Control Statements: Part II.
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
PEG200/Saidatul Rahah 1.  Selection Criteria › if..else statement › relational operators › logical operators  The if-then-else Statement  Nested if.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Department of CSE Control Structures: Selection.
Week 4 Program Control Structure
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.
CPS120: Introduction to Computer Science Decision Making in Programs.
Control Statements: Part1  if, if…else, switch 1.
Chapter 4 Selection Structures: if and switch Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville.
Making Decisions in c. 1.if statement Imagine that you could translate a statement such as “If it is not raining, then I will go swimming” into the C.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
CHAPTER 5: SELECTION STRUCTURES: if and switch STATEMENTS Prepared By: Pn. Nik Maria Nik Mahamood Reference: Hanly, Koffman, C Problem Solving and Program.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Chapter 4 : Selection Structures: if and switch statement By Suraya Alias.
THE DECISIONS CONTROL STRUCTURE! CHAPTER 2. Transfer of control statement: o The statement of computer program are executed one after the other in the.
Lesson #4 Logical Operators and Selection Statements.
Lesson #4 Logical Operators and Selection Statements.
CHAPTER 5: SELECTION STRUCTURES: if and switch STATEMENTS
The if…else Selection Statement
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Decisions Chapter 4.
Chapter 4 (Conditional Statements)
CHAPTER 5: SELECTION STRUCTURES: if and switch STATEMENTS
Selection Structures: if and switch Statements
CSC215 Lecture Control Flow.
Week 3 – Program Control Structure
Chapter 4: Selection Structures: if and switch Statements
CSC215 Lecture Control Flow.
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming Errors

A. Abhari CPS1252 Control Structures Using for control the flow of the execution in a program or function. They are a combination of the individual instructions into a single logical unit with one entry point and one exit point. Three kinds of control instructions are: Sequence Selection Repetition

A. Abhari CPS1253 Control Structures Sequence flow: A compound statement is used to specify sequential flow { statement 1; statement 2; ….. Control flow statement n; } A function body consist of a single compound statement

A. Abhari CPS1254 Conditions An expression that is either false (represented by 0) or true (usually represented by 1) For example : rest_heart_rate > 75 Conditions establish criteria for executing or skipping a group of statements

A. Abhari CPS1255 Relational and Equality Operators variable relational-operator variable/constant variable equality-operator variable/constant Examples : x <= 0 salary < MIN_SALARY x > Y dependents >= 5 item == 3 (It is not the assignment operator ‘=‘ ) num != SENTINEL

A. Abhari CPS1256 Logical Operators Three logical operators && (and), || (or) and ! (not) can be used to form logical expressions: Examples: n >= 0 && n <= 100 0<= n && n <= 100 ! ( 0 <= n && n <= 100 ) 0 > n || n > 100

A. Abhari CPS1257 Logical operators && (and) op1 op2 op1 && op T T T T F F F T F F F F

A. Abhari CPS1258 Logical operators || (or) op1 op2 op1 || op T T T T F T F T T F F F

A. Abhari CPS1259 Logical operators ! (not) op1 ! op T F F T The result of logical expression is always 0 or 1. C accepts any nonzero value as a representation of true

A. Abhari CPS12510 Operator Precedence function calls highest ! + - & (unary operators) * / % + - = > == != && || = lowest

A. Abhari CPS12511 Operator Precedence -2 – 1 * 2 => -4 ( 2 3 ) && 2 > 1  1 (true) 2 3 && 2 >1 =>1(true) !0 || ( >= 3.0 – 2.0) => 1(true) !(0 || ( >= 3.0 – 2.0)) => 0(false)

A. Abhari CPS12512 Short-Circuit Evaluation For && and || C uses the short-circuit evaluation. It means stopping the evaluation of the logical expression as soon as its value can be determined Examples: ! 1 && ( 5+ 7 >= 3 ) 1 || ( 6+ 4 < 7 )

A. Abhari CPS12513 Examples Range checking x > 2 && y > 2 but not using x && y > 2 Character comparison ‘9’ >= ‘0’ 1(true) ‘Z’ == ‘z’ 0(false) ‘a’ <= ch && ch <=‘z’ true if ch is a lowercase letter ‘a’ <= ‘A’ system dependent

A. Abhari CPS12514 Logical Assignment Example 1: int age, senior_citizen; scanf(“%d”, &age); senior_citizen = (age >= 65); Example 2: int even, n; scanf(“%d”, &n); even = ( n %2 == 0 )

A. Abhari CPS12515 Complementing a Condition The condition item == sent complemented as !(item == sent ) or item != sent DeMorgan’s Theorem age > 25 && ( s == ‘S’ || s == ‘D’) complemented as age <=25 || ( s != ‘S’ && s != ‘D’)

A. Abhari CPS12516 THE if STATEMENT if ( mark > 50 ) printf ( “pass”); else printf(“fail”); Display “pass” Display “fail” mark> 50 TF

A. Abhari CPS12517 THE if STATEMENT if ( mark == 50 ) mark = mark + 1; if ( mark > 50 ) printf ( “pass”); else printf(“fail”); mark==50 mark = mark + 1 F T

A. Abhari CPS12518 THE if STATEMENT if statement (One Alternative) if ( condition ) statement T ; if statement ( Two Alternatives) if ( condition ) statement T ; else statement F ;

A. Abhari CPS12519 if ( mark == 50 ) mark = mark + 1; if ( mark > 50 ) printf ( “pass”); else printf(“fail”); if ( mark >= 90 ) printf (“outstanding\n” ); printf (“Enter another mark”); It is not depending on the last if statement

A. Abhari CPS12520 Errors, when using if statement if mark == 100 printf (“highest mark \n” ); if (mark = 100) printf (“highest mark \n” ); if (mark == 100); printf (“highest mark \n” );

A. Abhari CPS12521 if statements with compound statements Computing the increase in fruit fly population if ( pop_today > pop_yesterday ) { growth = pop_today – pop_yesterday; growth_pct = * growth /pop_yesterday; printf ( “ The growth percentage is %.2f \n”, growth_pct); }

A. Abhari CPS12522 if statements with compound statements Keeping records of safety rating of the fleet cars if (ctri <= MAX_SAFE_CTRI) { printf(“Car #%d: safe\n”, auto_id); safe = safe + 1; } What is the result when omitting this brace else { printf(“Car #%d: unsafe\n”, auto_id); unsafe = unsafe + 1; }

A. Abhari CPS12523 if statements with compound statements if (condition) { statements; } else { statements; }

A. Abhari CPS12524 Tracing an if statement if (x > y) { /* Switch x and y */ temp = x; /* Store old x in temp */ x = y; /* Store old y in x */ y = temp; } Stat. x y temp ? If (x>y) { temp = x; 12.5 x = y; 5.0 y = temp; 12.5

A. Abhari CPS12525 Nested if Statements if (expression1) statement1; else if (expression2) statement2; else statement3;

A. Abhari CPS12526 Nested if statements if (x > 0) num_pos = num_pos + 1; else if (x < 0) num_neg = num_neg + 1; else num_zero = num_zero + 1; Sequence of if statements: (It is less readable and less efficient because all conditions are always tested) if (x > 0) num_pos = num_pos + 1; if (x < 0) num_neg = num_neg + 1; if (x == 0) num_zero = num_zero + 1;

A. Abhari CPS12527 Multiple-Alternative Decision Form of Nested if Can be used instead of nested if, when each false task (except for the last) is followed by if-then-else statement The conditions are evaluated in sequence until a true condition is reached Upon a true condition the statements in the else part are skipped The words else and if the next condition appear on the same line if (x > 0) num_pos = num_pos + 1; else if (x < 0) num_neg = num_neg + 1; else /* x equal to 0 */ num_zero = num_zero + 1;

In multiple-alternative decision, the order of conditions affects the result. For example by placing if (salary <= ) at the beginning of the following if statement the result for the $40,000 salary input would be wrong: if (salary < 0.0) tax = -1.0; else if (salary < )/* first range */ tax = 0.15 * salary; else if (salary < )/* second range*/ tax = (salary ) * ; else if (salary < )/* third range*/ tax = (salary ) * ; else if (salary < )/* fourth range*/ tax = (salary ) * ; else if (salary <= )/* fifth range*/ tax = (salary ) * ; else tax = -1.0;

A. Abhari CPS12529 Multiple variables nested if if (marital_status == ‘ S ’ ) if (gender == ‘ M ’ ) if (age >= 18) if (age <= 26) printf( “ All criteria are met. \n ” ); Is equal to: if (marital_status == ‘ S ’ && gender == ‘ M ’ && age >= 18 && age <= 26 ) printf( “ All criteria are met. \n ” );

A. Abhari CPS12530 Always C associates an else with the most recent if if (road_status == ‘S’) if (temp > 0) { printf(“Wet roads ahead\n”); printf(“Stopping time doubled\n”); } else { printf(“Icy roads ahead\n”); printf(“Stopping time quadrupled\n”); } else printf(“Drive carefully\n”);

A. Abhari CPS12531 By placing braces, else can be associated to the further if, For example: if (road_status == ‘S’){ if (temp > 0) { printf(“Wet roads ahead\n”); printf(“Stopping time doubled\n”); } } else printf(“Drive carefully\n”);

Case study: Computing Compass Bearing /* * Transforms a compass heading to a compass bearing using this table: * *HEADING *IN DEGREES BEARING COMPUTATION * * north (heading) east * south ( heading) east * south (heading ) west * north ( heading) west */ #include void instruct(void); int main(void) { double heading; /* Input - compass heading in degrees */ instruct(); /* Get compass heading. */ printf("Enter a compass heading> "); scanf("%lf", &heading);

A. Abhari CPS12533 /* Display equivalent compass bearing. */ if (heading < 0.0) printf("Error -- negative heading (%.1f)\n", heading); else if (heading < 90.0) printf("The bearing is north %.1f degrees east\n", heading); else if (heading < 180.0) printf("The bearing is south %.1f degrees east\n", heading); else if (heading < 270.0) printf("The bearing is south %.1f degrees west\n", heading ); else if (heading <= 360.0) printf("The bearing is north %.1f degrees west\n", heading); else printf("Error--heading > 360 (%.1f)\n", heading); return (0); }

A. Abhari CPS12534 /* * Display program purpose and user instructions */ void instruct(void) { printf("To convert a compass heading to a "); printf("compass bearing,\nenter a value "); printf("between 0.0 and at the prompt.\n"); } The results of bearing computation in the printf statements can be stored into output variable bearing. In that case it can be used later. For testing the program the boundary values of 0, 90, 180, 270, 360 and also an out of range value can be used as the program input.

A. Abhari CPS12535 The switch Statement The switch statement is useful when selection is based on the value of single value or of a simple expression (called controlling expression). This value of controlling expression should be of type int or char, but not of type double The controlling expression is evaluated and compared to each of the case labels in the label sets until a match is found When this match is found the statements following the case label are executed until break statement then the rest of switch statement is skipped. If no case label value matches the controlling expression, the entire switch statement body is skipped unless it contains a default label. In that case the statement following the default label are executed.

A. Abhari CPS12536 Syntax of the switch statement switch ( integer or char expression ) { caseconst1: statements 1 break; caseconst2: statements 2; break; …… default: statements d; break; } Controlling Expression Label Set1

Example of a switch Statement with Type char Case Labels switch (class) { case 'B': case 'b': printf("Battleship\n"); break; case 'C': case 'c': printf("Cruiser\n"); break; case 'D': case 'd': printf("Destroyer\n"); break; case 'F': case 'f': printf("Frigate\n"); break; default: printf("Unknown ship class %c\n", class); }

A. Abhari CPS12538 Example of a switch Statement with Type int Case Labels switch (watts) { case 25: life = 2500; break; what is the result of omission of this break ? case 40: case 60: life = 1000; break; case 75: case 100: life = 750; break; default: life =0; } what is the result of omission of this brace ? What is the equivalent nested if statement for this switch statement ?

A. Abhari CPS12539 Common Programming Errors Using 0 < x < 4 instead of (0< x && x<4) in the if statements Confusing the operator = with == Forgetting parentheses in the if condition Missing braces in compound statements of the if statements Confusion when matching else with related if in the nested if statements Missing break and default in the switch statement