Loops & List Intro2CS – week 3 1. Loops -- Motivation Sometimes we want to repeat a certain set of instructions more than once. The number of repetitions.

Slides:



Advertisements
Similar presentations
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Advertisements

CS107 Introduction to Computer Science Lecture 3, 4 An Introduction to Algorithms: Loops.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Repeating Actions While and For Loops
Lists Introduction to Computing Science and Programming I.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
COMP 14 Introduction to Programming Miguel A. Otaduy May 21, 2004.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Loops – While, Do, For Repetition Statements Introduction to Arrays
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Programming for Linguists An Introduction to Python 24/11/2011.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 4 Objectives  Learn about repetition (looping) control structures.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Quiz Answers 1. Show the output from the following code fragment: int a = 5, b = 2, c = 3; cout
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
ㅎㅎ logical operator if if else switch while do while for Third step for Learning C++ Programming Repetition Control Structures.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
Control Structures II: Repetition.  Learn about repetition (looping) control structures  Explore how to construct and use count-controlled, sentinel-controlled,
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
COMP Loop Statements Yi Hong May 21, 2015.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Catie Welsh February 9,  Friday - No Lab! ◦ Bring questions on Project 2  Lab 3 due on Friday 2.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
CONDITIONALS CITS1001. Scope of this lecture if statements switch statements Source ppts: Objects First with Java - A Practical Introduction using BlueJ,
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
String and Lists Dr. José M. Reyes Álamo.
Chapter 6: Loops.
Topic: Iterative Statements – Part 1 -> for loop
Chapter 5: Control Structures II
Repetition Structures Chapter 9
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Chapter 2.2 Control Structures (Iteration)
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Arrays, For loop While loop Do while loop
Programming Fundamentals Lecture #6 Program Control
Outline Altering flow of control Boolean expressions
Lesson #5 Repetition and Loops.
CS190/295 Programming in Python for Life Sciences: Lecture 6
Nate Brunelle Today: Repetition, Repetition
Chapter (3) - Looping Questions.
Iteration: Beyond the Basic PERFORM
Iteration: Beyond the Basic PERFORM
String and Lists Dr. José M. Reyes Álamo.
Fundamentals of visual basic
2.6 The if/else Selection Structure
Comparing Python and Java
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
Presentation transcript:

Loops & List Intro2CS – week 3 1

Loops -- Motivation Sometimes we want to repeat a certain set of instructions more than once. The number of repetitions may be unknown in advance (depends on input). Two types of loops: – Repeat some instructions until some condition is met (while loops) – Repeat some instructions for every item in a sequence (for loops) 2

The while loop 3 while : Evaluate boolean expression Execute statements Skip statements (resume rest of program) True False Start Here

A simple example 4

5

What if we forget? The loop does not stop… This is a problem. 6

How to check if a number is prime 7

Break and Continue Two statements to use in loops: breakexits the loop immediately. continueskips remaining statements in loop 8

Break, continue 9

The for loop over sequences 10 A line that does not do anything. How else can you write this?

Counting Range objects represent a sequence of integers range(stop) represents ints from 0 to stop-1 (excluding stop) range(start,stop) represents ints from start to stop-1 (excluding stop) range(start,stop,step) represents ints from start to stop (exluding) with given step size 11

Counting So what do these print? 12

Checking if prime (again) 13

Lists We may want to save a large amount of data. Example: the name of every person in class. Do we assign each to a different variable? What if we need to add a person? How do we process all this data in a loop? 14

Lists Use [ ] to specify a list and assign it. Separate items with commas, Access items using their index: 15 print(names[0]) print(names[-1]) print(len(names)) names[1] = “Robert” print(names) names = ["Alice", "Bob", "Charlie", "Dave", "Eve"] Access to cell in list. Indices start at 0 Negative indices: count from the end. Length of the list. Last index is length-1. We can assign to cells (like regular variables)

Lists An empty list: Other ways to create lists through the list “constructor”: 16 list()[] list(“word”)['w', 'o', 'r', 'd'] list(range(5))[0, 1, 2, 3, 4] names = []

Multiplication and addition membership, deleting, appending 17 names = [“Alice”, “Bob”, “Charlie”, “Dave”] print("Bob" in names) del names[1:3] print(names) names.append(“Eve”) print(names) print([1, 2, 3] * 3) print([1, 2, 3] + [4, 5, 6, 7])

Slicing 18 numbers = list(range(10)) numbers[:] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] numbers[3:][3, 4, 5, 6, 7, 8, 9] numbers[:3][0, 1, 2] numbers[1:3][1, 2] numbers[::2][0, 2, 4, 6, 8] numbers[::-1][9, 8, 7, 6, 5, 4, 3, 2, 1, 0] Assign to slices: numbers[1:3] = ['a','b','c','d’] [0, 'a', 'b', 'c', 'd', 3, 4, 5, 6, 7, 8, 9]

loops over lists We can loop over lists just like any other sequence: Or: (less elegant, but works) 19 for element in my_list: print(element) for index in range(len(my_list)): print(my_list[index])

Finding all primes 20 >>> print(all_primes_up_to(100)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

The Sieve of Eratosthenes Mark suspected prime numbers in a list The idea: once we find a prime number, we can erase all its multiples as primes. 2 is prime. Next “suspect” is also a prime (why?) TTTTTTTTTTTTTTTTTTTT TTFTFTFTFTFTFTFTFTFT

The Sieve of Eratosthenes TTFTFTFFFTFTFFFTFTFF TTFTFTFFFTFTFFFTFTFF Not Prime, so multiples already erased!

The Sieve of Eratosthenes 23

24

Nested lists We can place lists inside each other. 25