CSC115 Introduction to Computer Programming

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
Loop - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 1.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
The for loop.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 2/4/20161.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC530 Data Structures - LOOP 7/9/20161.
Adapted from slides by Marty Stepp and Stuart Reges
Lesson #5 Repetition and Loops.
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
Introduction To Repetition The for loop
CSC141 Computer Science I Zhen Jiang Dept. of Computer Science
Python: Control Structures
Lesson #5 Repetition and Loops.
Loop Structures.
Chapter 5: Control Structure
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Algorithm Analysis CSE 2011 Winter September 2018.
Topics Introduction to Repetition Structures
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
CSC115 Introduction to Computer Programming
Chapter 13 Control Structures
Repetition Chapter 6 12/06/16 & 12/07/16 1 1
Chapter 4 Control structures and Loops
CSC240 Computer Science III
Control Structure Senior Lecturer
Control Structure Senior Lecturer
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Lesson #5 Repetition and Loops.
CSC115 Introduction to Computer Programming
Alternate Version of STARTING OUT WITH C++ 4th Edition
Iteration: Beyond the Basic PERFORM
Iteration: Beyond the Basic PERFORM
CSc 110, Spring 2017 Lecture 4: Nested Loops and Loop Figures
Loops CIS 40 – Introduction to Programming in Python
Algorithm Discovery and Design
Building Java Programs
Building Java Programs
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Computing Fundamentals
Building Java Programs
Building Java Programs
The for loop suggested reading:
Chapter 5: Control Structures II (Repetition)
Building Java Programs
Building Java Programs
For loops Taken from notes by Dr. Neil Moore
Objectives You should be able to describe: The while Statement
Building Java Programs
Building Java Programs
Topics Introduction to Repetition Structures
Building Java Programs
Lesson #5 Repetition and Loops.
Building Java Programs
Building Java Programs
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Building Java Programs
Chapter 2 Lecture 2-2: The for Loop reading: 2.3
ICS103: Programming in C 5: Repetition and Loop Statements
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Chapter 13 Control Structures
Presentation transcript:

CSC115 Introduction to Computer Programming Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA 19383 zjiang@wcupa.edu

Table of Contents Review of Condition and Decision Making Loop/Repetition Format/Syntax and Execution Code alignment and end of block Variations Development Counter control loop Event control loop File I/O Nested loop For loop

Review Condition = =, !=, is String and numerical values Simple check: Value and threshold Complex check: and, or, not Precedence order Processing Operator, selection (of 2 cases), multi-case problem Prepare for the test

Loop Big-or-small? Random.randint(1,6), store and not show Guess 123 small or 456 big Won or lost Continue to play!

Format and Execution <initialization>; while <condition test> : <body>

Initialization, test of condition, and body, and execution results of loop x = 0 while x < 4: print(str(x)+" squared is "+str(x*x)) x += 1 1st iteration? 2nd iteration? 3rd iteration? …

The initial and final values for the loop counter/event variable can be arbitrary expressions: x = -2 while x < 47%4 : print(str(x)+" squared is "+str(x*x)) x += 1

The update can be any other operation, e.g., −=1, or +=3. Caution: This requires changing the test from <= to >= . x = 3 while x >0 : print(x) x -= 1 print("Blast off!")

Invalidation: Loops that never execute. x = 3 while x <= 0 : print(x) x += 1 print("Blast off!")

ERROR: Loop tests that never fail. A loop that never terminates is called an infinite loop. x = 3 while x >0 : print(x) x += 1 print("Blast off!")

Loops that go on… forever while 1: <statement(s)> If it goes on forever, how do you stop?

break statement: Immediately exits a loop Example: x = 3 while 1: print(x) if x == 5 : break x += 1

Development Process Simple While Loop Nested Loop For Loop Counter Control Loop Event Control Loop Nested Loop For Loop

If the number of iterations is known before the loop starts, the loop is called a count-controlled loop. Counter =0, counter+=1, counter <number Counter = 1, counter+=1, counter <=number

k = int(input(“an positive even number k: ")) result = 2 i = 1 while i <= k/2 -1 : result = result + 2 * i + 2 i += 1 print (result)

Suppose that we have the following loop: count = 1 While count <= 49: ... count+=1 What statement could we write in the body of the loop that would make the loop print the following output? 2 4 6 8 … Answer: print(2 * count)

Now consider another loop of the same style: count = 1 While count <= 49: ... count+=1 What statement could we write in the body of the loop that would make the loop print the following output? 3 5 7 9 11 Answer: print(2 * count + 1)

What statement could we write in the body of the loop that would make the loop print the following output? 2 7 12 17 22 To find the pattern, it can help to make a table. Each time count goes up by 1, the number should go up by 5. But count * 5 is too big by 3, so we must subtract 3. count number to print count * 5 count * 5 - 3 1 2 5 2 2 7 10 7 3 12 15 12 4 17 20 17 5 22 25 22

17 4 22 12 7 2 number to print (y)‏ 5 3 1 count (x)‏

Caution: This is algebra, not assignment! Recall: slope-intercept form (y = mx + b)‏ Slope is defined as “rise over run” (i.e. rise / run). Since the “run” is always 1 (we increment along x by 1), we just need to look at the “rise”. The rise is the difference between the y values. Thus, the slope (m) is the difference between y values; in this case, it is +5. To compute the y-intercept (b), plug in the value of y at x = 1 and solve for b. In this case, y = 2. y = m * x + b 2 = 5 * 1 + b Then b = -3 So the equation is y = 5 * x – 3 y = 5 * count - 3 17 4 22 12 7 2 number to print (y)‏ 5 3 1 count (x)‏

Algebraically, if we always take the value of y at x = 1, then we can solve for b as follows: y = m * x + b y1 = m * 1 + b y1 = m + b b = y1 – m In other words, to get the y-intercept, just subtract the slope from the first y value (b = 2 – 5 = -3)‏ This gets us the equation y = 5 * x – 3 y = 5 * count – 3 (which is exactly the equation from the previous slides)‏

What statement could we write in the body of the loop that would make the loop print the following output? 17 13 9 5 1 Let's create the loop table together. Each time count goes up 1, the number should ... But this multiple is off by a margin of ... 5 4 1 9 13 17 number to print 3 2 count 5 -16 -20 -12 -8 -4 count * -4 1 9 13 17 count * -4 + 21

How to confirm the initialization correct? On preparing the 1st iteration … How to ensure the detail of the body? A consistent view of 1st, 2nd, 3rd iterations … Map of the counter value to the iteration expression …

Calculate the result 1/i+2/(i-1)+3/(i-2)+…+(i-1)/2+i/1. i = int(input("Enter an integer: ")) print(total)

Otherwise (unknown or unclear), the loop is called a event-controlled loop. Use a loop for an easy checkpoint development. Asking the user before each iteration if it is time to end the loop is called the ask-before-iterating technique. Appropriate status update (or event initializing) for a sequence of iterations

k = int(input("a number >1: ")) i = 2 while k%i != 0 : i+=1

Type a non-negative integer: -5 Write a program that will repeatedly prompt the user to type a number until the user types a non-negative number, then square it. Example log: Type a non-negative integer: -5 Invalid number, try again: -1 Invalid number, try again: -235 Invalid number, try again: -87 Invalid number, try again: 11 11 squared is 121

Enter a nonnegative number: 29107 Write a program that reads an integer from the user and prints the sum of the digits of that number. You may assume that the number is non-negative. Example: Enter a nonnegative number: 29107 prints out 19 (i.e.,2+9+1+0+7 ) Hint: Use the % operator to extract the last digit of a number. If we do this repeatedly, when should we stop?

File I/O fname = input("Enter the file name: ") fp = open(fname) str = "" while True: line = fp.readline() str+=line #replaced by any other processing if (""==line): print("End of reading") break print(str) print("end of file")

f = open("demofile.txt", "a") f.write("Now the file has one more line!\n")

Nested Loop Accumulation Loops Accumulation loops keep track of the accumulation function each time through the loop. Usually, such a function says to find the “total” or “average” or “maximum” or “biggest” or “anything-est”, then you need an accumulation loop. In an accumulation loop, the body computes a number, and repeats this set of commands to update it. Accumulation loops are add-ons to either counter control loop or event control loop. 

The data type of the accumulator depends on what kind of information you are trying to accumulate with such a function. Same for the current_value, and the way in which the current_value combines with the existing accumulator value to create the new accumulator value. For instance: If you are trying to find the total of a sequence of integer numbers, then accumulator is type int, i.e., accumulator = accumulator + current_value;  If you are trying to find the longest value in a sequence of double numbers, then accumulator is type double, accumulator = current_value if current_value is larger than accumulator. 

Write a program that reads in an integer and displays its number of factors. For example, if the user enters 60, the program will display 12 because 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, and 60 are all factors of 60.

Write a program that reads 10 integers and displays its minimum and maximum.

Nested Loop Nested loops combine an inner loop (which repeats some stuff X times) with an outer loop (which repeats the whole inner loop Y times). As a result, the inner loop’s stuff gets repeated X * Y times.

A nested loop can combine an inner counter control loop with an outer event control loop, or an inner event control loop with an outer counter control loop, or any other combination. It is commonly used when the body of a loop (i.e., outer loop) can be simplified by decomposing into another loop (i.e., inner loop). For instance: Get the first 10 prime numbers. The inner loop is to check a possible factor and the outer loop is to count total 10 successes of search by the inner loop.

Write a program that display the first 10 prime numbers after 1000.

For Loop fname = input("Enter the file name: ") fp = open(fname) str = "" for line in fp: str+=line #replaced by any other processing print("End of reading")

fruits = ["apple", "banana", "cherry"] for x in fruits: print(x)