What is Iteration? CMPT-101. Recursion. Understanding Recursion. The Function Header and Documentation. Recursively Adding Numbers

Similar documents
Unit 7. 'while' Loops

LECTURE 5 Control Structures Part 2

Intro. Scheme Basics. scm> 5 5. scm>

C++ Reference NYU Digital Electronics Lab Fall 2016

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

Repetition Through Recursion

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

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

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

Programming in C++ PART 2

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

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

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

1 Unit 8 'for' Loops

To become familiar with array manipulation, searching, and sorting.

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2).

Working with recursion

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

Module 4: Decision-making and forming loops

Fundamentals of Programming Session 4

n! = 1 * 2 * 3 * 4 * * (n-1) * n

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

Introduction to C++ Lecture Set 2. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 1

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Loop structures and booleans

Why Is Repetition Needed?

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

Animations that make decisions

Lab 6 Vectors and functions

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

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

REPETITION CONTROL STRUCTURE LOGO

RECURSION. Many Slides from Ken Birman, Cornell University

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

Learning Recursion. Recursion [ Why is it important?] ~7 easy marks in Exam Paper. Step 1. Understand Code. Step 2. Understand Execution

EECS 183. Week 3 - Diana Gage. www-personal.umich.edu/ ~drgage

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++.

Pointers in C/C++ 1 Memory Addresses 2

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

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

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

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

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

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

Looping. Arizona State University 1

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Introduction. C provides two styles of flow control:

Text Input and Conditionals

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

6.001 Notes: Section 4.1

CIS 130 Exam #2 Review Suggestions

do { statements } while (condition);

Chapter 1 - What s in a program?

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

CMPT 120 Introduction To Computing Science And Programming I. Pseudocode. Summer 2012 Instructor: Hassan Khosravi

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

QUIZ. What is wrong with this code that uses default arguments?

Ch. 12: Operator Overloading

Condition Controlled Loops. Introduction to Programming - Python

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

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

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Chapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup.

CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too)

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

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Chapter 5 Errors. Bjarne Stroustrup

More About WHILE Loops

SFU CMPT Topic: Control Statements

Chapter Goals. Contents LOOPS

pointers + memory double x; string a; int x; main overhead int y; main overhead

COMP322 - Introduction to C++ Lecture 01 - Introduction

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

Shorthand for values: variables

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

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Module 5: Lists. Readings: HtDP, Sections 9, 10.

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Discussion 1H Notes (Week 2, 4/8) TA: Brian Choi Section Webpage:

LOOPS. Repetition using the while statement

Variables and Constants

Algorithm Design and Recursion. Search and Sort Algorithms

Iteration Preview of Coming Attractions The Need to Get Your Act Together A Process for Developing While Statements

CS112 Lecture: Loops

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

Loops. When to Use Loops

Outline. Introduction. 2 Proof of Correctness. 3 Final Notes. Precondition P 1 : Inputs include

12 Macros. Localmake. is an abbreviation for the two instructions. localmake "fred 87. local "fred make "fred 87

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.

Flow Control: Branches and loops

CS61A Notes Week 1A: Basics, order of evaluation, special forms, recursion

CS11 Introduction to C++ Fall Lecture 1

CS150 Intro to CS I. Fall Fall 2017 CS150 - Intro to CS I 1

CS 137 Part 2. Loops, Functions, Recursion, Arrays. September 22nd, 2017

Chapter 3 Objects, types, and values. Bjarne Stroustrup

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

Transcription:

What is Iteration? CMPT-101 Week 6 Iteration, Iteration, Iteration, Iteration, Iteration, Iteration,... To iterate means to do the same thing again and again and again and again... There are two primary ways to repeatedly execute a block of code: recursion loops Sometimes iteration is implies not recursive, but we ll use it in a more general sense. Recursion Recursion happens when a function calls itself a function that calls itself is recursive Recursion is elegant and powerful often inefficient in practice tricky to understand at first But sometimes it s the perfect tool for the job Understanding Recursion To understand recursion, you must first understand recursion. Recursively Adding Numbers Problem: Write a function that recursively calculates the sum of the ints from lo to hi (inclusive); assume lo is less than or equal to hi For example: sum(5,10) returns 45, because 5+6+7+8+9+10 = 45; sum(75,75) is 75; sum(-5,5) is 0 The Function Header and Documentation /* PURPOSE: adds ints from lo to hi RECEIVES: lo - the smallest int in the range hi - the highest int in the range (cannot be less than lo) RETURNS: sum of all ints from lo to hi (inclusive) */

No Mention of Recursion Yet! Notice that the function documentation doesn t say anything about recursion How the sum is calculated is an implementation detail Remember, the ordinary user of this function will be unconcerned with the implementation details unless the function works poorly! The Recursive Idea Look at an example: sum(5,10) 5 + 6 + 7 + 8 + 9 + 10 = sum(6,10) This shows that sum(5,10) = 5 + sum(6,10) sum(5,10) = 5 + sum(6,10) A Recursive Rule sum(6,10) = 6 + sum(7,10) sum(7,10) = 7 + sum(8,10) sum(8,10) = 8 + sum(9,10) sum(9,10) = 9 + sum(10,10) sum(10,10) = 10 base case From these examples, you can infer a general rule: sum(lo,hi) = lo + sum(lo+1,hi) sum is defined in terms of a (simpler) call to itself! This rule is not correct, since it doesn t tell you want to do when lo == hi, e.g. this rule doesn t tell you how to calculate sum(75,75) or sum(10,10), etc. A Recursive Rule Here s the completely correct rule: sum(lo,hi) = sum(lo,hi) = lo, if lo == hi sum(lo,hi) = lo + sum(lo+1,hi), if lo < hi Note that this rule is undefined when lo is greater than hi. Check for this case using an assert statement. A Recursive Function We can translate the previous recursive rule into a recursive C++ function quite straightforwardly header documentation is here... if (lo == hi) // base case return lo; else // recursive case return lo + sum(lo + 1,hi); Trace the function call sum(1,4) by hand to see how it works

Understanding Recursion Most programmers initially find recursion to be tricky to understand It doesn t seem to do anything --- it appears to work almost by magic! You ll learn more about recursion in later courses, e.g. CMPT-201 Many mathematical definitions are naturally recursive, so recursion makes implementing such functions almost trivial Understanding Recursion To understand recursion, try this: trace examples by hand implement them in C++ compare actual output to your hand-traced results do this with as many simple examples as you can find! Loops while Loops are Cool The other major way to repeatedly execute a code block is to use a loop C++ has three main looping constructs while loops do/while loops for loops this codeblock is the loop body while (cond) The loop terminates when cond is false cond is a bool expression before each execution of the body, cond is tested to make sure it s true What Does this Code Do? What Does this Code Do? int sum = 0; while (num >= 0) sum += num; // same as: sum = sum + num cout << \n << sum; entering any negative number causes this loop to terminate int sum = 0; while (num >= 0) sum += num; // shorthand for: sum = sum + num // while cout << \n << sum; typed in by the user Note: an actual program should have more user-friendly prompts and instructions, but on slides space is precious so I ve left those things out. 4 3 6 5 0 0 3-1 21

What Does this Code Do? int sum = 0; while (num >= 0) sum += num; // shorthand for: sum = sum + num // while cout << \n << sum; Answer: it reads in ints and adds them to sum, until the user enters a negative number, which terminates the loop. Then the sum of all the positive numbers is printed. Another Example Problem: Write a program that generates this output: Bold indicates user input 4-3 2 2 4-93 -1 0 You entered 7 numbers: 3 negative 4 positive 0 indicates the end of the input int neg = 0, pos = 0; while (num!= 0) if (num < 0) ++neg; else ++pos; Another Example this loop terminates when the user enters a 0 for each repetition of the loop, either neg or pos is incremented --- but not both cout << "You entered " << (neg + pos) << " numbers\n" << neg << " negative\n" << pos << " positive"; initialize variables get first item while (item is not a terminator) do process item get next item end while output results A Loop Idiom the first item is gotten outside the loop because it might be a terminating item, and in that case we don t want the loop body to execute even once You can use this as a template to help you design your own loops, although it doesn t apply in all cases. Notes on while Loops A while loop s body is executed 0 or more times the condition for the while loop is always tested before the loop body is executed You don t need to know ahead of time how many times the loop will execute Rule of thumb: if you re unsure about what kind of loop to use, use a while loop the body of a do/while is always executed once before checking cond do/while Loops Rock cond is a bool expression tested at the end of the loop after the body is executed do while (cond); After the body is executed, cond is checked: if it s true, the loop body is executed again; if it s false, the loop terminates

Example do/while Loop do cout << "Enter a non-zero int: "; while (num == 0); cout << "Thanks!"; Enter a non-zero int: 0 Enter a non-zero int: 0 this keeps prompting the user to enter a non-zero int for as long as the user keeps entering 0s! Loop Notes Always try to pick the best loop However, for practical reasons, many C++ programmers avoid the use of do/while loops... Enter a non-zero int: -1 Thanks! A Quote From Stroustrup for-loops In my experience, the [do/while loop] is a source of errors and confusion. The reason is that its body is always executed once before the condition is evaluated. However, for the body to work correctly, something very much like the condition must hold even the first time through. More often than I would have guessed, I found that condition not to hold as expected, either when the program was first written and tested or later after the code preceding it has been modified. I also prefer the condition up front where I can see it. Consequently, I tend to avoid [do/while loops]. --- Bjarne Stroustup, The C++ Programming Language, 3rd Edition, p. 137 In C++, for-loops are a shorthand for a commonly used form of while loop init; while (cond) update; for(init; cond; update) these code fragments do the same thing An Example of a for Loop Compared to a while Loop int total = 0; return total; Initialization happens at the start of the loop, before the body is executed This loop causes i to take on the values lo, lo+1, lo+2,..., hi in succession The update happens after the loop body has been executed This condition is always checked at the top of the loop (and after i is initialized) equivalent code int total = 0; return total; the for-loop version is generally considered neater and shorter; plus it puts all the loop control information in one place int total = 0; int i = lo; while (i <= hi) ++i; // while return total;

for-loop Notes Use for-loops for counting loops, e.g. loops where you know ahead of time how many times they ll execute loops that need an index variable incremented throughout the loop s iterations Don t write strange, difficult to understand for loops use while loops for complex loops for-loop Notes cout << i; // Oops! Error! this is an error in modern C++ compilers because i only lives inside the body and header of the for-loop this for-loop s body has only one statement, so no brackets are necessary for-loop Notes cout << i; // okay in old C++ Beware: in older C++ compilers, this is legal! That is, in older C++ compilers, the scope of i in a for-loop extends past the end of the body