Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Similar documents
Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

C++ Programming: From Problem Analysis to Program Design, Third Edition

Chapter 4: Control Structures I (Selection)

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

Chapter 4 - Notes Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Third Edition

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

REPETITION CONTROL STRUCTURE LOGO

Introduction. C provides two styles of flow control:

Why Is Repetition Needed?

Control Structures: The IF statement!

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 5: Control Structures II (Repetition)

Lecture 3 Tao Wang 1

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Chapter 7. Additional Control Structures

LESSON 3 CONTROL STRUCTURES

Chapter 4: Control Structures I

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Objectives. In this chapter, you will:

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

CSCI 1061U Programming Workshop 2. C++ Basics

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

LECTURE 5 Control Structures Part 2

Chapter 2 Basic Elements of C++

Chapter 4: Making Decisions

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Chapter 4: Making Decisions

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Programming for Engineers Iteration

5. Selection: If and Switch Controls

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Chapter 3. More Flow of Control

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Add Subtract Multiply Divide

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

The following expression causes a divide by zero error:

(Refer Slide Time: 00:26)

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

In this chapter you will learn:

Chapter 5: Loops and Files

Loops and Files. of do-while loop

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

LECTURE 04 MAKING DECISIONS

Flow Control. CSC215 Lecture

Increment and the While. Class 15

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Lecture 7 Tao Wang 1

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Chapter 5 Selection Statements. Mr. Dave Clausen La Cañada High School

5. Control Statements

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

Introduction to C Programming

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Checking Multiple Conditions

Computer Programming : C++

DELHI PUBLIC SCHOOL TAPI

Control Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Using Boolean Expressions. Multiway Branches. More about C++ Loop Statements. Designing Loops. In this chapter, you will learn about:

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

C++ Programming: From Problem Analysis to Program. Design, Fifth Edition. Chapter 1: An Overview of Computers and Programming Languages

C++ Final Exam 2017/2018

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Chapter 5: Control Structures

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

SFU CMPT Topic: Control Statements

Chapter 3 Structured Program Development

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

G. Tardiani RoboCup Rescue. EV3 Workshop Part 1 Introduction to RobotC

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

CS110D: PROGRAMMING LANGUAGE I

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision

Transcription:

EEE-117 COMPUTER PROGRAMMING Control Structures Conditional Statements Today s s Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean) expressions Discover how to use the selection control structures if, if...else, and switch in a program Learn to use loops (Chapter 5) Assistant Prof. Dr. Turgay IBRIKCI Thursday, October 14, 2010 2 Control Structures A computer can proceed: in sequence selectively (branch) - making a choice repetitively (iteratively) - performing a statement over and over, also called a loop Some statements are executed only if certain conditions are met A condition is represented by a logical (Boolean) expression that has a value of either true or false A condition is met if it evaluates to true 3 4 Relational Operators Relational Operators in C++ A relational operator allows you to make comparisons in a program Equality of real numbers is usually machine dependent so it is possible that on a particular machine 6.8 + 3.1 == 2.7 + 7.2 might evaluate to false Comparing values of different data types may produce unpredictable results For example, 8 < '5' should not be done C++ returns an integer value of 1 if the logical expression evaluates to true and the value of 0 otherwise In C++, any nonzero value is treated as true 5 6

Comparing string Types Relational operators can be applied to string variables They are compared character by character, starting with the first character, using the collating sequence This comparison continues until either a mismatch is found or the last characters have been compared and are equal If two strings of different lengths are compared and the comparison is equal to the last character of the shorter string, the shorter string is less than the larger string 7 8 string Comparison Example Suppose we have the following declarations: string str1 = "Hello"; string str2 = "Hi"; string str3 = "Air"; string str4 = "Bill"; Logical (Boolean) Operators Logical (Boolean) operators enable you to combine logical expressions There are three logical (Boolean) operators:! - not && and - or Logical operators take logical values as operands and yield logical values as results! is unary, so it has only one operand, while && and are binary operators Putting! in front of a logical expression reverses the value of that logical expression 9 10 Precedence of Operators Relational and logical operators are evaluated from left to right so the associativity is said to be from left to right Parentheses can be used to indicate an order of operation that is different than the order indicated by order of precedence Short-circuit evaluation (of a logical expression) - a process in which the computer evaluates a logical expression from left to right and stops as soon as the value of the expression is known Precedence of Operators Expression Evaluates To Comments (14 >= 5) && ( A < B ) True (24 >= 35) && ( A < B ) False Because (14 >= 5) is True, ( A < B ) is True and true && true is true, the expression evaluates to true. Because (24 >= 35) is false, ( A < B ) is true and false && true is false, the expression evaluates to false. Refer to page 150 for further explanation 11 12

Precedence of Operators Logical (Boolean) Assignments The int Data Type and Logical (Boolean) Expressions earlier versions of C++ had no built in data type that had logical (or Boolean) values, true and false since logical expressions are evaluated to either 1 or 0, the value of a logical expression is stored in a variable of the type int logical (Boolean) expressions were manipulated with the help of the int data type any nonzero value is treated as true 13 14 Logical (Boolean) Assignments The bool Data Type and Logical (Boolean) Expressions recent versions of C++ contain a built in data type called bool the data type bool has logical (Boolean) values true and false in C++, bool, true, and false are reserved words the identifier true has the value 1 the identifier false has the value 0 Logical (Boolean) Assignments Logical expressions do not always behave as expected The following expression appears to represent a comparison of 0, num, and 10: 0 <= num <= 10 It will always evaluate to true because 0 <= num evaluates to either 0 or 1, and 0 <= 10 is true and 1 <= 10 is true The correct way to write this expression is: 0 <= num && num <= 10 15 16 One-Way (if( if) ) Selection Two-Way (if( if else) ) Selection The syntax of one-way selection is: if(expression) statement If the value of the expression is true the statement is executed If the value is false the statement is not executed and the computer goes on to the next statement in the program The expression is usually a logical expression statement is any C++ statement if is a reserved word Two-way selection takes the form: if(expression) else statement1 statement2 If the value of the expression is true, statement1 is executed otherwise statement2 is executed statement1 and statement2 are any C++ statements else is a reserved word 17 18

Two-Way (if( if else) ) Selection if(score >= 90) grade = A ; cout<< The grade is <<grade<<endl; What is is wrong with the above statement? If If incorrect, how would you re-write the logical statements? Compound Statement A compound statement (also called a block of statements) takes the form statement1; statement2;... statementn; A compound statement is considered a single statement 19 20 Compound Statement Example if(age > 18) cout<<" Eligible to vote."<<endl; cout<<" No longer a minor."<<endl; else cout<<"not eligible to vote."<<endl; cout<<"still a minor."<<endl; Nested if When one control statement is within another, it is said to be nested An else is associated with the most recent if that has not been paired with an else For example: if(score >= 90) cout<<"the grade is A"<<endl; else if(score >= 80) else cout<<"the grade is B"<<endl; cout<<"the grade is F"<<endl; 21 22 switch Structures In a switch structure, the expression is evaluated first Next, the value of the expression is used to perform the corresponding action The expression is usually an identifier It is sometimes called the selector The expression value can be only integral Its value determines which statement is selected for execution A particular case value should appear only once switch Structures One or more statements may follow a case label Braces are not needed to turn multiple statements into a single compound statement The break statement may or may not appear after each statement The break statement has a special meaning and may or may not appear after each statement switch, case, break, and default are reserved words 23 24

switch Statement Rules When the value of the expression is matched against a case value, the statements execute until a break statement is found or the end of the switch structure is reached If the value of the expression does not match any of the case values, the statements following the default label execute. If there is no default label, and if the value of the expression does not match any of the case values, the entire switch statement is skipped A break statement causes an immediate exit from the switch structure Control Structures - Repetition Chapter 5 25 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled Loops Flag Controlled Loops EOF Controlled Loops for Loops The do while Looping Structure Why Is Repetition Needed? Consider a task that the computer might automate Calculate and print paychecks Read invoices from a file and print monthly statements Read inputs from a sensor and adjust the air-fuel mixture of an engine In general The "Input process output" cycle 27 28 Why Is Repetition Needed? 29 The Repetition Structure 30 The algorithm requires a set of actions to be done over and over again Same set of actions Number of times to be executed is unknown at design time We need a structure which allows Statement(s) to be repeated A method of testing to see whether the statements should be repeated The while loop provides the repetition structure Statement(s) to be repeated A means of checking whether the statement(s) will be repeated Syntax: while ( logicalexpression ) statement;

Phases of Loop Execution 31 While Loop Illustration 32 Loop entry => flow of control reaches first statement inside loop Iteration => each pass thru the loop Loop test => condition tested before each iteration while (condition) false true Loop Iteration Loop Iteration Loop Test Loop Test Loop Exit Loop Exit Loop exit => when termination condition occurs statement 1 in while statement, loop is NOT executed another time statement 2 Loop Entry Loop Entry Counter Controlled Loops For when you know exactly how many times the loop should run There are 10 employees for which to print checks There are 60 sensor inputs per second The program needs a Loop Control Variable 33 Count Controlled Loop Uses a Loop Control Variable (LCV) x = 0; 0; while (x (x <= <= 10) cout << << count = << << x << << endl; x = x + 1; 1; 34 What gets printed? What gets printed? Count Controlled Loops 35 Count Controlled Loops 36 The LCV must be... Initialized I nitialized I ncremented I nspected YES x = 0; 0; while (x (x <= <= 10) 10) cout << << count = << << x << << endl; x = x + 1; 1; Inspected Incremented

Sentinel Controlled Loops Suppose you want to read some positive integers and average them You do not have a preset number of data items in mind. Suppose the number 999 marks the end of data. Then the -999 is your "sentinel" cin>>variable; 37 while(variable!= sentinel)... View sample program Flag Controlled Loops A flag controlled loop uses a Boolean variable to control the loop Example Let found be the Boolean variable found = false; while(!found)... if(expression) found = true; 38 The flag is set according to some condition cin>> variable; EOF Controlled Loops End of File Controlled 39 Testing the State of an I/O Stream The name of the input stream (used by itself) returns a value returns a 0 if it is NOT successful it returns a NON zero value if it IS successful 40 Do you need to to know how many items are in in the file? Why? Why not? Testing the State of an I/O Stream 41 EOF Controlled Loops 42 When reading a file (a named input stream) we wish to know when it reaches the end Since the name returns a 0 or non-0, this can be used as a Boolean value Used to control program sequencing, control a file reading loop Can also be used in keyboard entry situations cin>>variable; while(cin)... cin>>variable; // Ctrl-Z Z to signify eof Although a sentinel controlled loop might be more user friendly

EOF Controlled Loops 43 A Special Count Controlled Loop 44 In addition to checking the value of an input stream variable eof The function with an input stream variable can also be used to determine the end of file status. Syntax: istreamvar.eof() Example infile.get(ch); while(!infile.eof()) cout<<ch; infile.get(ch); The for ( ) statement for for ( initialization ; test expression ; update ) 0 or or more statements to to repeat Initialization : initializes the LCV Condition : usually a comparison, acts like a while ( ) Incrementing statement : LCV is incremented (or decremented) The for ( ) Loop 45 The for ( ) Loop 46 Example - what gets printed? x gets initialized How did it Happen? All three of the portions inside the parentheses can be multiple statements separated by commas Any or all of the three portions inside the parenthesis may be missing accomplish those tasks some other way the two semicolons MUST be there value of x inspected x gets incremented for Loops 47 A Different Looping Statement 48 Note the sequence of events in a for loop Recall that the while ( ) statement always checked the condition BEFORE the loop In certain situations we wish to check the condition at The END of the loop After the statement Is it possible that the initialization and condition could be set so that that the loop statement would never execute?

The Do-While Statement 49 The do-while Illustrated Condition tested at end/bottom of loop Guarantees loop body executes at least once Loop Entry Loop Entry Loop Iteration Loop Iteration Note: always at least one iteration Loop Exit Loop Exit Loop Trest Loop Trest 50 The Do-While Statement 51 The Do while Statement 52 Can be used for a counting loop This logic sometimes more suitable for some algorithms Example : trap for valid input do cout << Enter value (1-5) -> ; cin >> value; if (value < 1 value > 5) cout << Invalid input\a << endl; while (value < 1 value > 5); What gets printed?? How do you change it to go 10 times? What makes this this easier than than the the while while (( )) loop loop for for this this task? do-while Loop vs. while Loop 53 The break; Statement 54 POST-TEST loop (exitcondition) The looping condition is tested after executing the loop body. Loop body is always executed at least once. PRE-TEST loop (entry-condition) The looping condition is tested before executing the loop body. Loop body may not be executed at all. We saw it in the switch statement Causes immediate exit from innermost block switch, while, do-while while, for Can be used to break out of purposely designed infinite loop not a good idea a lazy shortcut Use only as last resort to avoid baffling combinations of multiple Boolean flags and nested ifs

The continue; Statement Valid only in loops Terminates current loop iteration NOT entire loop Causes branch to bottom of loop skips rest of loop statements Loop then prepares for next iteration for ( )( would increment lcv all loops would check condition 55 56 Guidelines for Choosing a Looping Statement Simple count-controlled use for ( )( loop Event controlled, body always executed at least once use do-while Event controlled and nothing known about first execution use while, possibly for When in doubt => use while Testing and Debugging For do-while loops, make sure to try data sets to make loop go exactly one time For data-dependant loop where expressions based on values other than constants make sure to test for proper number of iterations Make sure switch statements have every branch tested including default 57 Testing and Debugging Remember to use break at end of case alternatives in switch statements otherwise next case is also executed! Case labels in switch statement must be values or named constants -- no variables Both switch expression & case constant cannot be floating point Provide default for switch when possibility of case values not being matched 58 Testing and Debugging Make sure all needed switch cases are present Choose looping structure carefully 59 for( ; ; ) loop heading must have two semicolons -- even if portions omitted Break statement can exit only one level of nesting innermost switch or loop where break is located The assert Function Certain types of errors that are very difficult to catch can occur in a program For example, division by zero can be difficult to catch using any of the programming techniques we have examined so far The predefined function, assert, is useful in stopping program execution when certain elusive errors occur 60

The assert Function The syntax to use the assert function is: assert(expression); expression is any logical expression If expression evaluates to true, the next statement executes If the expression evaluates to false, the program terminates and indicates where in the program the error occurred The specification of the assert function is found in the header file cassert The assert Function The assert statement is very useful for enforcing programming constraints during program development After a program has been developed and put into use, if an assert statement fails for some reason, an end user would have no idea what the error means After developing and testing a program, remove or disable assert statements The preprocessor directive #define NDEBUG must be placed before the directive #include <cassert> to disable the assert statement 61 62 Quick Quiz Given the following values for Boolean variables X, Y, and Z, evaluate the logical expressions and answer T if the result is True and F if the result is False. X = True, Y = False, Z = False!(Y!(Y Z) Z) X Z && && X && && Y!Y!Y (Z (Z!X)!X) Z (X (X && && (Y (Y Z) Z) )) 5!X!X && && Z Quick Quiz What is the output of the following code segment? int hours = 12; If (hours > 40) cout << "Overtime Hours\n"; What is the output of the following code segment? int num1 = 3, num2 = 2, temp = 0; if (num1 > num2) temp = num1; num1 = num2; num2 = temp; cout << num1 << endl; else cout << "No change\n"; 63 64 Quick Quiz What occurs if a program statement includes a divide by zero? What occurs if a program statement includes a divide by zero and the assert function is used? 65 66