Lecture 04 More Iteration, Nested Loops. Meet UTA Jarrett s dog Greta, lying in her nest

Size: px
Start display at page:

Download "Lecture 04 More Iteration, Nested Loops. Meet UTA Jarrett s dog Greta, lying in her nest"

Transcription

1 Lecture 4 More Iteration, Nested Loops Meet UTA Jarrett s dog Greta, lying in her nest

2 Indefinite Loops Rest Chase tail Got tail! Almost got it... Based in part on notes from the CS-for-All curriculum developed at Harvey Mudd College

3 So far: Two Types of for Loops vals[] vals[] vals[] vals[3] vals = [3, 5, 7, 7] vals = [3, 5, 7, 7] 3 x i def sum(vals): result = for x in vals: result += x return result element-based loop def sum(vals): result = for i in range(len(vals)): result += vals[i] return result index-based loop Both are examples of definite loops (i.e., fixed number of iterations) 3

4 Indefinite Loops Use an indefinite loop when the # of repetitions you need is: not obvious or known impossible to determine before the loop begins, e.g., Finding an element Computing an estimate up to some error bound Playing a game of rock, paper, scissors (as opposed to one round) Toy problem: print_multiples(n, bound) should print all multiples of n that are less than bound output for print_multiples(9, ):

5 Rock, Paper, Scissors, Lizard, Spock 5

6 Indefinite Loop for Printing Multiples while loops are how you code indefinite loops in Python: def print_multiples(n, bound): mult = n while mult < bound: print(mult, end=" ") mult = mult + n print() 6

7 while Loops while <loop test>: <body of the loop> loop test Steps:. evaluate the loop test (a boolean expression). if it's True, execute the statements in the body, and go back to step 3. if it's False, skip the statements in the body and go to the statement after the loop False True 7

8 Tracing a while Loop Let's trace the loop for print_multiples(5, 7): mult = n while mult < bound: print(mult, end=' ') mult = mult + n print() mult < bound output thus far n bound Prints everything on the same line with spaces in between! Neat! mult 8

9 Tracing a while Loop Let's trace the loop for print_multiples(5, 7): mult = n while mult < bound: print(mult, end=' ') mult = mult + n print() mult < bound output thus far n bound mult 5 5 < 7 (True) < 7 (True) < 7 (True) < 7 (True) < 7 (False) so we exit the loop and print() 9

10 Important! In general, a while loop's test includes a key "loop variable". We need to update that loop variable in the body of the loop. Failing to update it can produce an infinite loop! Recall the loop in print_multiples: mult = n while mult < bound: print(mult, end=' ') mult = mult + n What is the loop variable? Where is it updated?

11 Important! In general, a while loop's test includes a key "loop variable". We need to update that loop variable in the body of the loop. Failing to update it can produce an infinite loop! Recall the loop in print_multiples: mult = n while mult < bound: print(mult, end=' ') mult = mult + n What is the loop variable? mult Where is it updated? In the body of the loop

12 Important! In general, a while loop's test includes a key "loop variable". We need to update that loop variable in the body of the loop. Failing to update it can produce an infinite loop! Showing every iteration makes progress towards making the while loop condition false is one way to show a while loop will terminate

13 Factorial Using a while Loop We don't need an indefinite loop, but we can still use while! def fac(n): result = while n > : result *= n return result # what do we need here? Let's trace fac(4): n n > result 3

14 Factorial Using a while Loop We don't need an indefinite loop, but we can still use while! def fac(n): result = while n > : result *= n n = n return result Let's trace fac(4): n n > result 4

15 Factorial Using a while Loop We don't need an indefinite loop, but we can still use while! def fac(n): result = while n > : result *= n n = n return result Let's trace fac(4): n n > result *4 = 4 4*3 = * = 4 4* = 4 4 > (True) 3 > (True) > (True) > (True) > (False) so we exit the loop and return 4 5

16 Factorial Four Ways! recursion map def fac(n): if n == : return else: rest = fac(n-) return n * rest Mo re on the se lat er! def fac(n): return reduce(lambda x,y : x*y,\ range(,max(,n+))) for loop def fac(n): result = for x in range(, n+): result *= x return result while loop def fac(n): result = while n > : result *= n n = n - return result 6

17 Extreme Looping! What does this code do? print('it keeps') while True: print('going and') print('phew! Done!') 7

18 Extreme Looping! What does this code do? print('it keeps') while True: print('going and') print('phew! Done!') # never gets here! An infinite loop! Use Ctrl-C to stop a program inside python Use W-F to stop a program in PyCharm 8

19 Breaking Out of A Loop import random while True: print('help!') if random.choice(range()) == : break print('let me out!') print('at last!') What are the final two lines that are printed? 9

20 Breaking Out of A Loop import random while True: print('help!') if random.choice(range()) == : break print('let me out!') print('at last!') What are the final two lines that are printed? Help! At last! How could we count the number of repetitions?

21 Counting the Number of Repetitions import random count = while True: print('help!') if random.choice(range()) == : break print('let me out!') count += print('at last! It took', count, 'tries to escape!')

22 Important! In general, a while loop's test includes a key "loop variable". We need to update that loop variable in the body of the loop. Failing to update it can produce an infinite loop! Can rely on a statistical argument (e.g., rock, paper, scissors) Counting the number of iterations and exiting after a maximum has been reached is a safer way to loop indefinitely

23 Counting the Number of Repetitions import random count = while count<=5: print('help!') if random.choice(range()) == : break print('let me out!') count += print('at last! It took', count, 'tries to escape!') 3

24 How many values does this loop print? a = 4 while a > : a = a // print(a - ) A. B. C. D. E. a > a prints none of these 4

25 How many values does this loop print? a = 4 while a > : a = a // print(a - ) A. B. C. D. E. a > True True True True False a 4 5 prints none of these 5

26 For what inputs does this function return True? def mystery(n): while n!= : if n %!= : return False n = n // return True A. B. C. D. E. Try tracing these two cases: mystery() mystery(8) n n 8 odd numbers even numbers multiples of 4 powers of none of these 6

27 For what inputs does this function return True? def mystery(n): while n!= : if n %!= : return False n = n // return True A. B. C. D. E. Try tracing these two cases: mystery() mystery(8) n n False True odd numbers even numbers multiples of 4 powers of none of these 7

28 Wesley says it s break time so it s break time 8

29 Nested Loops! for y in range(84): for m in range(): for d in range(f(m,y)): for h in range(4): for mn in range(6): for s in range(6): tick() 9

30 Nested Loops! Nested Loops are loops where a loop appears inside the body of another loop. The loop inside the body is called the inner loop. The other is called the outer loop. The inner loop completes all passes for a single pass of the outer loop This is very useful for many types of algorithms, especially with data that has more than one dimension. 3

31 Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) inner loop outer loop 3

32 Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) #,, #,,, 3 3

33 Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) #,, #,,, 3 33

34 Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) #,, #,,, 3 34

35 Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) #,, #,,,

36 Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) #,, #,,,

37 Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) #,, #,,,

38 Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) print('---') inner loop outer loop 38

39 Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) print('---') inner loop outer loop

40 How many lines are printed? for i in range(5): for j in range(7): print(i, j) A. B. C. D. E

41 How many lines are printed? for i in range(5): for j in range(7): print(i, j) A. B. C. D. E = 5*7 executions of inner code block full output:

42 Tracing a Nested for Loop for i in range(5): for j in range(i): print(i, j) i range(i) j # [,,,3,4] value printed 4

43 Tracing a Nested for Loop for i in range(5): for j in range(i): print(i, j) # [,,,3,4] i range(i) [] [] [,] 3 [,,] 4 [,,,3] value printed nothing (we exit the inner loop) full output: j none 3 43

44 Second Example: Tracing a Nested for Loop for i in range(4): for j in range(i, 3): print(i, j) print(j) i range(i, 3) j value printed 44

45 Second Example: Tracing a Nested for Loop for i in range(4): # [,,, 3] for j in range(i, 3): print(i, j) print(j) # would go here next i 3 range(i, 3) [,, ] j value printed [, ] [] [], so body of inner loop doesn't execute full output: 45

46 Side Note: Staying on the Same Line When Printing By default, print puts an invisible newline character at the end of whatever it prints. causes separate prints to print on different lines Example: What does this output? for i in range(7): print(i * 5)

47 Staying on the Same Line When Printing (cont.) To get separate prints to print on the same line, we can replace the newline with something else. Examples: for i in range(7): print(i * 5, end=' ') for i in range(7): print(i * 5, end=','),5,,5,,5,3, 47

48 Printing Patterns for row in range(3): for col in range(4): print('#', end=' ') print() # go to next line col row 3 # # # # # # # # # # # # 48 48

49 Fill in the Blank # for row in range(3): for col in range(6): print(, end=' ') print() # go to next line row col

50 Fill in the Blank # for row in range(3): for col in range(6): print(col, end=' ') print() # go to next line row col

51 Fill in the Blank # for row in range(3): for col in range(6): print(, end=' ') print() # go to next line row col 5 5

52 Fill in the Blank # for row in range(3): for col in range(6): print(row, end=' ') print() # go to next line row col 5 5

53 What is needed in the blanks to get this pattern? for row in range(5): for col in : print(, end=' ') print() # go to next line first blank A. B. C. D. E second blank range(row) row range(row) col range(5 - row) row range(5 - row) col none of the above 53 53

54 What is needed in the blanks to get this pattern? for row in range(5): for col in : print(, end=' ') print() # go to next line first blank A. B. C. D. E second blank range(row) row range(row) col range(5 - row) row range(5 - row) col none of the above 54 54

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen 1 Truth Last lecture we learned about the int, float, and string types. Another very important object type in Python is the boolean type. The two reserved keywords True and False are values with type boolean.

More information

LOOPS. Repetition using the while statement

LOOPS. Repetition using the while statement 1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

More information

Textbook. Topic 5: Repetition. Types of Loops. Repetition

Textbook. Topic 5: Repetition. Types of Loops. Repetition Textbook Topic 5: Repetition Are you saying that I am redundant? That I repeat myself? That I say the same thing over and over again? Strongly Recommended Exercises The Python Workbook: 64, 69, 74, and

More information

Module 06. Topics: Iterative structure in Python Readings: ThinkP 7. CS116 Spring : Iteration

Module 06. Topics: Iterative structure in Python Readings: ThinkP 7. CS116 Spring : Iteration Module 06 Topics: Iterative structure in Python Readings: ThinkP 7 1 In Python, repetition can be recursive def count_down_rec(x): ''' Produces the list [x, x-1, x-2,..., 1,0] count_down:nat->(listof Nat)'''

More information

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board) Chapter 5 : Informatics practices Class XI ( As per CBSE Board) Conditional & Looping Constructs Control Statements Control statements are used to control the flow of execution depending upon the specified

More information

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley Lecture 11: while loops CS1068+ Introductory Programming in Python Dr Kieran T. Herley Python s while loop. Summary Department of Computer Science University College Cork 2017-2018 KH (24/10/17) Lecture

More information

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical Recommended Readings Chapter 5 Topic 5: Repetition Are you saying that I am redundant? That I repeat myself? That I say the same thing over and over again? 1 2 Repetition So far, we have learned How to

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala Loops and Conditionals HORT 59000 Lecture 11 Instructor: Kranthi Varala Relational Operators These operators compare the value of two expressions and returns a Boolean value. Beware of comparing across

More information

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

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1 Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1 Chapter 6 : (Control Structure- Repetition) Using Decrement or Increment While Loop Do-While Loop FOR Loop Nested Loop

More information

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters. CS 61A Spring 2019 Guerrilla Section 5: April 20, 2019 1 Interpreters 1.1 Determine the number of calls to scheme eval and the number of calls to scheme apply for the following expressions. > (+ 1 2) 3

More information

Chapter 2: Understanding Structure. Programming Logic and Design, 4 th Edition Introductory

Chapter 2: Understanding Structure. Programming Logic and Design, 4 th Edition Introductory Chapter 2: Understanding Structure Programming Logic and Design, 4 th Edition Introductory Objectives After studying Chapter 2, you should be able to: Describe the features of unstructured spaghetti code

More information

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

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator. Chapter 5: Looping 5.1 The Increment and Decrement Operators Copyright 2009 Pearson Education, Inc. Copyright Publishing as Pearson 2009 Addison-Wesley Pearson Education, Inc. Publishing as Pearson Addison-Wesley

More information

Intro. Speed V Growth

Intro. Speed V Growth Intro Good code is two things. It's elegant, and it's fast. In other words, we got a need for speed. We want to find out what's fast, what's slow, and what we can optimize. First, we'll take a tour of

More information

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

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

More information

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

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ PROGRAM CONTROL Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Repetition Statement for while do.. while break and continue

More information

Announcements. Project 5 is on the street. Second part is essay questions for CoS teaming requirements.

Announcements. Project 5 is on the street. Second part is essay questions for CoS teaming requirements. Announcements Project 5 is on the street. Second part is essay questions for CoS teaming requirements. The first part you do as a team The CoS essay gets individually answered and has separate submission

More information

Problem 1. Remove consecutive duplicates (6 points, 11 mintues)

Problem 1. Remove consecutive duplicates (6 points, 11 mintues) Problem 1. Remove consecutive duplicates (6 points, 11 mintues) CS3 Fall 04 Midterm 2 Consider a function remove-conseq-dups that takes a sentence and returns a sentence in which any occurrences of a word

More information

Conditionals and Recursion. Python Part 4

Conditionals and Recursion. Python Part 4 Conditionals and Recursion Python Part 4 Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print (remainder) 1 Boolean expressions An expression that

More information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 Announcements Check the calendar on the course webpage regularly for updates on tutorials and office hours.

More information

Flow Control: Branches and loops

Flow Control: Branches and loops Flow Control: Branches and loops In this context flow control refers to controlling the flow of the execution of your program that is, which instructions will get carried out and in what order. In the

More information

Lecture 7 Tao Wang 1

Lecture 7 Tao Wang 1 Lecture 7 Tao Wang 1 Objectives In this chapter, you will learn about: Interactive loop break and continue do-while for loop Common programming errors Scientists, Third Edition 2 while Loops while statement

More information

Repetition Structures

Repetition Structures Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

More information

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

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

More information

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Python review. 1 Python basics. References. CS 234 Naomi Nishimura Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not

More information

Lab 5 - Repetition. September 26, 2018

Lab 5 - Repetition. September 26, 2018 Lab 5 - Repetition September 26, 2018 1 ME 30 Lab 5 - Repetition ME 30 ReDev Team Description and Summary: This lab introduces the programming concept of repetition, also called looping, where some operations

More information

Chapter 5: Loops and Files

Chapter 5: Loops and Files Chapter 5: Loops and Files 5.1 The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1;

More information

Control of Flow. There are several Python expressions that control the flow of a program. All of them make use of Boolean conditional tests.

Control of Flow. There are several Python expressions that control the flow of a program. All of them make use of Boolean conditional tests. Control of Flow There are several Python expressions that control the flow of a program. All of them make use of Boolean conditional tests. If Statements While Loops Assert Statements 6 If Statements if

More information

Practical Questions CSCA48 Week 6

Practical Questions CSCA48 Week 6 Practical Questions CSCA48 Week 6 Trace the following functions with a variety of input, and describe their functionality in a single sentence. 1. def mystery(n): if n == 4: result = n result = 2 * mystery(n+1)

More information

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

L o o p s. for(initializing expression; control expression; step expression) { one or more statements } L o o p s Objective #1: Explain the importance of loops in programs. In order to write a non trivial computer program, you almost always need to use one or more loops. Loops allow your program to repeat

More information

Introduction to Python (All the Basic Stuff)

Introduction to Python (All the Basic Stuff) Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions

More information

Test #2 October 8, 2015

Test #2 October 8, 2015 CPSC 1040 Name: Test #2 October 8, 2015 Closed notes, closed laptop, calculators OK. Please use a pencil. 100 points, 5 point bonus. Maximum score 105. Weight of each section in parentheses. If you need

More information

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

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x ); Chapter 4 Loops Sections Pages Review Questions Programming Exercises 4.1 4.7, 4.9 4.10 104 117, 122 128 2 9, 11 13,15 16,18 19,21 2,4,6,8,10,12,14,18,20,24,26,28,30,38 Loops Loops are used to make a program

More information

logical operators and else-if statements

logical operators and else-if statements logical operators and else-if statements Lecture 5 Step 0: TODAY open http://localhost:3000/close -- if this errors that's OK / expected Step 1: Open VSCode and its Integrated Terminal Step 2: npm run

More information

Chapter 5 Conditional and Iterative Statements (Part-II) To carry out repetitive task, python provides following iterative/looping statements:

Chapter 5 Conditional and Iterative Statements (Part-II) To carry out repetitive task, python provides following iterative/looping statements: Chapter 5 Conditional and Iterative Statements (Part-II) Iterative Statements To carry out repetitive task, python provides following iterative/looping statements: 1. Conditional loop while (condition

More information

(Python) Chapter 3: Repetition

(Python) Chapter 3: Repetition (Python) Chapter 3: Repetition 3.1 while loop Motivation Using our current set of tools, repeating a simple statement many times is tedious. The only item we can currently repeat easily is printing the

More information

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment Iteration 6.1. Multiple assignment As you may have discovered, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop

More information

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control Chapter 2 Control, Quick Overview Control Selection Selection Selection is how programs make choices, and it is the process of making choices that provides a lot of the power of computing 1 Python if statement

More information

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

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

The story so far. Elements of Programming Languages. While-programs. Mutable vs. immutable

The story so far. Elements of Programming Languages. While-programs. Mutable vs. immutable The story so far Elements of Programming Languages Lecture 12: Imperative programming James Cheney University of Edinburgh November 4, 2016 So far we ve mostly considered pure computations. Once a variable

More information

CS100: CPADS. Decisions. David Babcock / Don Hake Department of Physical Sciences York College of Pennsylvania

CS100: CPADS. Decisions. David Babcock / Don Hake Department of Physical Sciences York College of Pennsylvania CS100: CPADS Decisions David Babcock / Don Hake Department of Physical Sciences York College of Pennsylvania James Moscola Decisions Just like a human, programs need to make decisions - Should turtle turn

More information

How many ways to make 50 cents? first-denomination Solution. CS61A Lecture 5. count-change. cc base cases. How many have you figured out?

How many ways to make 50 cents? first-denomination Solution. CS61A Lecture 5. count-change. cc base cases. How many have you figured out? 6/6/ CS6A Lecture -6-7 Colleen Lewis How many ways to make cents? first-denomination Solution (define (first-denomination kinds-of-coins) ((= kinds-of-coins ) ) ((= kinds-of-coins ) ) ((= kinds-of-coins

More information

Control Flow: Branching booleans and selection statements CS GMU

Control Flow: Branching booleans and selection statements CS GMU Control Flow: Branching booleans and selection statements CS 112 @ GMU Topics booleans selection statements: if if-else if-elif(s) if-elif(s)-else flow charts 2 Booleans Booleans - examples Booleans are

More information

Scope of this lecture. Repetition For loops While loops

Scope of this lecture. Repetition For loops While loops REPETITION CITS1001 2 Scope of this lecture Repetition For loops While loops Repetition Computers are good at repetition We have already seen the for each loop The for loop is a more general loop form

More information

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

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013 While Loops A loop performs an iteration or repetition A while loop is the simplest form of a loop Occurs when a condition is true CHAPTER 5: LOOP STRUCTURES Introduction to Computer Science Using Ruby

More information

Lecture 10: Recursion vs Iteration

Lecture 10: Recursion vs Iteration cs2010: algorithms and data structures Lecture 10: Recursion vs Iteration Vasileios Koutavas School of Computer Science and Statistics Trinity College Dublin how methods execute Call stack: is a stack

More information

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 2 Control 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Control: A Quick Overview 2 Selection

More information

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute Module 02 Lecture - 45 Memoization Let us continue our discussion of inductive definitions. (Refer Slide Time: 00:05)

More information

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

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

More information

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

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #16 Loops: Matrix Using Nested for Loop In this section, we will use the, for loop to code of the matrix problem.

More information

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn CPS109 Course Notes 6 Alexander Ferworn Unrelated Facts Worth Remembering Use metaphors to understand issues and explain them to others. Look up what metaphor means. Table of Contents Contents 1 ITERATION...

More information

Quiz Determine the output of the following program:

Quiz Determine the output of the following program: Quiz Determine the output of the following program: 1 Structured Programming Using C++ Lecture 4 : Loops & Iterations Dr. Amal Khalifa Dr. Amal Khalifa - Spring 2012 1 Lecture Contents: Loops While do-while

More information

CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 5&6: Loops Lecture Contents Why loops?? While loops for loops do while loops Nested control structures Motivation Suppose that you need

More information

CS3 Midterm 2 Standards and Solutions

CS3 Midterm 2 Standards and Solutions CS3 Midterm 2 Standards and Solutions Spring 2007 16 14 12 10 8 6 4 2 0 Std. Dev = 5.43 Mean = 18.3 N = 90.00 2.0 6.0 10.0 14.0 18.0 22.0 26.0 30.0 4.0 8.0 12.0 16.0 20.0 24.0 28.0 scaled Problem 1. Roman

More information

Lecture Transcript While and Do While Statements in C++

Lecture Transcript While and Do While Statements in C++ Lecture Transcript While and Do While Statements in C++ Hello and welcome back. In this lecture we are going to look at the while and do...while iteration statements in C++. Here is a quick recap of some

More information

Iteration Part 1. Motivation for iteration. How does a for loop work? Execution model of a for loop. What is Iteration?

Iteration Part 1. Motivation for iteration. How does a for loop work? Execution model of a for loop. What is Iteration? Iteration Part 1 Motivation for iteration Display time until no more time left Iteration is a problemsolving strategy found in many situations. Keep coding until all test cases passed CS111 Computer Programming

More information

Repetition Structures II

Repetition Structures II Lecture 9 Repetition Structures II For and do-while loops CptS 121 Summer 2016 Armen Abnousi Types of Control Structures Sequential All programs that we have written so far The statements inside a pair

More information

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators CS 61A Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions 1 Control Control structures direct the flow of logic in a program. For example, conditionals (if-elif-else) allow a program

More information

Decision Making in C

Decision Making in C Decision Making in C Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed

More information

Execution order. main()

Execution order. main() Functions Execution order When you load and run a Python module (file), the statements and definitions in the file are executed in the order in which they occur Executing a def defines a function, it doesn

More information

4.2 Function definitions the basics

4.2 Function definitions the basics 4.2. FUNCTION DEFINITIONS THE BASICS 89 4.2 Function definitions the basics There are three questions you must answer before you can write a function definition: What will the function do? What inputs

More information

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

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code. Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code. The Need For Repetition (Loops) Writing out a simple counting program (1

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 8 Part 1 The Department of Computer Science Chapter 8 Loop Structures and Booleans 2 Objectives To understand the concepts

More information

Condition Controlled Loops. Introduction to Programming - Python

Condition Controlled Loops. Introduction to Programming - Python Condition Controlled Loops Introduction to Programming - Python Decision Structures Review Programming Challenge: Review Ask the user for a number from 1 to 7. Tell the user which day of the week was selected!

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 06 / 04 / 2015 Instructor: Michael Eckmann Today s Topics Questions / comments? Calling methods (noting parameter(s) and their types, as well as the return type)

More information

Introduction to CS. Welcome to CS 5! 1 handout. We don't have words strong enough to describe this class. Everyone will get out of this course a lot!

Introduction to CS. Welcome to CS 5! 1 handout. We don't have words strong enough to describe this class. Everyone will get out of this course a lot! Welcome to CS 5! Introduction to CS Wally Wart, a protrusive advocate of concrete computing We don't have words strong enough to describe this class. -US News and Course Report Everyone will get out of

More information

CS302: Self Check Quiz 2

CS302: Self Check Quiz 2 CS302: Self Check Quiz 2 name: Part I True or False For these questions, is the statement true or false? Assume the statements are about the Java programming language. 1.) The result of an expression with

More information

CSE200 Lecture 6: RECURSION

CSE200 Lecture 6: RECURSION Table of Contents Review of functions (using factorial example)... 1 Recursion... 1 Step by step run through of recursive factorial... 2 Recursion vs. iteration (for and while loops)... 3 Helper functions:...

More information

Chapter 8. Statement-Level Control Structures

Chapter 8. Statement-Level Control Structures Chapter 8 Statement-Level Control Structures Levels of Control Flow Within expressions Among program units Among program statements Copyright 2012 Addison-Wesley. All rights reserved. 1-2 Control Structure

More information

Loop structures and booleans

Loop structures and booleans Loop structures and booleans Michael Mandel Lecture 7 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture07final.ipynb

More information

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming Lecture Loops && Booleans Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda (In-)definite loops (for/while) Patterns: interactive loop and sentinel loop Solve problems using (possibly

More information

Iterative Statements. Iterative Statements: Examples. Counter-Controlled Loops. ICOM 4036 Programming Languages Statement-Level Control Structure

Iterative Statements. Iterative Statements: Examples. Counter-Controlled Loops. ICOM 4036 Programming Languages Statement-Level Control Structure ICOM 4036 Programming Languages Statement-Level Control Structure Selection Statement Iterative Statements Unconditional Branching Guarded Commands This lecture covers review questions 8-16 This lecture

More information

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

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1 Chapter 5: Loops and Files The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; ++ can be used before (prefix) or after (postfix)

More information

Fundamentals of Programming Session 13

Fundamentals of Programming Session 13 Fundamentals of Programming Session 13 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Lecture 02 Making Decisions: Conditional Execution

Lecture 02 Making Decisions: Conditional Execution Lecture 02 Making Decisions: Conditional Execution 1 Flow of Control Flow of control = order in which statements are executed By default, a program's statements are executed sequentially, from top to bottom.

More information

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi CMPT 120 Control Structures in Python Summer 2012 Instructor: Hassan Khosravi The If statement The most common way to make decisions in Python is by using the if statement. The if statement allows you

More information

CS1150 Principles of Computer Science Loops (Part II)

CS1150 Principles of Computer Science Loops (Part II) CS1150 Principles of Computer Science Loops (Part II) Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Review Is this an infinite loop? Why (not)?

More information

LECTURE 5 Control Structures Part 2

LECTURE 5 Control Structures Part 2 LECTURE 5 Control Structures Part 2 REPETITION STATEMENTS Repetition statements are called loops, and are used to repeat the same code multiple times in succession. The number of repetitions is based on

More information

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

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018. Week 2 Branching & Looping Gaddis: Chapters 4 & 5 CS 5301 Spring 2018 Jill Seaman 1 Relational Operators l relational operators (result is bool): == Equal to (do not use =)!= Not equal to > Greater than

More information

CSSE 120 Introduction to Software Development Practice for Test 1 paper-and-pencil part Page 1 of 6

CSSE 120 Introduction to Software Development Practice for Test 1 paper-and-pencil part Page 1 of 6 CSSE 120 Introduction to Software Development Practice for Test 1 paper-and-pencil part Page 1 of 6 Name: Use this quiz to help you prepare for the Paper-and-Pencil portion of Test 1. Complete it electronically

More information

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently. The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without

More information

Loops. Upsorn Praphamontripong. CS 1110/CS 1111 Introduction to Programming Spring 2018

Loops. Upsorn Praphamontripong. CS 1110/CS 1111 Introduction to Programming Spring 2018 Loops Upsorn Praphamontripong CS 1110/CS 1111 Introduction to Programming Spring 2018 Walking and Shaking if Given a list of Python experts in this room Upsorn-bot wants to shake hands the Python experts

More information

Introduction to Recursion

Introduction to Recursion Recursive Patterns Introduction to Recursion CS Computer Programming Department of Computer Science Wellesley College Reminder: DCG What is Recursion? 8- Recursion is an instance of divide-conquer-glue

More information

Lecture #5: Higher-Order Functions. A Simple Recursion. Avoiding Recalculation. Redundant Calculation. Tail Recursion and Repetition

Lecture #5: Higher-Order Functions. A Simple Recursion. Avoiding Recalculation. Redundant Calculation. Tail Recursion and Repetition nnouncements: Lecture #5: Higher-Order Functions Make sure that you have registered electronically with our system (not just TeleBERS). ttend a discussion/lab in which you can fit; don t worry about Tele-

More information

Introduction to Programming I

Introduction to Programming I Still image from YouTube video P vs. NP and the Computational Complexity Zoo BBM 101 Introduction to Programming I Lecture #09 Development Strategies, Algorithmic Speed Erkut Erdem, Aykut Erdem & Aydın

More information

Chapter 1. Fundamentals of Higher Order Programming

Chapter 1. Fundamentals of Higher Order Programming Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 10 Functions Last Class We Covered The string data type Built-in functions Slicing and concatenation Escape sequences lower() and upper() strip() and whitespace

More information

Looping. Arizona State University 1

Looping. Arizona State University 1 Looping CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 5 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Conditionals & Control Flow

Conditionals & Control Flow CS 1110: Introduction to Computing Using Python Lecture 8 Conditionals & Control Flow [Andersen, Gries, Lee, Marschner, Van Loan, White] Announcements: Assignment 1 Due tonight at 11:59pm. Suggested early

More information

Chapter 8. Statement-Level Control Structures

Chapter 8. Statement-Level Control Structures Chapter 8 Statement-Level Control Structures Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions Copyright 2009 Addison-Wesley.

More information

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

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators Chapter 5: 5.1 Looping The Increment and Decrement Operators The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++;

More information

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop Topics C H A P T E R 4 Repetition Structures Introduction to Repetition Structures The for Loop: a Count- Sentinels Nested Loops Introduction to Repetition Structures Often have to write code that performs

More information

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

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration) Week 7: Advanced Loops while Loops in C++ (review) while (expression) may be a compound (a block: {s) Gaddis: 5.7-12 CS 1428 Fall 2015 Jill Seaman 1 for if expression is true, is executed, repeat equivalent

More information

Control flow statements

Control flow statements Control flow statements It is important to make decisions in programming about how your code will be looked at. You may need to be selective, iterative or repetitive with the code statements. Python provides

More information

CMSC 201 Fall 2018 Python Coding Standards

CMSC 201 Fall 2018 Python Coding Standards CMSC 201 Fall 2018 Python Coding Standards The purpose of these coding standards is to make programs readable and maintainable. In the real world you may need to update your own code more than 6 months

More information

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

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

User-defined Functions. Conditional Expressions in Scheme

User-defined Functions. Conditional Expressions in Scheme User-defined Functions The list (lambda (args (body s to a function with (args as its argument list and (body as the function body. No quotes are needed for (args or (body. (lambda (x (+ x 1 s to the increment

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 2/e 1 Objectives æ To understand the programming pattern simple decision and its implementation

More information

Introduction to Computers and Programming. Recap

Introduction to Computers and Programming. Recap Introduction to Computers and Programming Prof. I. K. Lundqvist Lecture 11 Reading: FK pp. 199-209, 220-223, 266-267 Sept 29 2003 Recap Scope : determine which declarations are visible and directly visible

More information