Flow Control in C++ Condi&onals & Loops CS 16: Solving Problems with Computers I Lecture #4

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

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

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

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

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

Chapter 3. More Flow of Control

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

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

Advanced Flow Control CS 16: Solving Problems with Computers I Lecture #5

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

Lecture # 6. Repetition. Review. If Else Statements Comparison Operators Boolean Expressions Nested Ifs. Switch Statements.

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

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

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

Computational Physics - Fortran February 1997

Programming in C++ PART 2

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

Introduction. C provides two styles of flow control:

REPETITION CONTROL STRUCTURE LOGO

Arrays 2 CS 16: Solving Problems with Computers I Lecture #12

Add Subtract Multiply Divide

Java Programming Basics. COMP 401, Fall 2017 Lecture 2

Func%ons in C++ Part 2 CS 16: Solving Problems with Computers I Lecture #5

Java Programming Basics. COMP 401, Spring 2017 Lecture 2

Information Science 1

Score score < score < score < 65 Score < 50

Design and Debug: Essen.al Concepts Numerical Conversions CS 16: Solving Problems with Computers Lecture #7

Introduc)on to Arrays in C++ Review for Midterm #2 CS 16: Solving Problems with Computers I Lecture #12

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

More on Strings in C++ Arrays CS 16: Solving Problems with Computers I Lecture #11

Chapter 6 More About Loops and Decisions PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Information Science 1

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

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

More on Func*ons Command Line Arguments CS 16: Solving Problems with Computers I Lecture #8

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

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

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

Lecture 5 Tao Wang 1

C++ Support Classes (Data and Variables)

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

Programming Language. Functions. Eng. Anis Nazer First Semester

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

CSI33 Data Structures

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

Introduc)on to C++ CS 16: Solving Problems with Computers I Lecture #2

In this chapter you will learn:

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

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

Increment and the While. Class 15

Announcements. Homework 0 out! Coming soon: 1. remote access 2. programming instructions 3. lab 1 (graded!) this week

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

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

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

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

Announcements. Lab 1 this week! Homework posted Thursday -Due next Thursday at 11:55pm

Pre- Defined Func-ons in C++ Review for Midterm #1

A SHORT COURSE ON C++

Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11

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

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

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

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

Loops / Repetition Statements

CSCI Wednesdays: 1:25-2:15 Keller Thursdays: 4:00-4:50 Akerman 211

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

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

Unit 7. 'while' Loops

Decision Making in C

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

C++ PROGRAMMING SKILLS Part 2 Programming Structures

Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5

Linked Lists CS 16: Solving Problems with Computers I Lecture #16

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Quiz Determine the output of the following program:

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

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.

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

CS 007A Midterm 1 Practice Chapters 1 5

Chapter 5: Loops and Files

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

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

Announcements. Homework 0: using cin with 10/3 is NOT the same as (directly)

Logical Operators and if/else statement. If Statement. If/Else (4.3)

Repetition Structures

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

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

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

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

Chapter 4: Control structures. Repetition

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

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

Chapter 3, Selection. Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved.

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

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

The following expression causes a divide by zero error:

CIS 130 Exam #2 Review Suggestions

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

CS150 Introduction to Computer Science 1. Logical Operators and if/else statement

Transcription:

Flow Control in C++ Condi&onals & Loops CS 16: Solving Problems with Computers I Lecture #4 Ziad Matni Dept. of Computer Science, UCSB

Announcements Homework #3 due today Homework #4 is assigned Lab #2 is due on Tuesday AT NOON! Class is closed to new registrajon No more switching lab Jmes Student Shen, Jinxu please idenjfy yourself! 4/13/17 Matni, CS16, Sp17 2

Note on Turning In Homework From Now On PLEASE STAPLE YOUR HOMEWORK PAGES J 4/13/17 Matni, CS16, Sp17 3

Lecture Outline Simple Flow of Control IF/ELSE Statements Review of Boolean Operators Truth Tables Loops While Do- While For Notes on Program Style 4/13/17 Matni, CS16, Sp17 4

Notes on the cmath Library Standard math library in C++ Contains several useful math funcjons, like cos( ), sin( ), exp( ), log( ), pow( ), sqrt( ) To use it, you must import it at the start of your program #include <cmath> You can find more informajon on this library at: h\p://www.cplusplus.com/reference/cmath/ 4/13/17 Matni, CS16, Sp17 5

Flow of Control Another way to say: The order in which statements get executed Branch: (verb) How a program chooses between 2 alternajves Usual way is by using an if- else statement if (Boolean expression) true statement else false statement 4/13/17 Matni, CS16, Sp17 6

ImplemenJng IF/ELSE Statements As simple as: in C++ if (income > 30000) { taxes_owed = 0.30 * 30000; } else { taxes_owed = 0.20 * 30000; } Curly braces are opjonal if they contain only 1 statement Where s the semicolon??!? 4/13/17 Matni, CS16, Sp17 7

IF/ELSE in C++ To do addijonal things in a branch, use the { } brackets to keep all the statements together if (income > 30000) { taxes_owed = 0.30 * 30000; category = RICH ; alert_irs = true; } // end if part of the statement else { taxes_owed = 0.20 * 30000; category = POOR ; alert_irs = false; } // end else part of the statement Groups of statements (somejmes called a block) kept together with { } 4/13/17 Matni, CS16, Sp17 8

Review of Boolean Expressions: AND, OR, NOT Since flow control statements depend on Booleans, let s review some related expressions: AND operator (&&) (expression 1) && (expression 2) True if both expressions are true OR operator ( ) Note: no space between each character! (expression 1) (expression 2) True if either expression is true NOT operator (!)!(expression) False, if the expression is true (and vice versa) 4/13/17 Matni, CS16, Sp17 9

Truth Tables for Boolean OperaJons X Y X && Y F F T T AND OR NOT F T F T F F F T X Y X Y F F T T F T F T F T T T X! X F T T F IMPORTANT NOTES: 1. AND and OR are not opposites of each other!! 2. AND: if just one condijon is false, then the outcome is false 3. OR: if at least one condijon is true, then the outcome is true 4. AND and OR are commuta^ve, but not when mixed (so, order ma\ers) X && Y = Y && X X && (Y Z) is NOT = (X && Y) Z 4/13/17 Matni, CS16, Sp17 10

Precedence Rules on OperaJons in C++ If parenthesis are omi\ed from Boolean expressions, the default precedence of operajons is: 4/13/17 Matni, CS16, Sp17 11

Examples of IF Statements if ( (x >= 3) && ( x < 6) ) y = 10; The variable y will be assigned the number 10 only if the variable x is equal to 3, 4, or 5 if!(x > 5) y = 10; The variable y will be assigned the number 10 if the variable x is NOT larger than 5 (i.e. if x is 4 or smaller) DESIGN TIP: Unless you really have to, avoid the NOT logic operator when designing condijonal statements 4/13/17 Matni, CS16, Sp17 12

Beware: = vs == ' = ' is the assignment operator Used to assign values to variables Example: x = 3; '= = ' is the equality operator Used to compare values Example: if ( x == 3) The compiler will actually accept this logical error: if (x = 3) Why? It s an error of logic, not of syntax But it stores 3 in x instead of comparing x and 3 Since the result is 3 (non- zero), the expression is true 4/13/17 Matni, CS16, Sp17 13

Simple Loops 1 while We use loops when an acjon must be repeated C++ includes several ways to create loops while, for, do while, etc The while loop example: int count_down = 3; while (count_down > 0) { cout << "Hello "; count_down - = 1; } Output is: Hello Hello Hello 4/13/17 Matni, CS16, Sp17 14

The do- while loop Executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given Boolean condijon at the end of the block. So, unlike the while loop, the Boolean expression is checked afer the statements have been executed int flag = 1; do { cout << "Hello "; flag - = 1; } while (flag > 0); Why is there a semicolon??!? Output is: Hello Simple Loops 2 do- while 4/13/17 Matni, CS16, Sp17 15

The for loop Simple Loops 3 for Similar to a while loop, but presents parameters differently. Allows you to inijate a counjng variable, a check condijon, and a way to increment your counter all in one line. for (counter declara=on; check condi=on statement; increment rule) { } for (int count = 2; count < 5; count++) { cout << "Hello "; } Output is: Hello Hello Hello 4/13/17 Matni, CS16, Sp17 16

Increments and Decrements by 1 In C++ you can increment- by- 1 like this: a++ or like this: ++a ß more common Similarly, you can decrement by: a- - or - - a 4/13/17 Matni, CS16, Sp17 17

Infinite Loops Loops that never stop to be avoided! Your program will either hang or just keep spewing outputs for ever The loop body should contain a line that will eventually cause the Boolean expression to become false Example: Goal: Print all posijve odd numbers less than 6 x = 1; while (x!= 6) { cout << x << endl; x = x + 2; } What simple fix can undo this bad design? while ( x < 6) 4/13/17 Matni, CS16, Sp17 18

Sums and Products A common task is reading a list of numbers and computing the sum Pseudocode for this task might be: sum = 0; repeat the following this_many times cin >> next; sum = sum + next; end of loop Let s look at it as a for-loop in C++ 4/13/17 Matni, CS16, Fa16 19

for-loop for a sum The pseudocode from the previous slide is implemented as int sum = 0; for(int count = 0; count < 10; count++) { cin >> next; sum = sum + next; } Note that sum must be initialized prior to the loop body! Why? 4/13/17 Matni, CS16, Fa16 20

for-loop For a Product Forming a product is very similar to the sum example seen earlier int product = 1; for(int count = 0; count < 10; count++) { cin >> next; product = product * next; } Note that product must be initialized prior to the loop body Product is initialized to 1, not 0! 4/13/17 Matni, CS16, Fa16 21

Ending a While Loop A for-loop is generally the choice when there is a predetermined number of iterations But what about ending while loops? The are 3 common methods: Ask before itera=ng Ask if the user wants to conjnue before each iterajon List ended with a sen=nel value Using a parjcular value to signal the end of the list Running out of input Using the eof funcjon to indicate the end of a file 4/13/17 Matni, CS16, Fa16 9

Ask Before IteraJng A while loop is used here to implement the ask before iterajng method to end a loop. sum = 0; char ans; cout << "Are there numbers in the list (Y/N)?"; cin >> ans; while (( ans == 'Y') (ans == 'y')) { //statements to read and process the number } cout << "Are there more numbers(y/n)? "; cin >> ans; 4/13/17 Matni, CS16, Fa16 23

List Ended With a SenJnel Value A while loop is typically used to end a loop using the list ended with a sen=nel value method cout << "Enter a list of nonnegative integers.\n" << "Place a negative integer after the list.\n"; sum = 0; cin >> number; while (number > 0) { //statements to read/process number cin >> number; } NoJce that the senjnel value is read, but not processed at the end 4/13/17 Matni, CS16, Fa16 24

Running Out of Input The while loop is typically used to implement the running out of input method of ending a loop ifstream infile; infile.open("data.dat"); while (! infile.eof( ) ) { // read and process items from the file // File I/O covered in Chapter 6 } infile.close( ); ß We ll cover ifstream objects later in the course 4/13/17 Matni, CS16, Fa16 25

Nested Loops The body of a loop may contain any kind of statement, including another loop When loops are nested, all iterajons of the inner loop are executed for each iterajon of the outer loop ProTip: Give serious considerajon to making the inner loop a funcjon call to make it easier to read your program 4/13/17 Matni, CS16, Fa16 26

Example of a Nested Loop int students(100) double grade(0), subtotal(0), grand_total(0); for (int count = 0; count < students; count++) { cout << StarJng with student number: << count << endl; cout << Enter his/her grades. To move to the next student, enter a negajve number.\n cin >> grade; while (grade >= 0) { subtotal = subtotal + grade; cin >> grade; } // end while loop cout << Total grade count for student << count << is << subtotal << endl; grand_total = grand_total + subtotal; subtotal = 0; } // end for loop cout << Average grades for all students= << grand_total / students << endl;

Notes on Program Style The goal is to write a program that is: easier to read easier to correct easier to change Items considered a group should look like a group Use the { } well Indent groups together as they make sense Make use of comments // for a single line comment /*. */ for muljple line comments If a number comes up oen in your program (like φ = 1.61803), consider declaring it as a constant at the start of the program: const double PHI = 1.61803; Constants, unlike variables, cannot be changed by the program Constants can be int, double, char, string, etc 4/13/17 Matni, CS16, Sp17 28

TO DOs Readings The rest of Chapter 3 in textbook Homework #4 Lab #2 Both due Tuesday 4/13/17 Matni, CS16, Sp17 29

4/13/17 Matni, CS16, Sp17 30