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

Size: px
Start display at page:

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

Transcription

1 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 KH (24/10/17) Lecture 11: while loops / 1 KH (24/10/17) Lecture 11: while loops / 1 for loop revisited while loop Syntax For loop is generally used where number of iterations (repetitions) is known in advance for i in range(n + 1): total = total + i What if we don t know this number? Components while condition : body Condition Boolean condition Loop body Indented block of statements Meaning Condition controls loop execution Repeatedly execute loop body but check that condition is True before each repetition; terminate loop if condition is False KH (24/10/17) Lecture 11: while loops / 1 KH (24/10/17) Lecture 11: while loops / 1

2 while loop cont d A concrete example while condition : body 1 Evaluate condition: if False skip to Step 4 otherwise proceed to Step 2 2 Execute loop body 3 Go back to Step 1 4 (Continue execution with statement following the while) Task Read in a series of positive numbers one per line and output their sum; series terminated by 1 (not part of series) e.g. Terminology Ideas The 1 is known as a sentinel No predetermined indication of length of series Use while loop: condition captures have we reached the end of the series? KH (24/10/17) Lecture 11: while loops / 1 KH (24/10/17) Lecture 11: while loops / 1 Solution num = int(input( Please enter a number: )) while num!= 1: num = int(input( Please enter a number: )) print( Total is, total ) Solution cont d while num!= 1: num = int(input( Please...: )) print ( Total is, total ) Trace of program execution for series: num =... (reads 1) num!= -1? (True) (now 1) num =... (read 17) num!= -1? (True) (now 18) num =... (reads 5) num!= -1? (True) (now 23) num =... (reads -1) KH (24/10/17) Lecture 11: while loops / 1 num!= -1? (False) print Note: Loop execution interleaves condition check and execute body steps KH (24/10/17) Lecture 11: while loops / 1

3 Solution cont d A variation on the theme while num!= 1: An alternative to the sentinel approach is the go-around option. Ask the user after each number whether it is the last print ( Total is, total ) KH (24/10/17) Lecture 11: while loops / 1 KH (24/10/17) Lecture 11: while loops / 1 Another solution Another solution cont d done = False while not done: num = int(input( Please enter a number: )) go again = input( Would you like another (y/n)? ) done = go again. strip ()!= y print( total was, total ) Statement done =... controls loop Variable done transmits it done = False while not done: go again = input( Would...? ) done = go again. strip ()!= y print ( total was, total ) Performs at least one iteration Execution sequence: Execute body Check if finished Execute body Check if finished Execute body Check if finished etc. Effectively check happens at the end of each loop body execution rather than the start KH (24/10/17) Lecture 11: while loops / 1 KH (24/10/17) Lecture 11: while loops / 1

4 for loops vs while loops Syracuse sequence Can always re-write for loops using while for n in range(20, 10, 2): total = total + n print( total ) n = 20 while n > 10: total = total + n n = n 2 print( total ) while is more powerful, but can be harder to work with General rule: Favour for loops for definite iteration i.e. where number of iterations known in advance and while loops otherwise The Syracuse sequence is generated by starting with a natural numbers and repeatedly applying the following function until 1 is reached: { x/2 if x even syr(x) = 3x + 1 if x odd Example (n = 5): 5, 16, 8, 4, 2, 1 Task: Write a program that generates the Syracuse sequence for a given value of n KH (24/10/17) Lecture 11: while loops / 1 KH (24/10/17) Lecture 11: while loops / 1 Syracuse function Generating Syracuse series def syr(x): if x % 2 == 0: return x // 2 else : return 3 x + 1 current = n print(current, :, end = ) while current!= 1: current = syr(current) print(current,, end = ) print() Wrap a for loop around this to generate series for values 1 to 20 say. KH (24/10/17) Lecture 11: while loops / 1 KH (24/10/17) Lecture 11: while loops / 1

5 Prime numbers Testing for primality A whole number is prime if it has no divisors other than itself and one Examples: primes 2, 3, 5, 7, 11, 13, (infinitely many) non primes 4, 10, 34 Task: Write a Python function that determines whether a given number is prime or not Idea: Try candidate divisors 2, 3, 4,, n 1 in turn to see if any divide number evenly; if none do then n is prime, otherwise not def is prime (n): # Return True if ' n' is prime no divisors = n > 1 cand = 2 while no divisors and cand < n: no divisors = no divisors and n % cand!= 0 cand = cand + 1 return no divisors KH (24/10/17) Lecture 11: while loops / 1 KH (24/10/17) Lecture 11: while loops / 1 Testing for primality cont d Goldbach s Conjecture def is prime (n): # Return True if n is prime no divisors = n > 1 cand = 2 while no divisors and cand < n: no divisors = no divisors \ and n % cand!= 0 cand = cand + 1 return no divisors Easy to see function produces correct answer for {0, 1, 2} Variable cand steps through values 2, 3, 4,, n 1 in turn If divisor found, variable no divisors set to False Once False, value can never revert to True The conjecture Every even integer greater than two can be expressed as the sum of two primes Believed to be true, but no known proof Task Verify the conjecture for integers up to 200 Idea For specific number n and value i, see if i and n i are both prime Try each possible i from 2 upwards, until you find a pair that works KH (24/10/17) Lecture 11: while loops / 1 KH (24/10/17) Lecture 11: while loops / 1

6 Back Material Solution Notes and Acknowledgements print(k, :, end = ) for i in range(2, k): if is prime ( i ) and is prime(k i): print(str( i ), +, str(k i), end = ) break print() Wrap a for loop around this to repeat this for even values of k in the range 4 to 200 (say) Reading Code Acknowledgements KH (24/10/17) Lecture 11: while loops / 1 KH (24/10/17) Lecture 11: while loops / 1

Lecture 7: Functions. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

Lecture 7: Functions. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork Lecture 7: Functions CS1068+ Introductory Programming in Python Dr Kieran T. Herley 2018/19 Department of Computer Science University College Cork Summary Functions in Python. Terminology and execution.

More information

Loops / Repetition Statements

Loops / Repetition Statements Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for

More information

Lecture 18: Lists II. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

Lecture 18: Lists II. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork Lecture 18: Lists II CS1068+ Introductory Programming in Python Dr Kieran T. Herley 2018/19 Department of Computer Science University College Cork Summary More on Python s lists. Sorting and reversing.

More information

Lecture 10: Boolean Expressions

Lecture 10: Boolean Expressions Lecture 10: Boolean Expressions CS1068+ Introductory Programming in Python Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (12/10/17) Lecture 10: Boolean Expressions

More information

Programming Training

Programming Training Programming Training Main Points: - Working with Functions in Python - Problems with Numbers. - Discuss some important algorithms - Primality - Digits - Greatest Common Divisor Python Repetitions. while

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

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

Lecture 4: Simple Input-Calculate-Output Programs

Lecture 4: Simple Input-Calculate-Output Programs Lecture 4: Simple Input-Calculate-Output Programs CS1068+ Introductory Programming in Python Dr Kieran T. Herley 2017/18 Department of Computer Science University College Cork input Statement Python s

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

switch-case Statements

switch-case Statements switch-case Statements A switch-case structure takes actions depending on the target variable. 2 switch (target) { 3 case v1: 4 // statements 5 break; 6 case v2: 7. 8. 9 case vk: 10 // statements 11 break;

More information

CS 241 Control Structures. Christopher A. Gantz. SPS Undergraduate Program Regis University

CS 241 Control Structures. Christopher A. Gantz. SPS Undergraduate Program Regis University CS 241 Control Structures Christopher A. Gantz SPS Undergraduate Program Regis University cgantz@regis.edu Slide 1 Lecture Topic #8 CS 241: Repetition Statements Christopher A. Gantz School of Professional

More information

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

1 class Lecture3 { 2 3 Selections // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137 1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 89 / 137 Flow Controls The basic algorithm (and program) is constituted

More information

Lecture 8: Simple Calculator Application

Lecture 8: Simple Calculator Application Lecture 8: Simple Calculator Application Postfix Calculator Dr Kieran T. Herley Department of Computer Science University College Cork 2016/17 KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17

More information

Simple Lexical Analyzer

Simple Lexical Analyzer Lecture 7: Simple Lexical Analyzer Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (03/10/17) Lecture 7: Simple Lexical Analyzer 2017-2018 1 / 1 Summary Use of jflex

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

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

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

Lecture 15: Dictionaries

Lecture 15: Dictionaries Lecture 15: Dictionaries CS1068+ Introductory Programming in Python Dr Kieran T. Herley 2018/19 Department of Computer Science University College Cork Summary Python s dictionary concept. 1 Dictionaries

More information

Arithmetic Compound Assignment Operators

Arithmetic Compound Assignment Operators Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages such as Matlab and R. Zheng-Liang Lu Java Programming 76 / 141 Example 1... 2 int x = 1; 3 System.out.println(x);

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

Algorithms and Data Structures

Algorithms and Data Structures Algorithms and Data Structures 4. Łódź 2018 Exercise Harmonic Sum - Type in the program code - Save it as harmonic.py - Run the script using IPython Wikipedia - This program uses the for loop, the range()

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

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141 Common Errors 2 double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141 Generating random numbers Example Write a program which generates

More information

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action. Chapter 5 Conditional and Iterative Statements Statement Statement are the instructions given to the computer to perform any kind of action. Types of Statement 1. Empty Statement The which does nothing.

More information

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

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

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

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

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

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed? Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct and use countercontrolled, sentinel-controlled,

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

Computer Programming I - Unit 5 Lecture page 1 of 14

Computer Programming I - Unit 5 Lecture page 1 of 14 page 1 of 14 I. The while Statement while, for, do Loops Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly. The while statement is one of three looping statements

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

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3 Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3 Ziad Matni Dept. of Computer Science, UCSB A Word About Registration for CS16 FOR THOSE OF YOU NOT YET REGISTERED:

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

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

Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today.

Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today. Lecture 6 Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today. Previously Decision structures with flowcharts Boolean logic UML

More information

Fundamentals of Programming. Week 1 - Lecture 3: Loops

Fundamentals of Programming. Week 1 - Lecture 3: Loops 15-112 Fundamentals of Programming Week 1 - Lecture 3: Loops May 18, 2016 Basic Building Blocks Statements Tells the computer to do something. Data Types Data is divided into different types. Variables

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

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control ECE15: Introduction to Computer Programming Using the C Language Lecture Unit 4: Flow of Control Outline of this Lecture Examples of Statements in C Conditional Statements The if-else Conditional Statement

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

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #16: Java conditionals/loops, cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Midterms returned now Weird distribution Mean: 35.4 ± 8.4 What

More information

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

1 class Lecture3 { 2 3 Selections // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133 1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 88 / 133 Flow Controls The basic algorithm (and program) is constituted

More information

Why Is Repetition Needed?

Why Is Repetition Needed? Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable

More information

Condition Controlled Loops. Introduction to Programming - Python

Condition Controlled Loops. Introduction to Programming - Python + Condition Controlled Loops Introduction to Programming - Python + Repetition Structures n Programmers commonly find that they need to write code that performs the same task over and over again + Example:

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

Control structure: Repetition - Part 3

Control structure: Repetition - Part 3 Control structure: Repetition - Part 3 01204111 Computers and Programming Chalermsak Chatdokmaiprai Department of Computer Engineering Kasetsart University Cliparts are taken from http://openclipart.org

More information

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input Loops / Repetition Statements Repetition s allow us to execute a multiple times Often they are referred to as loops C has three kinds of repetition s: the while loop the for loop the do loop The programmer

More information

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure Objectives Differentiate between a pretest loop and a posttest loop Include a pretest loop in pseudocode Include

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

Example: Monte Carlo Simulation 1

Example: Monte Carlo Simulation 1 Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149

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

Lecture 8: Context Free Grammars

Lecture 8: Context Free Grammars Lecture 8: Context Free s Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (12/10/17) Lecture 8: Context Free s 2017-2018 1 / 1 Specifying Non-Regular Languages Recall

More information

Syntax of for loop is as follows: for (inite; terme; updatee) { block of statements executed if terme is true;

Syntax of for loop is as follows: for (inite; terme; updatee) { block of statements executed if terme is true; Birla Institute of Technology & Science, Pilani Computer Programming (CSF111) Lab-5 ---------------------------------------------------------------------------------------------------------------------------------------------

More information

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops Chapter 5: Loops and Iteration CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox Motivations Suppose that you need to print a string (e.g.,

More information

UNIT 2B An Introduc0on to Programming (for loops) for Loop (simple version) for loop_variable in range(n): loop body

UNIT 2B An Introduc0on to Programming (for loops) for Loop (simple version) for loop_variable in range(n): loop body UNIT 2B An Introduc0on to Programming (for loops) 1 for Loop (simple version) for loop_variable in range(n): loop body The loop variable is a new variable name The loop body is one or more instruc0ons

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

Repetition and Loop Statements Chapter 5

Repetition and Loop Statements Chapter 5 Repetition and Loop Statements Chapter 5 1 Chapter Objectives To understand why repetition is an important control structure in programming To learn about loop control variables and the three steps needed

More information

Chapter 4: Control structures. Repetition

Chapter 4: Control structures. Repetition Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition

More information

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()

More information

Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions

Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions Lecture 4: Applications CS2504/CS4092 Algorithms and Linear Data Structures Dr Kieran T. Herley Department of Computer Science University College Cork Summary. Postfix notation for arithmetic expressions.

More information

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad Outline 1. C++ Iterative Constructs 2. The for Repetition Structure 3. Examples Using the for Structure 4. The while Repetition Structure

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

Computer Programming

Computer Programming Computer Programming Dr. Deepak B Phatak Dr. Supratik Chakraborty Department of Computer Science and Engineering Session: for statement in C++ Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, 1 Quick Recap

More information

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

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

More information

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points) Name Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Relational Expression Iteration Counter Count-controlled loop Loop Flow

More information

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

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018 Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative

More information

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

Lecture 04 More Iteration, Nested Loops. Meet UTA Jarrett s dog Greta, lying in her nest Lecture 4 More Iteration, Nested Loops Meet UTA Jarrett s dog Greta, lying in her nest Indefinite Loops Rest Chase tail Got tail! Almost got it... Based in part on notes from the CS-for-All curriculum

More information

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 4 Loops 1 Motivations Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred times. It would be tedious to have to write the following statement a hundred times: So, how do

More information

Repetition, Looping. While Loop

Repetition, Looping. While Loop Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

More information

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures Chapter 5: Control Structures II Java Programming: Program Design Including Data Structures Chapter Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled,

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

Principles of Computer Science I

Principles of Computer Science I Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120A - Fall 2004 Lecture Unit 7 Review Chapter 4 Boolean data type and operators (&&,,) Selection control flow structure if, if-else, nested

More information

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

Lecture 2: Writing Your Own Class Definition

Lecture 2: Writing Your Own Class Definition Lecture 2: Writing Your Own Class Definition CS6507 Python Programming and Data Science Applications Dr Kieran T. Herley 2017-2018 Department of Computer Science University College Cork Summary Writing

More information

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Logic is the anatomy of thought. John Locke ( ) This sentence is false. Logic is the anatomy of thought. John Locke (1632 1704) This sentence is false. I know that I know nothing. anonymous Plato (In Apology, Plato relates that Socrates accounts for his seeming wiser than

More information

Chapter 4: Control structures

Chapter 4: Control structures Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition

More information

Chapter 8 Statement-Level Control Structures

Chapter 8 Statement-Level Control Structures Chapter 8 Statement-Level Control Structures In Chapter 7, the flow of control within expressions, which is governed by operator associativity and precedence rules, was discussed. This chapter discusses

More information

Lecture 20: While Loops (Sections 7.3, 7.4)

Lecture 20: While Loops (Sections 7.3, 7.4) http://www.cs.cornell.edu/courses/cs1110/2018sp Lecture 20: While Loops (Sections 7.3, 7.4) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 5: Control Structures II (Repetition) Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input,

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information

lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions

lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions Outline 1 Guessing Secrets functions returning functions oracles and trapdoor functions 2 anonymous functions lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions

More information

UNIT 2B An Introduction to Programming ( for -loops) Principles of Computing, Carnegie Mellon University

UNIT 2B An Introduction to Programming ( for -loops) Principles of Computing, Carnegie Mellon University UNIT 2B An Introduction to Programming ( for -loops) Carnegie Mellon University 1 Announcements Programming assignment 2 is due Thursday night at 11:59 PM Is there anybody who needs help for setting up

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

Lecture Notes, CSE 232, Fall 2014 Semester

Lecture Notes, CSE 232, Fall 2014 Semester Lecture Notes, CSE 232, Fall 2014 Semester Dr. Brett Olsen Week 11 - Number Theory Number theory is the study of the integers. The most basic concept in number theory is divisibility. We say that b divides

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

Conditionals and Loops

Conditionals and Loops Conditionals and Loops Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing steps in a loop Chapter 5 focuses on: boolean expressions conditional

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

Lecture 8. Conditionals & Control Flow

Lecture 8. Conditionals & Control Flow Lecture 8 Conditionals & Control Flow Announcements For This Lecture Readings Sections 5.1-5.7 today Chapter 4 for Tuesday Assignment 2 Posted Today Written assignment Do while revising A1 Assignment 1

More information

Control Structures 1 / 17

Control Structures 1 / 17 Control Structures 1 / 17 Structured Programming Any algorithm can be expressed by: Sequence - one statement after another Selection - conditional execution (not conditional jumping) Repetition - loops

More information

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

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017 Loops! Loops! Loops! Lecture 5 COP 3014 Fall 2017 September 25, 2017 Repetition Statements Repetition statements are called loops, and are used to repeat the same code mulitple times in succession. The

More information

Controls Structure for Repetition

Controls Structure for Repetition Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power

More information

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133 Scanner Objects It is not convenient to modify the source code and recompile it for a different radius. Reading from the console enables the program to receive an input from the user. A Scanner object

More information

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations Suppose that you need to print a string (e.g., "Welcome to Java!") a

More information

Structured Programming. Dr. Mohamed Khedr Lecture 9

Structured Programming. Dr. Mohamed Khedr Lecture 9 Structured Programming Dr. Mohamed Khedr http://webmail.aast.edu/~khedr 1 Two Types of Loops count controlled loops repeat a specified number of times event-controlled loops some condition within the loop

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 10 For Loops and Arrays Outline Problem: How can I perform the same operations a fixed number of times? Considering for loops Performs same operations

More information

1. What is the minimum number of bits needed to store a single piece of data representing: a. An integer between 0 and 100?

1. What is the minimum number of bits needed to store a single piece of data representing: a. An integer between 0 and 100? 1 CS 105 Review Questions Most of these questions appeared on past exams. 1. What is the minimum number of bits needed to store a single piece of data representing: a. An integer between 0 and 100? b.

More information

CS 112: Intro to Comp Prog

CS 112: Intro to Comp Prog CS 112: Intro to Comp Prog Importing modules Branching Loops Program Planning Arithmetic Program Lab Assignment #2 Upcoming Assignment #1 Solution CODE: # lab1.py # Student Name: John Noname # Assignment:

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. Application Of Loops In Actual Software Play again? Re-running specific

More information

Lecture 2: Python Arithmetic

Lecture 2: Python Arithmetic Lecture 2: Python Arithmetic CS1068+ Introductory Programming in Python Dr Kieran T. Herley 2018/19 Department of Computer Science University College Cork Basic data types in Python Python data types Programs

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 02 / 15 / 2016 Instructor: Michael Eckmann Questions? Comments? Loops to repeat code while loops for loops do while loops Today s Topics Logical operators Example

More information