All about flow control

Similar documents
Looping. Arizona State University 1

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

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

Lecture 5. Review from last week. Selection Statements. cin and cout directives escape sequences

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

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

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

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

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

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

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

Information Science 1

Information Science 1

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

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

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

REPETITION CONTROL STRUCTURE LOGO

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

CSCE Practice Midterm. Data Types

Chapter 5: Loops and Files

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

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

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

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

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

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

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

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Chapter 5: Control Structures II (Repetition)

CSCE Practice Midterm. Data Types

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

In this lab, you will learn more about selection statements. You will get familiar to

Flow Control. CSC215 Lecture

LAB 4.1 Relational Operators and the if Statement

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

CSI33 Data Structures

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

Chapter 4 - Notes Control Structures I (Selection)

Basic Statements in C++ are constructed using tokens. The different statements are

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

CS 105 Lecture 5 Logical Operators; Switch Statement. Wed, Feb 16, 2011, 5:11 pm

For loops, nested loops and scopes. Jordi Cortadella Department of Computer Science

Loops and Files. of do-while loop

Loops / Repetition Statements

Chapter 5: Control Structures

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Chapter 3. More Flow of Control

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

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Technical Questions. Q 1) What are the key features in C programming language?

CSCE 206: Structured Programming in C++

Pattern Maker Lab. 1 Preliminaries. 1.1 Writing a Python program

CIS 130 Exam #2 Review Suggestions

5. Control Statements

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

Lab 9 Loops, Debugging

Outline. For loops, nested loops and scopes. Calculate x y. For loops. Scopes. Nested loops. Algorithm: repeated multiplication x x x x

Name Section: M/W T/TH Number Definition Matching (8 Points)

LECTURE 5 Control Structures Part 2

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

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

CSCI 1061U Programming Workshop 2. C++ Basics

Introduction. C provides two styles of flow control:

Chapter 4: Control structures. Repetition

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Why Is Repetition Needed?

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

C++ Final Exam 2017/2018

Chapter 2 Basic Elements of C++

Chapter 4: Control Structures I (Selection)

Announcements. HW0 is posted on schedule, due next Friday at 9pm (pretty easy)

Control Statements Review CSC 123 Fall 2018 Howard Rosenthal

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

CS1100 Introduction to Programming

The following expression causes a divide by zero error:

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

(Refer Slide Time: 00:26)

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Name Section: M/W T/TH Number Definition Matching (6 Points)

WARM UP LESSONS BARE BASICS

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

Chapter 4: Control structures

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

Quiz Determine the output of the following program:

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Lab 09: Advanced SQL

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

Programming Assignment 3

Repetition and Loop Statements Chapter 5

Computer Programming : C++

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

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

More loops Ch

Transcription:

All about flow control Prof. Zhang March 11, 2014 1 Read Coding Style Guideline Please go to the class website, find the resource part, click on the how labs are graded? link. Read the guideline, and then follow the Quick Hints to fix the indentation of your lab4.cpp (before you submit the labs). 2 Basics In order to do something interesting, we need to be able to branch off in our code, i.e., execute different codes depending on whether some condition is met or not. repeat some codes for a certain number of times, or until some condition becomes true C++ s answer to the above two needs are if- statement, if statement, and switch statement for loop, while loop, and do-while loop. 3 Branch off 3.1 if- statements The basic format (or syntax) or a if- statement is as follows if (condition) yes_statement; no_statement; 1

The semantics (or meaning) of the above statement is 1. first check condition s value 2. if condition s value is true, execute yes statement 3. if condition s value is false, execute no statement 4. execute next statement. 3.2 if statement The basic format (or syntax) or a if statement is as follows if (condition) yes_statement; The semantics (or meaning) of the above statement is 1. first check condition s value 2. if condition s value is true, execute yes statement 3. execute next statement. 3.3 Nested if- and if statements Nested if- and if statements: the yes statement or no statement itself can be a if- or if statement. For example: if (x==1) if (y==2) //this if- statement is the yes_statement for the if (x==1) cout <<"x==1 and y==2\n"; cout <<"x==1 and y!=2\n"; if (y==3) //this if statement is the no_statement for the if (x==1) cout <<"x!=1, y==3\n"; Note that the above code is not hard to understand due to the indentation style. Now compare that with the following: if (x==1) if (y==2) //this if- statement is the yes_statement for the if (x==1) cout <<"x==1 and y==2\n"; cout <<"x==1 and y!=2\n"; if (y==3) //this if statement is the no_statement for the if (x==1) cout <<"x!=1, y==3\n"; 2

Both reads the same to the compiler, but the second one gives everyone a big headache to figure out. So often the first step to debug your program, or even just to understand it, is to fix its indentation. 3.4 Multi-way branch Multi-way branch We often use nested if- statement to express a multi-way branch, for example, if (coin=="quarter") value=25; if (coin=="dime") value=10; if (coin=="nickle") value=5; if (coin=="penny") value=1; cout <<"Invalid coin name" << coin <<"\n"; A conventional way to format a multi-way branch such as above is follows: if (coin=="quarter") value=25; if (coin=="dime") value=10; if (coin=="nickle") value=5; if (coin=="penny") value=1; cout <<"Invalid coin name" << coin <<"\n"; Compare the above code segment with the following (where 5 consecutive if statements are used): if (coin=="quarter") value=25; if (coin=="dime") value=10; 3

if (coin=="nickle") value=5; if (coin=="penny") value=1; if (coin!="quarter" && coin!="dime" && coin!="nickle" && coin!=penny") cout <<"Invalid coin name" << coin <<"\n"; 3.5 Dangling problem Dangling problem is a problem in computer programming in which an optional clause in an if() statement results in nested conditionals being ambiguous. if (condition1) if (condition2) yes_statement; //is this for the first if, or the second if? no_statement; In C++, the compiler will associate the with the nearest unmatched if statement. So in the above example, the is associated with if condition2. If you want the to be associated with the first if condition, do the following: if (condition1) //use to demarcate this if statement if (condition2) yes_statement; no_statement; 3.6 switch statement switch statement has the following syntax: switch (expression) case constant1: statement11; case constant2: statement21; 4

default: statement31; There are some constraints about switch statement: The expression that we switch on needs to be integetral type, including int, long, char, bool. The switch case needs to be constants (named constants or literal constants) The meaning (or semantics) of the switch statement can be explained in terms of the equivalent if- statement: if (expression==constant1) statemt11; if (expression==constant2) statemnet21; statement31; Note: Pay special attention to the break statements at the end of each cases. As beginners, use break always. Without break statement, the flow of execution cascade down to next case, and the case after (if the next case also does not have break statement). char lettergrade; switch (lettergrade) case A : cout <<"you got 90-100\n"; 5

case B : cout <<"You are above average\n"; case C : cout <<"Try harder!\n"; case D : case F : cout <<"Danger of failing!\n"; defalut: cout <<"Invalid grade\n"; Here are the outputs of the program depending on lettergrade s value: A: you got 90-100 you are above average B: You are above average C: try harder! D: Danger of failing! F: Danger of failing! other values: invalid grade 4 Understand and Build Loop 4.1 for loop statement The basic format (or syntax) or a for loop statement is as follows for (initialiation; condition; update) statement_to_repeat; The semantics (or meaning) of the above statement is 1. first execute initialization 2. condition is checked, 3. if condition is true, executes statement, then update, and then goes back to step 2. 6

4. if condition is false, for loop ends, execution continues from the next statement (after the for loop statement) A for loop can be converted to a while loop as follows: initialization; while (condition) statement_to_repeat; update; For example, the following code prints out integers from 0 to 99: for (int i=0;i<100;i++) cout << i <<"\n"; First, variable i is declared and initialized to 0 (in the initialization of the loop). As long as i is less than 100, the loop body prints out i s value, and then i is incremented by 1. This continues until i==100. Note that the above for loop is the most commonly used form. Variable i is called counter variable, it counts up from 0 to 100 by 1. One can count up, or count down, or by other increment other than 1. //this for loop calculate the sum of all even numbers between 0 and 98 sum=0; for (int i=0;i<100;i=i+2) sum = sum+i; Exercises: Write a for loop to print out 30 asterisk signs on the same line We can count up: for (int i=0;i<30;i++) cout <<"*"; or count donw: for (int i=30;i>0;i--) cout <<"*"; Write a for loop to print power of 2 s, i.e., 2 0, 2 1, 2 2,, up to 2 31. We first initilaizes our power variable that keeps track the current power, and then keeps doubling its value: 7

int power=1; for (int i=0;i<32;i++) cout <<"2^" << i <<"= "<<power; power=power*2; for loop can be nested, for example, the following code prints multiplication table: for (int i=1;i<10;i++) //we call this outer loop for (int j=1;j<10;j++) //we call this inner loop cout << " " << i*j << " "; cout <<"\n"; Let s follow (trace) this loop to see how it works Exercises: Write a program to print a rectangle made up of asterisks, the length and height of the rectangle are given by the user. For example, if the length is 5, and the height is 3, the output should be: ***** ***** ***** Write a program to print a right triangle made up of asterisks of a given side length. For example, if the side length is 5, the output should be: * ** *** **** ***** Write a program to print a triangle of the following shape with a given side length. For example, if the side length is 4, the output should be: * *** ***** ******* 8

4.2 while loop statement The basic format (or syntax) or a while loop statement is as follows while (condition) statement; The semantics (or meaning) of the above statement is 1. condition is checked, 2. if condition is true, executes statement, and then goes back to step 1. 3. if condition is false, while loop ends, execution continues from the next statement (after the loop statement) The most simple while loop is as follows: int i=0; while (true) i++; cout <<"i=" <<i <<"\n"; Exercise What will happen when the above while loop is executed? How to make the loop ends when i reaches the maximum int value? statement Use break // To read any number of values, end with a -1 int num; while (true) cout <<"Enter next value:"; cin >> num; if (num==-1) Preferred way to write such as loop is to avoid using break statement. What do you think are the downsides of using break statement (one or multiple?)? We prefer to express the loop condition in the while header only, so that it s easy to see when the loop continues, as the loop can be very long and complicated. 9

// To read any number of values, end with a -1 int num=0; while (num!=-1) // as long as value is not -1, continue cout <<"Enter next value:"; cin >> num; 4.3 do-while loop The do-while loop has the following syntax: do statement; while (condition); The semantics (or meaning) of the statement is as follows: 1. execute statement first 2. evaluate condition, if it s true, go back to 1 The difference between while loop and do-while loop is that while loop might iterate for zero time (if the condition is false the first time), while do-while loop always iterate the first time. 10