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

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

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

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

Chapter 3. More Flow of Control

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

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

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

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter Procedural Abstraction and Functions That Return a Value. Overview. Top-Down Design. Benefits of Top Down Design.

Chapter 4. Procedural Abstraction and Functions That Return a Value

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

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

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

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

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

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

Lab Instructor : Jean Lai

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

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

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

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

Chapter Four: Loops II

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

Top-Down Design Predefined Functions Programmer-Defined Functions Procedural Abstraction Local Variables Overloading Function Names

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

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

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

(More) Fun with Pointers and Linked Lists! CS 16: Solving Problems with Computers I Lecture #17

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

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

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

Why Is Repetition Needed?

Chapter 3 Function Basics

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

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

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

Chapter 3 - Functions

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

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

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

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

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

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

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

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

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

CS110D: PROGRAMMING LANGUAGE I

do { statements } while (condition);

(created by professor Marina Tanasyuk) FUNCTIONS

CSCE 206: Structured Programming in C++

Functions. Lecture 6 COP 3014 Spring February 11, 2018

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

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

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

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

Principles of Computer Science I

More About WHILE Loops

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Functions and Recursion

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

Unit 7. 'while' Loops

File I/O CS 16: Solving Problems with Computers I Lecture #9

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

CS 103 Lecture 3 Slides

STUDENT LESSON A12 Iterations

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.6

Review for the Final Exam CS 8: Introduction to Computer Science, Winter 2018 Lecture #15

Strings in Python 1 Midterm#1 Exam Review CS 8: Introduction to Computer Science Lecture #6

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Score score < score < score < 65 Score < 50

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

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

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

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

Call- by- Reference Func0ons Procedural Abstrac0ons Numerical Conversions CS 16: Solving Problems with Computers I Lecture #9

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

CS31 Discussion 1E. Jie(Jay) Wang Week1 Sept. 30

PASS$MOCK$EXAM$ $FOR$PRACTICE$ONLY$

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Lecture 04 FUNCTIONS AND ARRAYS

Repetition Structures

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

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

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

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

Week 4 EECS 183 MAXIM ALEKSA. maximal.io

CIS 130 Exam #2 Review Suggestions

REPETITION CONTROL STRUCTURE LOGO

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

Chapter 4: Subprograms Functions for Problem Solving. Mr. Dave Clausen La Cañada High School

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

Finding Pi: Applications of Loops, Random Numbers, Booleans CS 8: Introduction to Computer Science, Winter 2018 Lecture #6

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Dept. of CSE, IIT KGP

C Functions. 5.2 Program Modules in C

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

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

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

CSCI 1061U Programming Workshop 2. Function Basics

Transcription:

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6 Ziad Matni Dept. of Computer Science, UCSB

Announcements Homework #5 due today Lab #3 is due on Friday AT NOON! Homework Solutions are now online at: http://cs.ucsb.edu/~zmatni/cs16/hwsolutions/ 10/11/2016 Matni, CS16, Fa16 2

Material: Everything we ve done, incl. up to Th. 10/13 Homework, Labs, Lectures, Textbook Tuesday, 10/18 in this classroom Starts at 2:00pm **SHARP** I will chose where you sit! Duration: 1 hour long Closed book: no calculators, no phones, no computers Only 1 sheet (single-sided) of written notes Must be no bigger than 8.5 x 11 You have to turn it in with the exam You will write your answers on the exam sheet itself. 10/11/2016 Matni, CS16, Fa16 3

Sample Question Multiple Choice Complete the following C++ code that is supposed to print the numbers 2, 3, 4, 5, 6: int c = 0; while ( ) { cout << c+2 << ; c++; } A. c < 7 B. c > 5 C. (c + 2) <= 6 D. (c + 2)!= 7 E. c!= 6 In this example, either C or D can be considered correct answers 10/11/2016 Matni, CS16, Fa16 4

Sample Question Coding Write C++ code that generates a random number between 3 and 7 and then prints out that number in words. For example, the program prints out five if the random number was 5. - Note: When I ask for code, that s different then when I ask for an entire program. 10/11/2016 Matni, CS16, Fa16 5

Sample Question Coding Reproduce the output of this C++ code exactly. int prod(1); for (int m = 1; m <= 6; m++) { prod *= m; m += 2; } cout << Total product is: << prod << endl; 10/11/2016 Matni, CS16, Fa16 6

Lecture Outline Designing Loops in C++ And debugging them Top-Down Design Concepts Pre-Defined Functions in C++ 10/11/2016 Matni, CS16, Fa16 7

Designing Loops What do I need to know? What am I doing inside the loop? What are my initializing statements? What are the conditions for ending the loop? 10/11/2016 Matni, CS16, Fa16 8

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 How can we best implement this code? Let s look at it as a for-loop on the next slide 10/11/2016 Matni, CS16, Fa16 9

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

Repeat "this many times" ProTip: Pseudocode containing the line repeat the following "this many times" is often implemented with a for-loop A for-loop is generally the choice when there is a predetermined number of iterations 10/11/2016 Matni, CS16, Fa16 11

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

Ending a Loop The are four common methods to terminate an input loop: List headed by size When we can determine the size of the list beforehand Ask before iterating Ask if the user wants to continue before each iteration List ended with a sentinel value Using a particular value to signal the end of the list Running out of input Using the eof function to indicate the end of a file 10/11/2016 Matni, CS16, Fa16 9

List Headed By Size The for-loops we have seen provide a natural implementation of the list headed by size method of ending a loop Example: int items; cout << "How many items in the list?"; cin >> items; for(int count = 1; count <= items; count++) { int number; cout << "Enter number " << count; cin >> number; cout << endl; // statements to process the number } 10/11/2016 Matni, CS16, Fa16 14

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

List Ended With a Sentinel Value A while loop is typically used to end a loop using the list ended with a sentinel 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; } Notice that the sentinel value is read, but not processed at the end 10/11/2016 Matni, CS16, Fa16 16

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( ); 10/11/2016 Matni, CS16, Fa16 17

General Methods To Control Loops Three general methods to control any loop Count controlled loops Ask before iterating Exit on flag condition 10/11/2016 Matni, CS16, Fa16 18

Count Controlled Loops Count controlled loops are loops that determine the number of iterations before the loop begins The list headed by size is an example of a count controlled loop for input 10/11/2016 Matni, CS16, Fa16 19

Exit on Flag Condition Loops can be ended when a particular flag condition exists Flag: A variable that changes value to indicate that some event has taken place Examples of exit on a flag condition for input List ended with a sentinel value Running out of input 10/11/2016 Matni, CS16, Fa16 20

Exit on Flag Example Consider this loop to identify a student with a grade of 90 or better and think of how it s logically limited. int n = 1; grade = compute_grade(n); while (grade < 90) { n++; grade = compute_grade(n); } cout << "Student number " << n << " has a score of " << grade << endl; 10/11/2016 Matni, CS16, Fa16 21

The Problem The loop on the previous slide might not stop at the end of the list of students if no student has a grade of 90 or higher It is a good idea to use a second flag to ensure that there are still students to consider The code on the following slide shows a better solution 10/11/2016 Matni, CS16, Fa16 22

The Exit On Flag Solution This code solves the problem of having no student grade at 90 or higher, making use of a flag (the variable n): int n=1; grade = compute_grade(n); while (( grade < 90) && ( n < number_of_students)) { // same as before } if (grade > 90) // same output as before else cout << "No student has a high score."; 10/11/2016 Matni, CS16, Fa16 23

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 10/11/2016 Matni, CS16, Fa16 24

Example of a Nested Loop int grand_total = 0, subtotal = 0, count, next, number_of_reports = 10; for (count = 1; count <= number_of_reports; count++) { cout << "Enter the report of conservationist number << count << endl; cout << Enter the number of eggs in each nest. End list with a negative number.\n cin >> next; while (next >=0) { subtotal = subtotal + next; cin >> next; } // end while loop cout << "Total egg count for conservationist number << count << is << subtotal << endl; grand_total = grand_total + subtotal; } // end for loop cout << Total egg count for all reports = << grand_total << endl; return 0; } // end program

Debugging Loops Common errors involving loops include Off-by-one errors in which the loop executes one too many or one too few times Infinite loops usually result from a mistake in the Boolean expression that controls the loop 10/11/2016 Matni, CS16, Fa16 26

Fixing Off By One Errors Check your comparison: should it be < or <=? Check that the initialization uses the correct value Does the loop handle the zero iterations case? 10/11/2016 Matni, CS16, Fa16 27

Fixing Infinite Loops Check the direction of inequalities: < or >? Test for < or > rather than equality (==) 10/11/2016 Matni, CS16, Fa16 28

More Loop Debugging Tips Be sure that the mistake is really in the loop Trace the variable to observe how the variable changes Tracing a variable is watching its value change during execution. Best way to do this is to insert cout statements to have the program show you the variable at every iteration of the loop. 10/11/2016 Matni, CS16, Fa16 29

Debugging Example The following code is supposed to conclude with the variable product containing the product of the numbers 2 through 5 i.e. 2 x 3 x 4 x 5, which, of course, is 120. What could go wrong?! int next = 2, product = 1; while (next < 5) { next++; product = product * next; } DEMO! Using variable tracing 10/11/2016 Matni, CS16, Fa16 30

Loop Testing Guidelines Every time a program is changed, it should be retested Changing one part may require a change to another Every loop should at least be tested using input to cause: Zero iterations of the loop body One iteration of the loop body One less than the maximum number of iterations The maximum number of iterations 10/11/2016 Matni, CS16, Fa16 31

Starting Over Sometimes it is more efficient to throw out a buggy program and start over! The new program will be easier to read The new program is less likely to be as buggy You may develop a working program faster than if you repair the bad code The lessons learned in the buggy code will help you design a better program faster 10/11/2016 Matni, CS16, Fa16 32

Top Down Design Concept In general, to write a program 1. Develop the algorithm that the program will use 2. Translate the algorithm into the programming language Top Down Design (also called stepwise refinement) 1. Break the algorithm into subtasks 2. Break each subtask into smaller subtasks 3. Eventually the smaller subtasks are trivial to implement in the programming language 10/11/2016 Matni, CS16, Fa16 33

Predefined Functions in C++ 10/11/2016 Matni, CS16, Fa16 34

Predefined Functions C++ comes with built-in libraries of predefined functions Example: sqrt function (found in the library cmath) Computes and returns the square root of a number the_root = sqrt(9.0); The number 9 is called the argument After calculation, the variable the_root will contain 3.0 Can variable the_root be either int or double? 10/11/2016 Matni, CS16, Fa16 35

Function Calls sqrt(9.0) is a function call It invokes a pre-defined function The argument (9), can also be a variable or an expression A function call can be used like any expression bonus = sqrt(sales) / 10; cout << The side of a square with area << area << is << sqrt(area); 10/11/2016 Matni, CS16, Fa16 36

Function Call Syntax Function_Name (Argument_List) Argument_List is a comma separated list: (Argument_1, Argument_2,, Argument_Last) Example: side = sqrt(area); cout << 2.5 to the power 3.0 is << pow(2.5, 3.0); 10/11/2016 Matni, CS16, Fa16 37

Function Libraries Predefined functions are found in libraries The library must be included in a program to make the functions available An include directive tells the compiler which library header file to include. To include the math library containing sqrt(), pow() & others: #include <cmath> Newer standard libraries, such as cmath, also require the directive using namespace std; 10/11/2016 Matni, CS16, Fa16 38

Other Predefined Functions abs(x) --- int value = abs(-8); Returns absolute value of argument x Return value is of type int Argument is of type int Found in the library cmath fabs(x) --- double value = fabs(-8.0); Also returns absolute value of argument x Return value is of type double Argument is of type double Found in the library cmath 10/11/2016 Matni, CS16, Fa16 39

Random Number Generation Not true-random, but pseudo-random numbers. First, seed the random number generator only once #include <cstdlib> #include <ctime> srand(time(0)); time() is a pre-defined function in the ctime library It gives the current system time It s used here because it generates a distinctive enough seed, so that rand() generates a good enough random number. Secondly, use the rand() function, which returns a random integer that is greater than or equal to 0 and less than RAND_MAX (a library-dependent value, but is at least 32767) int r = rand(); 10/11/2016 Matni, CS16, Fa16 40

Random Numbers Use % and + to scale to the number range you want For example to get a random number bounded from 1 to 6 to simulate rolling a six-sided die: int die = (rand() % 6) + 1; 10/11/2016 Matni, CS16, Fa16 41

TO DOs Readings The rest of Chapter 4, of textbook Homework #6 Due on Thursday, 10/13 and submit in class Lab #3 Due Friday, 10/14, at noon 10/11/2016 Matni, CS16, Fa16 42

10/11/2016 Matni, CS16, Fa16 43