Introduction to Computing Science and Programming I

Slides:



Advertisements
Similar presentations
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Advertisements

Computer programming Lecture 3. Lecture 3: Outline Program Looping [Kochan – chap.5] –The for Statement –Relational Operators –Nested for Loops –Increment.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Conditional Statements Introduction to Computing Science and Programming I.
Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Introduction to Computer Programming in c
Fundamentals of Python: From First Programs Through Data Structures
4. Python - Basic Operators
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
General Programming Introduction to Computing Science and Programming I.
Chapter 2 - Algorithms and Design
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
Using Shortcut Arithmetic Operators Accumulator: A variable that is used to total. Its value is repeatedly increased by some amount. Java provides shortcuts.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping with.
1 Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Repetition Structures Repetition Structures allow you to write programs that will repeat program steps multiple times. –Also called Loops –Counter controlled.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Decision Making and Branching (cont.)
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
CRE Programming Club - Class 4 Robert Eckstein and Robert Heard.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
Computer C programming Chapter 3. CHAPTER 3 Program Looping –The for Statement –Nested for Loops –for Loop Variants –The while Statement –The do Statement.
Introduction to Computing Science and Programming I
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Introduction To Repetition The for loop
Python: Control Structures
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Control Structure Senior Lecturer
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Structured Program
Iteration: Beyond the Basic PERFORM
Loops CIS 40 – Introduction to Programming in Python
Computing Fundamentals
Computer programming Lecture 3.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Introduction to Computing Science and Programming I Loops Introduction to Computing Science and Programming I

Loops To this point you’ve learned how to write code that executes from top to bottom as well as how to use conditional (if) statements to select or skip parts of the code. Loop structures allow the programmer to have sections of code executed multiple times. This allows many programs that couldn’t be written without loops as well as making many programs that can be written without loops, more simple.

Algorithms With Loops Before getting into how to write the loops themselves, let’s look at some problems that require loops.

Prime Number Algorithm Here’s an algorithm we looked at previously to test whether a user input number is prime. set divisor to 2 write “Enter an integer greater than 2” read userNumber repeat while divisor2 < userNumber if userNumber % divisor is equal to 0 write “The number is not prime, it is divisible by :” write divisor exit program set divisor to divisor +1 write “The number is prime.”

Prime Number Algorithm Notice that we have a section of the algorithm we want to repeat repeat while divisor2 < userNumber if userNumber % divisor is equal to 0 write “The number is not prime, it is divisible by :” write divisor exit program set divisor to divisor +1 The algorithm wants to repeat the indented section of code while (divisor2 < userNumber)

Algorithms A couple simpler algorithms that will need to repeat code. Factorial n! = n * (n-1) * (n-2) *…*2 * 1 5! = 5 * 4 * 3 * 2 * 1 = 120 Algorithm write “Enter a nonnegative integer:” read n set factorial to 1 do this for i equal to each number from 1 to n: set factorial to factorial * i write factorial Notice the code that will be repeated, but this time it is stated differently. Instead of repeat while this is true, it says do this this many times.

A Couple More Algorithms Repeatedly prompting a user until they give proper input set number to 0 repeat while number < 1 write “Enter a positive integer: “ read number Printing out the powers of 2 write “How many powers of 2 should be printed?” read max set value to 1 do this max times write value set value to value * 2

Two Kinds of Loop while loops for loops These are called indefinite loops because they are often used to repeat code without knowing how many times it will be repeated beforehand. for loops These are called definite loops because they usually will repeat a set number of times

while Loops while condition: code block Similar to an if statement, a while loop is given a condition (boolean expression). The code block associated with the while loop will repeat over and over again until the condition becomes false.

while Loops A simple example that prints the number 1 through 3. while num <= 3: print num num = num + 1 print “Finished” When the while statement is reached the first time, num is 1 which is less than five. Therefore execution enters the code block and repeats the code block until num is greater than 5

while Loops Unwinding the loop To understand what’s going on we can ‘unwind’ the loop num = 1 while num <= 3: print num num = num + 1 print “Finished” Check the condition, is num <=3? Yes, so enter the code block num = num + 1 (num is 2) Check the condition, is num <= 3? Yes, so repeat the code block num = num + 1 (num is 3) num = num + 1 (num is 4) Check the condition, is num <= 3? No, so skip the code block

while Loops Remember that the condition is checked before the block of code is executed for the first time. Therefore, the code in a while loop may never be executed. You also need to make sure the condition eventually becomes false, if not you will have an infinite loop. The program will never leave the while loop and never finish

while Loops while loops are an easy way to wait for proper input from the user number = 0 while number < 1: number = int(raw_input(“Enter a positive integer: “)) print “Your number is “ + str(number)

for Loops For the time being all of the for loops we look at will look something like this for x in range(5): print x We’ll learn more general uses of it, but for now the for statement will be of the form for varname in range(..): Here we just have the single statement ‘print x’ inside the loop, but you have any sized code block you like

range Function range is a Python function that returns a list of numbers If you give range one argument, it returns a list of integers starting at 0, ending at one less than the argument range(4) = [0, 1, 2, 3] range(10) = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] You can also give range a beginning and ending number. The list starts at the first argument and ends at one less than the second argument. range(1,5) = [1, 2, 3, 4] range(-2,2) = [-2, -1, 0, 1] range(0,4) = range(4) We will learn about the list data type and how to create our own lists later

for Loops What the for loop does is assign the values returned by range to the variable one by one and executes the code block for each value for x in range(5): print x x will be assigned the 5 values in range, and those values will be printed

for Loops Unwinding a for loop for x in range(5): print x Remember, range(5) = {0,1,2,3,4} x=0 (first value in range(5)) x=1 (second value in range(5)) x=2 (third value in range(5)) x=3 (fourth value in range(5)) x=4 (final value in range(5)) No more values remain in range(5) so we are finished

for Loops You can just use the structure to repeat code a certain number of times, ignoring the value assigned to the variable in the for statement Printing out the powers of 2 max = int(raw_input("How many powers of 2 should be printed? ")) num = 1; for i in range(max): print num num = num * 2 Notice that the values in range(max) will be assigned to i, but we don’t use i inside the loop. We’re just using the structure to repeat the code block max times.

for Loops Unwinding a for loop Assume a user entered 3 in the last example num = 1 for i in range(max): //max previously set to 3 print num num = num * 2 Remember, range(3) = {0,1,2} i=0 (first value in range(3)) print num (num is 1) num = num * 2 (num is 2) i=1 (second value in range(3)) num = num * 2 (num is 4) i=2 (third and last value in range(3)) num = num * 2 (num is 8) No values remain in range(3) so the loop is complete

for Loops Factorial Example n = int( raw_input("Enter a nonnegative integer: ") ) factorial = 1 for i in range(n): factorial = factorial * (i+1) print factorial

for Loops range(n) returns {0,1,2…,n}, but you may want to use the integers starting at 1 Print the first 5 positive integers for num in range(5): print num+1 num is set to 0,1,2… but we offset it by one in the for loop to get the numbers we desired We could also have used range(1,6) in this case

for Loops Extending that idea Print the first 5 positive even numbers for num in range(5): print 2*(num+1) Print the first 5 positive odd numbers print 2*num + 1 Print the first 5 positive numbers squared print num**2 Print the first 5 powers of 2 print 2**num

Nesting The code block inside a loop (or if structure) can contain loops (or if structures) itself. This is called nesting loops. As you get into more complex programs these nested structures become commonplace

Nesting Nested for loops to print a block of 0s Output for row in range(4): for col in range(5): print 0, print “” Output 0 0 0 0 0 If you put a comma at the end of a print statement ‘print 0,’ it will not go to the next line after printing

Nesting Another nested for loop example that prints out the coordinates (row,col) of each location in a grid with (0,0) being the upper left-hand corner.. for row in range(4): for col in range(6): print "(" +str(row) + "," + str(col) + ")", print “” Output: (0,0) (0,1) (0,2) (0,3) (0,4) (0,5) (1,0) (1,1) (1,2) (1,3) (1,4) (1,5) (2,0) (2,1) (2,2) (2,3) (2,4) (2,5) (3,0) (3,1) (3,2) (3,3) (3,4) (3,5)

Nesting Another nested for loop example that prints out the coordinates (row,col) of each location in a grid. for row in range(4): for col in range(6): print "(" +str(row) + "," + str(col) + ")", print “” Remember that the inner for loop is run from start to end every time the code block for the outer for loop is run Each time one of the values in range(4) is assigned to row, every value in range(6) will be assigned to col

Nesting Nested loops to find the average of different students grades count = 0 name = raw_input("Enter student's name, enter nothing to quit: ") while name!= "": count = count + 1 totalScore=0 for i in range(3): totalScore=totalScore + int(raw_input("Assignment " + str(i+1) + " score: ")) print name + "'s average is " + str(round(totalScore/3.0)) + "." print "You entered the grades of " + str(count) + " student(s)"

Deciding Which Control Structure To Use You have code that only needs to run in certain situations if statement Absolute value num = int(raw_input(“Enter number: “)) if num < 0: num = -num print “Absolute value is “ + str(num)

Deciding Which Control Structure To Use You have two chunks of code, one or the other of which should run every time if – else structure num = int(raw_input(“Enter a number: “)) if (num % 2) == 0: print “You entered an even number.” else: print “You entered an odd number.”

Deciding Which Control Structure To Use You have more than two chunks of code, with one and only one of which that should run each time. if-elif-else structure temp = int(raw_input(“Enter the temperature: “)) if temp > 25: print “It is hot today.” elif temp > 15: print “It is warm today.” elif temp > 5: print “It is cool today.” else: print “It is cold today.”

Deciding Which Control Structure To Use You have code that needs to be repeated for or while loop There are many cases where either type of loop can be used, but there are general rules. If you know how many times a loop is going to repeat, usually a for loop is best. You may only know the repetitions based on user input or some other variable. If you need to keep repeating something until some process is finished/goal is met

In Class Exercise Write a short program that reads some user entered text, and outputs whether there is a repeated character in the string. e.g. “aa”, “speed”, but not “banana” if text is a variable containing a string len(text) tells you how many characters it has text[0] gives you the first character, text[1] the second and text[len(text) – 1] the last Write a short program that prints out an NxN multiplication table where N is entered by the user If the user entered 3 the table should be. 1 2 3 2 4 6 3 6 9

In Class Exercise This could also be done with a while loop #Find a repeated character text = raw_input("Enter text: ") found = False #will be set to true if we find a repeated character for index in range(len(text)-1): if text[index] == text[index+1]: print "Repeated character found: "+text[index] found = True if not found: print "No repeats found"

In Class Exercise size = int(raw_input(“How many rows/colums? “)) for row in range(size): for col in range(size): print (row+1) * (col+1), print We need to use row+1 and col+1 since we want to start at 0, not 1 Remember that the comma at the end of the print statement prevents it from proceeding to the next line print without anything after ends the line

In Class Exercise What does the code print out? count = int(raw_input("Enter the max: ")) for row in range(count): line = "" for i in range(count-row-1): line = line + " “ for i in range(row+1): line = line + str(i+1) for i in range(row): line = line + str(row-i) print line

In Class Exercise The outer loop is pretty clearly printing out one line for each iteration, the inner loops are adding text to that line. Take each inner loop individually for i in range(count-row-1): line = line + " “ Assume count is 5. For each value of row, this will add count-row-1 spaces. row will be assigned the values 0,1,2…count – 1 Therefore, on the first line this adds count-1 spaces, count-2 on the second, … , and none on the last

In Class Exercise for i in range(row+1): line = line + str(i+1) For each value of row this will add the numbers 1,2,3…row+1 to the current line for i in range(row): line = line + str(row-i) For each value of row this will add the numbers row,row-1,row-2…,1 to the current line Combining these two, the first line will get 1, the second, 121, the third, 12321, and so on

In Class Exercise Combining all of this, we see a pyramid of numbers printed out The first inner for loop adds the spaces at the left, the second for loop adds the increasing number, the last adds the decreasing numbers 1 121 12321 1234321 123454321