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

Similar documents
Flow Control in C++ Condi&onals & Loops 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

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

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

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

Chapter 3. More Flow of Control

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

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

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

Overloading Functions & Command Line Use 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.

Repetition Structures

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

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

Introduction. C provides two styles of flow control:

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

REPETITION CONTROL STRUCTURE LOGO

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

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

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

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

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

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

Increment and the While. Class 15

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

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

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

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

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

Score score < score < score < 65 Score < 50

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

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

Loops / Repetition Statements

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

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

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

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

Chapter 4: Control structures. Repetition

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

Looping. Arizona State University 1

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

Chapter 4: Control structures

Add Subtract Multiply Divide

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

CS112 Lecture: Repetition Statements

Information Science 1

Introduction to Programming

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

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

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

CS110D: PROGRAMMING LANGUAGE I

Why Is Repetition Needed?

Quiz Determine the output of the following program:

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

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

Unit 7. 'while' Loops

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

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

In this chapter you will learn:

CS112 Lecture: Loops

Information Science 1

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

Chapter Goals. Contents LOOPS

Object-Oriented Programming in Java

Numerical Conversions Intro to Strings in C/C++ CS 16: Solving Problems with Computers I Lecture #8

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

Chapter 5: Loops and Files

Programming in C++ PART 2

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

CSCE 206: Structured Programming in C++

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

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

ECE 122. Engineering Problem Solving with Java

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

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

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

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

STUDENT LESSON A12 Iterations

204111: Computer and Programming

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.

INTRODUCTION TO COMPUTER SCIENCE - LAB

C++ PROGRAMMING SKILLS Part 2 Programming Structures

Control Structures of C++ Programming (2)

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

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

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

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

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

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

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

Computer Programming I - Unit 5 Lecture page 1 of 14

Loops (while and for)

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

Lecture 7 Tao Wang 1

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

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

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

Transcription:

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

A Word About Registration for CS16 FOR THOSE OF YOU NOT YET REGISTERED: There s still a waitlist to add this class! We now have a few openings and I will go by the prioritized waitlist WAITLISTED STUDENTS MUST SEE ME AFTER CLASS 10/5/2017 Matni, CS16, Fa17 2

Lecture Outline Problem Solving Simple Flow of Control IF/ELSE Statements Loops (While ; Do-While ; For) Multiway Branching and the switch command Local vs. Global Variables Some Notes on Program Style and Errors 10/5/2017 Matni, CS16, Sp17 3

How Does One Solve Problems? Understand the problem Devise a plan Carry out the plan Look back and re-assess 10/5/2017 Matni, CS16, Fa17 4

Ask questions! Strategies What do I know about the problem? What is the information that I have to process in order the find the solution? What does the solution look like? What sort of special cases exist? How will I recognize that I have found the solution? 10/5/2017 Matni, CS16, Fa17 5

Strategies Ask questions! Don t reinvent the wheel! Similar problems come up again and again in different guises A good programmer recognizes a task that has been solved before and can research the solution However, a good programmer does not plagiarize 10/5/2017 Matni, CS16, Fa17 6

Strategies Divide and Conquer! Break up a large problem into smaller units and solve each smaller problem Applies the concept of abstraction The divide-and-conquer approach can be applied over and over again until each subtask is manageable 10/5/2017 Matni, CS16, Fa17 7

Computer Problem-Solving Analysis and Specification Phase Analyze the problem Specify the details Algorithm Development Phase Develop an algorithm Test your algorithm Implementation Phase Code your algorithm Test your code Maintenance Phase Use the program Maintain the program Can you see a recurring theme? 10/5/2017 Matni, CS16, Fa17 8

Developing Software Products As a business product Software is made (developed) to meet market needs Needs resources and planning Software needs to be programmed, documented, tested, fixed/maintained There is a process to everything you need to do! A complex task a problem to solve needs a plan, an algorithm 10/5/2017 Matni, CS16, Fa17 9

Systems Development Life Cycle (SDLC) A structured approach to software development: GOAL: A software development process that leads to a high quality system that meets or exceeds customer expectations, within time and cost estimates, works effectively and efficiently in the current and planned infrastructure, and is cheap to maintain and cost effective to enhance. 10/5/2017 Matni, CS16, Fa17 10

Software Systems Development: Waterfall Model Requirement Analysis (Both Business &Tech.) Systems Design Implementation (Programming) Testing Deployment & Maintenance 10/5/2017 Matni, CS16, Fa17 11

10/5/2017 Matni, CS16, Fa17 12

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

Implementing IF/ELSE Statements in C++ As simple as: if (income > 30000) { taxes_owed = 0.30 * 30000; } else { taxes_owed = 0.20 * 30000; } 10/5/2017 Matni, CS16, Sp17 14

IF/ELSE in C++ To do additional 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 (sometimes called a block) kept together with { } 10/5/2017 Matni, CS16, Sp17 15

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

Beware: = vs == ' = ' is the assignment operator '= = ' is the equality operator Used to assign values to variables Used to compare values Example: x = 3; Example: if ( x == 3) y = 0; The compiler will actually accept this logical error: if (x = 3) y = 0; 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, so y becomes 0 10/5/2017 Matni, CS16, Sp17 17

Simple Loops 1: while We use loops when an action must be repeated C++ includes several ways to create loops while, for, do while, etc The while loop example: Output is: Hello Hello Hello int count_down = 3; while (count_down > 0) { cout << "Hello "; count_down -= 1; } 10/5/2017 18

Simple Loops 2: do-while Executes a block of code at least once, and then repeatedly executes the block depending on a given Boolean condition at the end of the block. So, unlike the while loop, the Boolean expression is checked after the statements have been executed Output is: Hello int flag = 1; do { cout << "Hello "; flag -= 1; } while (flag > 0); Why is there a semicolon here??!? 10/5/2017 Matni, CS16, Sp17 19

Simple Loops 3: for Similar to a while loop, but presents parameters differently. Allows you to initiate a counting variable, a check condition, and a way to increment your counter all in one line. for (counter declaration; check condition statement; increment rule) { } Output is: Hello Hello Hello for (int count = 2; count < 5; count++) { cout << "Hello "; } 10/5/2017 Matni, CS16, Sp17

Increments and Decrements by 1 In C++ you can increment-by-1 like this: or like this: more common a++ ++a Similarly, you can decrement by: a-- or --a 10/5/2017 Matni, CS16, Sp17 21

Some Cool Uses of x++ In a while loop, you always need to increment a counter var. Example: int max = 0; while (max < 4) { cout << hi << endl; max++; } What will this print out? 10/5/2017 Matni, CS16, Fa17 22

Some Cool Uses of x++ You can make a slight change and save a line of code! Example: int max = 0; while (max++ < 4) { cout << hi << endl; } 10/5/2017 Matni, CS16, Fa17 23

When to use x++ vs ++x x++ will assess x then increment it ++x will increment x first, then assess it 95% of the time, you will use the first one In while statements, it makes a difference In for statements, it won t make a difference 10/5/2017 Matni, CS16, Fa17 24

Examples for (int c = 0; c < 4; c++) cout << hi << endl; Prints hi 4 times Prints hi 4 times int max = 0; while (max++ < 4) { cout << hi << endl; } for (int c = 0; c < 4; ++c) cout << hi << endl; Prints hi 3 times int max = 0; while (++max < 4) { cout << hi << endl; } 10/5/2017 Matni, CS16, Sp17 25

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 (to make the loop to end) Example: Goal: Print all positive odd numbers less than 6 x = 1; while (x!= 6) { cout << x << endl; x = x + 2; } What is the problem with this code? x will never be 6! Infinite Loop! What simple fix can undo this bad design? while ( x < 6 ) 10/5/2017 Matni, CS16, Sp17 26

Using for-loops For Sums 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 get input for next sum = sum + next end of loop Let s look at it as a for-loop in C++ 10/5/2017 Matni, CS16, Fa16 27

Using for-loops For Sums The pseudocode from the previous slide can be 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? 10/5/2017 Matni, CS16, Fa16 28

Using for-loops For Products 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! 10/5/2017 Matni, CS16, Fa16 29

Ending a While Loop A for-loop is generally the choice when there is a predetermined number of iterations When you DON T have a predetermined number of iterations, you will want to use while loops The are 3 common methods to END a while loop: List ended with a sentinel value: Using a particular value or calculation to signal the end Ask before iterating: Ask if the user wants to continue before each iteration Running out of input: Using the eof function to indicate the end of a file (more on this when we discuss file I/Os) 10/5/2017 Matni, CS16, Fa16 9

List Ended With a Sentinel Value cout << "Enter a list of positive integers.\n" << "Place a negative integer after the list to quit.\n"; sum = 0; cin >> number; while (number > 0) { cout << The double of that is: << 2*number << endl; cin >> number; } Notice that the sentinel value is read, but not processed at the end 10/5/2017 Matni, CS16, Fa16 31

Ask Before Iterating 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; 10/5/2017 Matni, CS16, Fa16 32

Nested Loops The body of a loop may contain any kind of statement, including another loop When loops are nested, all iterations of the inner loop are executed for each iteration of the outer loop ProTip: Give serious consideration to making the inner loop a function call to make it easier to read your program More on functions later 10/5/2017 Matni, CS16, Fa16 33

Example of a Nested Loop You want to collect the total grades of 100 students in a class Each student has multiple scores Example: multiple homeworks, multiple quizzes, etc You go through each student one at a time and get their scores You calculate a sub-total grade for each student Then after collecting every student score, you calculate a grand total grade of the whole class and a class average (grand total / no. of students) 10/5/2017 Matni, CS16, Fa16 34

Example of a Nested Loop int students(100); double grade(0), subtotal(0), grand_total(0); for (int count = 0; count < students; count++) { cout << Starting with student number: << count << endl; cout << Enter grades. To move to the next student, enter a negative 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;

YOUR TO-DOs Finish reading up to (& including) Chapter 3 Finish Lab1 by TOMORROW AT NOON (Fri, 10/6) HW2 is now ready Visit Prof s and TAs office hours if you need help! Eat all your vegetables 10/5/2017 Matni, CS16, Fa17 36

10/5/2017 Matni, CS16, Fa17 37