Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Similar documents
Control Structures in Java if-else and switch

Control Structures in Java if-else and switch

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

Chapter 4: Making Decisions

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

Chapter 4: Making Decisions

LECTURE 04 MAKING DECISIONS

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

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.

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

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

Programming for Engineers Iteration

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

BRANCHING if-else statements

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

CS 115 Lecture 8. Selection: the if statement. Neil Moore

The following expression causes a divide by zero error:

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Decision Making in C

Flow Control. CSC215 Lecture

Lecture 5 Tao Wang 1

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

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

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

Boolean Algebra Boolean Algebra

5. Control Statements

Control Structures 1 / 17

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Selection Statements. Pseudocode

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

Chapter 4: Control Structures I (Selection)

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

LECTURE 5 Control Structures Part 2

5. Selection: If and Switch Controls

UEE1302(1102) F10: Introduction to Computers and Programming

BASIC ELEMENTS OF A COMPUTER PROGRAM

Relational Operators and if. Class 10

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

Flow Control. So Far: Writing simple statements that get executed one after another.

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Information Science 1

Statements execute in sequence, one after the other, such as the following solution for a quadratic equation:

C++ Program Flow Control: Selection

Computer Programming : C++

An overview about DroidBasic For Android

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Following is the general form of a typical decision making structure found in most of the programming languages:

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

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

If Control Construct

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

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

Introduction. C provides two styles of flow control:

G Programming Languages - Fall 2012

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

Information Science 1

Introduction to Programming

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Chapter 3. More Flow of Control

Lexical Considerations

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

These are notes for the third lecture; if statements and loops.

VARIABLES AND TYPES CITS1001

Software Design & Programming I

Chapter 2: Functions and Control Structures

Quiz 1: Functions and Procedures

Programming, numerics and optimization

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

1007 Imperative Programming Part II

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

CSCI 1061U Programming Workshop 2. C++ Basics

egrapher Language Reference Manual

Introduction to Object-Oriented Programming

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

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

Control Statements. If Statement if statement tests a particular condition

COMP 202 Java in one week

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

Expressions & Assignment Statements

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

Conditional Statement

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

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.

CT 229 Java Syntax Continued

cs1114 REVIEW of details test closed laptop period

Full file at

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

Chapter-8 DATA TYPES. Introduction. Variable:

C++ Programming Lecture 1 Software Engineering Group

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

Basics of Java: Expressions & Statements. Nathaniel Osgood CMPT 858 February 15, 2011

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Creating a C++ Program

Accelerating Information Technology Innovation

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Transcription:

Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017

Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls of an imperative program are executed or evaluated

Types of Control Flow Flow of control through any given function is implemented with three basic types of control structures: Sequential: Default mode. Statements are executed line by line. Selection: Used for decisions, branching choosing between 2 or more alternative paths. if if - else switch conditional statements Repetition: Used for looping repeating a piece of code multiple times in a row. while do - while for The function construct, itself, forms another way to affect flow of control through a whole program. This will be discussed later in the course.

True and False Selection and repetition statements typically involve decision steps. These steps rely on conditions that are evaluated as true or false C++ has a boolean data type (called bool) that has values true and false. Improves readability. Most functions that answer a yes/no question (or a true/false situation) will return a boolean answer (or in the case of user-defined functions, they should be coded that way) Important: ANY C++ expression that evaluates to a value (i.e. any R-value) can be interpreted as a true/false condition. The rule is: If an expression evaluates to 0, its truth value is false If an expression evaluates to non-zero, its truth value is true

Logical Operators

Logical Operators The comparison operators in C++ work much like the symbols we use in mathematics. Each of these operators returns a Boolean value: a true or a false. x == y x!= y x <y x <= y x >y x >= y // x is equal to y // x is not equal to y // x is less than y // x is less than or equal to y // x is greater than y // x is greater than or equal to y

Logical Operators C++ has operators for combining expressions. Each of these operators returns a boolean value: a true or a false.!x // the NOT operator (negation) //true if x is false x && y // the AND operator //true if both x and y are true x y // the OR operator //true if either x or y or both are true These operators will be commonly used as test expressions in selection statements or repetition statements (loops).

Examples of Expressions (x >0 && y >0 && z >0) // all three of (x, y, z) are positive (x <0 y <0 z <0) // at least one of the three variables is negative ( numstudents >= 20 &&!(classavg <70)) // there are at least 20 students and the class average is at least 70 ( numstudents >= 20 && classavg >= 70) // means the same thing as the previous expression

Short Circuit Evaluation The && and operators also have a feature known as short-circuit evaluation. In the Boolean AND expression (X && Y), if X is false, there is no need to evaluate Y (so the evaluation stops). Example: (d!= 0 && n / d >0) Notice that the short circuit is crucial in this one. If d is 0, then evaluating (n / d) would result in division by 0 (illegal). But the short-circuit prevents it in this case. If d is 0, the first operand (d!= 0) is false. So the whole && is false. Similarly, for the Boolean OR operation (X Y), if the first part is true, the whole thing is true, so there is no need to continue the evaluation. The computer only evaluates as much of the expression as it needs. This can allow the programmer to write faster executing code.

The if/else Selection Statement The most common selection statement is the if/else statement. Basic syntax: if (expression) { statement(s) } else { statement(s) } The else clause is optional, so this format is also legal: if (expression) { statement(s) }

The if/else Selection Statement The expression part can be any expression that evaluates a value (an R-value), and it must be enclosed in parentheses ( ). The best use is to make the expression a Boolean expression, which is an operation that evaluates to true or false For other expressions (like (x + y), for instance): an expression that evaluates to 0 is considered false an expression that evaluates to anything else (non-zero) is considered true The statement parts are the bodies of the if-clause and the else-clause. The statement after the if or else clause must be either: an empty statement a statement a block Appropriate indentation of the bodies of the if-clause and else-clause is a very good idea (for human readability), but irrelevant to the compiler

Examples if (grade >= 68) cout <<"Passing"; If grade is below 68, we just move on. if (x == 0) cout <<"Nothing here"; else cout <<"There is a value"; This example contains an else clause. The bodies are single statements.

Examples if (y!= 4) { cout <<"Wrong number"; y = y * 2; counter++; } else { cout <<"That s it!"; success = true; } Multiple statements are to be executed as a result of the condition being true or false. In this case, notice the compound statement to delineate the bodies of the if and else clauses.

Examples Be careful with ifs and elses. If you don t use { }, you may think that you ve included more under an if condition than you really have. if (val <5) cout <<"True"; else cout <<"False"; cout <<"Too bad!"; Indentation is only for people! It improves readability, but means nothing to the compiler.

Some Common Errors What s wrong with these if-statements? Which ones are syntax errors and which ones are logic errors? if (x == 1 2 3) cout <<"x is in the range 1-3"; if (x >5) && (y <10) cout <<"Yahoo!"; if (response!= Y response!= N ) cout <<"You must type Y or N (for yes or no)";

The switch Statement A switch statement is often convenient for occasions in which there are multiple cases to choose from. The syntax format is: switch (expression) { case constant: statements case constant: statements...(as many case labels as needed) } default: statements // optional label

The switch Statement The switch statement evaluates the expression, and then compares it to the values in the case labels. If it finds a match, execution of code jumps to that case label. The values in case labels must be constants, and may only be integer types, which means that you This means only integer types, type char, or enumerations (not yet discussed) This also means the case label must be a literal or a variable declared to be const Note: You may not have case labels with regular variables, strings, floating point literals, operations, or function calls If you want to execute code only in the case that you jump to, end the case with a break statement, otherwise execution of code will fall through to the next case

The Conditional Operator There is a special operator known as the conditional operator that can be used to create short expressions that work like if/else statements. Format: test expr? true expr : false expr How it works: The text expression is evaluated for true/false value. This is like the test expression of an if-statement. If the expression is true, the operator returns the true expression value. If the test expression is false, the operator returns the false expression value. Note that this operator takes three operands. It is the one ternary operator in the C++ language

Some Examples cout <<(x >y)? "x is greater than y" : "x is less than or equal to y"); // Note that this expression gives the same result as the following if (x >y) cout <<"x is greater than y"; else cout <<"x is less than or equal to y");

Some Examples (x <0? value = 10 : value = 20); // this gives the same result as: value = (x <0? 10 : 20); // and also gives the same result as: if (x <0) value = 10; else value = 20;