Topic 5 – Control Structures. CISC 105 – Topic 5 Program Flow Thus far, we have only encountered programs that flow sequentially. The first statement.

Slides:



Advertisements
Similar presentations
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Advertisements

Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Topic 6 – Repetition and Loops. CISC 105 – Topic 6 Program Repetition Repetition refers to the repeats of certain program statements within a program.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
true (any other value but zero) false (zero) expression Statement 2
If Statements Sections 1.25, Control Structures o All code thus far executes every line of code sequentially o We want to be able to repeat,
1 Conditionals In many cases we want our program to make a decision about whether a piece of code should be executed or not, based on the truth of a condition.
1 CS 201 Selection Structures (1) Debzani Deb. 2 Error in slide: scanf Function scanf(“%lf”, &miles); function name function arguments format string variable.
C++ for Engineers and Scientists Third Edition
The switch Statement, DecimalFormat, and Introduction to Looping
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Structural Program Development: If, If-Else Outline.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Java Programming: From The ground Up  Chapter 4 Selection and Decision: if Statements.
Computer Science Department Relational Operators And Decisions.
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.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CMSC 104, Version 8/061L11Relational&LogicalOps.ppt Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
If…else statements. Boolean Expressions Boolean expression - An expression whose value is either true or false true = 1 false = 0 Datatype: boolean.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Decision making statements. Decision making statements are used to skip or to execute a group of statements based on the result of some condition. The.
1 2. Program Construction in Java. 2.4 Selection (decisions)
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
CHAPTER#3 STRUCTURED PROGRAM DEVELOPMENT IN C++ 1 st semester King Saud University College of Applied studies and Community Service Csc 1101.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Bordoloi and Bock CONTROL STRUCTURES: CONDITIONAL CONTROLS.
Java Programming Fifth Edition Chapter 5 Making Decisions.
Week 4 Program Control Structure
Decision Statements, Short- Circuit Evaluation, Errors.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Dr. Sajib Datta Jan 23,  A precedence for each operator ◦ Multiplication and division have a higher precedence than addition and subtraction.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
 2006 Pearson Education, Inc. All rights reserved if…else Double-Selection Statement if – Performs action if condition true if…else – Performs.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Dr. Sajib Datta Sep 3,  A new operator used in C is modulus operator: %  % only used for integers, not floating-point  Gives the integer.
The if…else Selection Statement
Selection (also known as Branching) Jumail Bin Taliba by
Chapter 4: Making Decisions.
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.
Chapter 4: Making Decisions.
Lecture 3- Decision Structures
EGR 2261 Unit 4 Control Structures I: Selection
CSC113: Computer Programming (Theory = 03, Lab = 01)
DKT121: Fundamental of Computer Programming
Chapter 4: Making Decisions.
Structured Program
3 Control Statements:.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Chapter 4: Control Structures I (Selection)
2.6 The if/else Selection Structure
Week 3 – Program Control Structure
Structured Program Development in C++
ICS103: Programming in C 4: Selection Structures
Structural Program Development: If, If-Else
Presentation transcript:

Topic 5 – Control Structures

CISC 105 – Topic 5 Program Flow Thus far, we have only encountered programs that flow sequentially. The first statement in a function is the first statement that is run when that function begins. Control then passes to the next statement, which passes it to the next statement, and so forth.

CISC 105 – Topic 5 Program Flow A function loses control when it ends (as in a function that returns no data) or when it encounters a return statement. However, sometimes we do not wish to have a program’s control flow pass from one statement to the next.

CISC 105 – Topic 5 Program Flow This introduces the concept of a condition. A program executes one statement or another, depending on the value of some condition. Thus, a condition establishes a criteria for executing or skipping a group of statements.

CISC 105 – Topic 5 The if statement In order to use a condition to make a decision about program control flow, C uses an if statement. The if statement first evaluates the specified condition. If the condition is true, the statement immediately following the if statement executes. If the condition is false, the statement immediately following the if statement is skipped.

CISC 105 – Topic 5 The if/else Statement In addition, C supports the use of an else statement. This statement can follow the optional statement (the one that may or may not execute depending on the condition). If there is an else statement, the statement immediately following the else statement will execute if the original condition (in the if statement) is false.

CISC 105 – Topic 5 The if/else Statement Therefore, if there is an else statement, either the statement immediately following the if statement is run (if the condition is true) OR the statement immediately following the else statement is run (if the condition is false).

CISC 105 – Topic 5 The if/else Statement statement1; if (condition) statement2; else statement3; statement4; In this program fragment, statement1 executes. Then, either statement2 or statement3 executes, depending on the condition. Then, statement4 executes. Note that only 3 statements execute.

CISC 105 – Topic 5 Compound Statements Sometimes, we wish to perform more than one thing as the result of an if statement. In this case, we can make use of a compound statement. A compound statement is a group of C language statements that run sequentially. A compound statement is enclosed with curly braces (“{” and “}”), in the same way a function body is.

CISC 105 – Topic 5 Compound Statements When used as the statement immediately following an if or else statement, a compound statement is treated like one statement (all of the statements enclosed by the braces are run, sequentially.)

CISC 105 – Topic 5 Compound Statements statement1; if (condition) { statement2; statement3; } else { statement4; statement5; } statement6; In this program fragment, statement1 executes. Then, either statement2 and statement3 execute or statement4 and statement5 execute, depending on the condition. Then, statement6 executes. Note that only 4 statements execute.

CISC 105 – Topic 5 Cascading if/else Statements statement1; if (condition1) { statement2; statement3; } else if(condition2) { statement4; statement5; } else statement6; statement7; We can also cascade if/else statements. Here, condition1 is first evaluated. If it is true, statements 2 & 3 run and then statement7. If condition1 is false and condition2 is true, statements 4 and 5 run and then statement 7. If both conditions are false, statement 6 runs and then statement 7. Note that if condition1 is true, condition2 is never evaluated!

CISC 105 – Topic 5 Conditions So, now the structure of if/else statements are known. So, how do we write the conditions? When an if statement is encountered, the program will first evaluate the condition in the if statement. Anything that evaluates to a nonzero value is true. Anything that evaluates to zero is false.

CISC 105 – Topic 5 Conditions Thus, an if statement that was written as: would cause statement1 to run if x was equal to any value other than zero. If x was zero, statement1 would be skipped. if (x) statement1;

CISC 105 – Topic 5 Relational and Equality Operators In order to write conditions effectively, C provides a number of relational and equality operators. For these operators, if the condition they specify is true, they evaluate to 1. If the condition they specify is false, they evaluate to 0.

CISC 105 – Topic 5 Operators The following relational and equality operators are used: <less than >greater than <=less than or equal to >=greater than or equal to ==equal to !=not equal to

CISC 105 – Topic 5 Conditions & Operators Some examples of the use of these operators include: x <= 0 number > MAX_NUMBER_ALLOWED male_or_female == ‘M’ num != flag_number y < 12.0 q <= p

CISC 105 – Topic 5 A VERY Common Error An assignment statement evaluates to the value being assigned. For example, x = 6; evaluates to 6. So…what would happen if we wrote if (x = 6) { … } First, 6 would be assigned to x! This overwrites whatever was previously stored in x. Also, x=6 evaluates to 6. As anything nonzero is true, this condition is ALWAYS true. BOTTOM LINE: Remember to use == for conditions!

CISC 105 – Topic 5 Compound Conditions More than one condition can be combined to create a compound condition. A logical operator is used to combine conditions. These include: &&AND ||OR (shift-\)

CISC 105 – Topic 5 Logical AND (&&) The logical AND operator works as follows: Condition 1Condition 2Overall Result TRUE (nonzero) TRUE (1) TRUE (nonzero)FALSE (0) TRUE (nonzero)FALSE (0)

CISC 105 – Topic 5 Logical OR (||) The logical OR operator works as follows: Condition 1Condition 2Overall Result TRUE (nonzero) TRUE (1) TRUE (nonzero)FALSE (0)TRUE (1) FALSE (0)TRUE (nonzero)TRUE (1) FALSE (0)

CISC 105 – Topic 5 Logical NOT (!) The last logical operator is the NOT operator. It behaves as follows: Condition!(Condition) TRUE (nonzero)FALSE (0) TRUE (1)

CISC 105 – Topic 5 Examples Write a condition that is true if both x is greater than and number is equal to 3 OR big_letter is not equal to ‘Q’. (X > && number == 3) || big_letter != ‘Q’

CISC 105 – Topic 5 Examples Write a condition that is true if either x equals 12, y is less than 29.9, letter equals ‘L’ or p does not equal 1. x == 12 || y < 29.9 || letter == ‘L’ || p != 1

CISC 105 – Topic 5 Review of Control Flow Keep in mind that while spacing and indenting are not necessary in conditional statements and their corresponding execution statements, it makes it very easy to see the condition statements (following the if or else statement). Indeed, without this spacing, it is much more difficult to see which statements are conditional and which are not. This is also true when if/else statements are not used. For instance, multiple statements can appear on the same line, spacing need not be consistent, etc…

CISC 105 – Topic 5 Review of Control Flow For example, what is the output of the following program fragment? i = 10; j=9; if (i == 10) { printf(“It’s ten!”); i++; } else if (j < 9) { printf(“Hello from inside.\n”); i++; j--; j = 12;} i--; printf(“i=%d and j=%d”,i,j); It’s ten! i=10 and j=9

CISC 105 – Topic 5 Review of Control Flow How about now? i = 10; j=9; if (i == 10) { printf(“It’s ten!”); i++; } else if (j <= 9) { printf(“Hello from inside.\n” ); i++; j--; j = 12;} i--; printf(“i=%d and j=%d”,i,j); It’s ten! i=10 and j=9

CISC 105 – Topic 5 Review of Control Flow And now? i = 10; j=9; if (i == 10) { printf(“It’s ten!”); i++; } if (j <= 9) { printf(“Hello from inside.\n”); i++; j--; j= 12;} i--; printf(“i=%d and j=%d”,i,j); It’s ten! Hello from inside. i=11 and j=12

CISC 105 – Topic 5 Nested if/else Statements If/else statements can be nested. This means that one if/else statement can appear as the conditional statement of another if/else statement. As an example, suppose we have two variables, raining (which is 1 if it’s raining and 0 if it’s not), and temp (which is the current temperature).

CISC 105 – Topic 5 Nested if/else Statements Using these variables: if (raining == 1) if (temp > 0) { printf(“Wet roads!\n”); printf(“Be careful when driving!\n”); } else { printf(“Snowy roads!\n”); printf(“Put snow tires on!\n”); } else printf(“OK weather. Drive safely.”);

CISC 105 – Topic 5 Alternative Forms Note than nested if/else statements can always be rewritten without nesting: if (raining == 1 && temp > 0) { printf(“Wet roads!\n”); printf(“Be careful when driving!\n”); } else if(raining == 1 && temp <= 0) { printf(“Snowy roads!\n”); printf(“Put snow tires on!\n”); } else printf(“OK weather. Drive safely.”);

CISC 105 – Topic 5 Alternative Forms We could also rewrite the program in an alternate format: if (raining == 0) printf(“OK weather. Drive safely.”); else if (temp > 0) { printf(“Wet roads!\n”); printf(“Be careful when driving!\n”); } else (temp <= 0) { printf(“Snowy roads!\n”); printf(“Put snow tires on!\n”); } Notice that these if/else statements correspond. Thus, they only run if the first condition (raining==0) is false.

CISC 105 – Topic 5 Alternative Forms And yet another alternative form: if (raining == 0) printf(“OK weather. Drive safely.”); if (raining == 1 && temp > 0) { printf(“Wet roads!\n”); printf(“Be careful when driving!\n”); } if (raining == 1 && temp <= 0) { printf(“Snowy roads!\n”); printf(“Put snow tires on!\n”); } Notice that these if statements are all independent. Thus, they all evaluate. However, as their conditions are all mutually exclusive, only one will evaluate to true, and thus only one conditional compound statement will run.

CISC 105 – Topic 5 The switch Statement When one variable (type int or char ONLY) is used to make a control decision, where different statements are run if the variable is equal to different values, the switch statement can be used. Note that this statement does not allow less than, greater than, etc. ONLY the equality operator (==) is used with a switch statement. The switch statement is composed of a control variable and a series of case clauses.

CISC 105 – Topic 5 The switch Statement The switch statement takes this form: switch(control variable) { case (value1):... break; case (value2):... break; default:... break; }

CISC 105 – Topic 5 The switch Statement When the switch statement is encountered, the control variable is evaluated. Then, if that evaluated value is equal to any of the values specified in a case clause, the statements immediately following the colon (“:”) begin to run. switch(control variable) { case (value1):... break; case (value2):... break; default:... break; }

CISC 105 – Topic 5 The switch Statement These statements then continue to run until a break statement is encountered. Control then flows to the statement immediately following the closing brace (“}”). switch(control variable) { case (value1):... break; case (value2):... break; default:... break; }

CISC 105 – Topic 5 The switch Statement It is important to remember that control will pass into the next case clause if a break statement is not encountered. switch(control variable) { case (value1):... break; case (value2):... break; default:... break; }

CISC 105 – Topic 5 The switch Statement So, what happens if the control variable is not equal to any of the values specified in the case clauses? The default case clause runs. switch(control variable) { case (value1):... break; case (value2):... break; default:... break; }

CISC 105 – Topic 5 switch Statement Example statement1; switch(x) { case (3): statement2; statement3; case (27): case (1): statement4; case (2): statement5; break; default: statement6: statement7: break; } statement8; Which statements run if: x = 1? x = 2? x = 3? x = 10? x = 27?

CISC 105 – Topic 5 Review of Control Structures Write a program that implements this flowchart using whichever control structures you deem appropriate.

CISC 105 – Topic 5 Review of Control Structures Write a program that uses one variable, letter_grade, which is a char, and displays “Excellent work!” if the grade is an A or A-, “Good work.” if the grade is a B+ or B, “Doing OK.” if the grade is a B-, C+, or C, or “Poor performance.” if the grade is a C-, D, or F.