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

Similar documents
COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

COMP-202 Unit 4: Programming with Iterations

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Warmup : Name that tune!

COMP-202: Foundations of Programming. Lecture 9: Arrays and Practice Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Warm-Up: COMP Programming with Iterations 1

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Last Class. While loops Infinite loops Loop counters Iterations

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.

Loops. CSE 114, Computer Science 1 Stony Brook University

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

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

Example: Monte Carlo Simulation 1

Bjarne Stroustrup. creator of C++

COMP-202: Foundations of Programming

Introduction to Java & Fundamental Data Types

Repetition Structures

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

Object-Oriented Programming

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

MIDTERM REVIEW. midterminformation.htm

Iteration statements - Loops

COMP 202 Java in one week

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

COMP 202 Java in one week

Topic 5: Enumerated Types and Switch Statements

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Last Class. More on loops break continue A bit on arrays

Darrell Bethea May 25, 2011

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Repetition with for loops

Repetition, Looping. While Loop

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Topic 4 Expressions and variables

COMP-202: Foundations of Programming. Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Introduction to the Java Basics: Control Flow Statements

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Computer Science is...

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

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

Building Java Programs

Top-Down Program Development

McGill University School of Computer Science COMP-202A Introduction to Computing 1

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

Introduction to Java Applications

2.8. Decision Making: Equality and Relational Operators

Computer Programming I - Unit 5 Lecture page 1 of 14

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Full file at

Example: Computing prime numbers

H212 Introduction to Software Systems Honors

Course Outline. Introduction to java

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Data dependent execution order data dependent control flow

Lecture Set 2: Starting Java

Controls Structure for Repetition

COMP 110 Project 1 Programming Project Warm-Up Exercise

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

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

Lecture Set 2: Starting Java

Primitive Data, Variables, and Expressions; Simple Conditional Execution

printf( Please enter another number: ); scanf( %d, &num2);

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

COMP-202 Unit 9: Exceptions

CS 170 Section 3, Spring 2015 Programming in Java Midterm Exam 1. Name (print):

COMP 202. Java in one week

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

STUDENT LESSON A12 Iterations

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

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

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

CompSci 125 Lecture 11

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

Scope of this lecture. Repetition For loops While loops

Conditional Execution

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Repetition, Looping CS101

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

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Programming Basics. Digital Urban Visualization. People as Flows. ia

Oct Decision Structures cont d

CMPT 125: Lecture 3 Data and Expressions

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

Object Oriented Programming. Java-Lecture 6 - Arrays

Transcription:

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. Tutorial by Priya: Friday, 15 th May at 10:30 in TR3120 Reminder : Assignment submission on Sunday!!!

Correction To a Slide from Lecture 2 Escape Characters Use an escape sequence for punctuations or spacing. \n NewLine \t Tab \ To have double quotes inside a string \{ \( \; To escape special symbols \\ To escape the escape character!!!!!

Boolean Expressions Review What data type and value do the following expressions evaluate to? (5 / 4) < (5.0 / 4.0) ((int) 3.1 == 3) && (2.0 > 1) In the following expressions, is it possible to come up with an assignment to X and Y such that the expression evaluates to true? (X Y) (!Y!Y) (X &&!X) (!X (Y && Y))

Review Mathematical Expressions In which expression could the parentheses be removed without changing the value of the expression? x * (y + z) (y x) / 3 x * 3 /(y + 2) (y % 3) + 2 The value of 5 / 2.0 and the value of 5.0 / 2 are the same. TRUE FALSE What is the output? int i = 10; int n = i++; System.out.println( Value i = + i + and n = + n); n = ++i; System.out.println( Value i = + i + and n = + n);

if else, if else if : Review Every statement with if must also include else. TRUE [FALSE] What will be the value of b after the following section of code executes: int a = 4, b = 0; if (a < 3) b = 4; else if ( (a < 10) && (b>0) ) b = 3; else if ( (a > 5) (b!=0) ) b = 2; A. 1 B. 0 C. 3 D. 4

This Lecture Loops While Loop For Loop Arrays One step at a time.

Loops (Repetitions)

Recall: if statement if (Condition) { // some code here } // code here happens regardless Condition evaluates to type boolean The if statement defines a block of code that happens if condition evaluates to true.

Control Flow if statements let us choose whether to execute some code, or to choose between multiple blocks of code to execute. Another way to control the flow of the program: execute something multiple times. Example: Counting the number of Apples!! Our program would look something like,

int count = 0 Copy and Paste? if ( Basket_A is not Empty ) { count = count + 1;} else {System.out.println( No. of Apples = + count);} if ( Basket_A is not Empty ) { count = count + 1;} else {System.out.println( No. of Apples = + count);} if ( Basket_A is not Empty ) { count = count + 1;} else {System.out.println( No. of Apples = + count);}

I will complete my practice exercises regularly. I will complete my practice exercises regularly. I will complete my practice exercises regularly. I will complete my practice exercises regularly. I will complete my practice exercises regularly. I will complete my practice exercises regularly. I will complete my practice exercises regularly. I will complete my practice exercises regularly. I will complete my practice exercises regularly.

Problems 1. Annoying who wants to copy/paste that much 2. Error prone easy to make mistake 3. Difficult to maintain hard to edit or fix mistakes 4. Does not generalize what if something changes each time you execute it? 5. Variable number of steps what if you don't know how many steps you need?

Solution: Loops In Java, there are two main types of loops: while loops for loops

while Loops Syntax: <initialize> while ( <condition> ) { // block of code } // go here only after // we fail the condition check Note similarity to if statement's syntax: if ( <condition> ) { // block of code } // go here afterwards

if vs. while Syntactically, the only difference between if and while is that the keyword is different Semantically, the effect of while vs. if is that: while: code block is repeatedly executed as long as the condition is evaluated to be true. if: code block is executed at most once, if the condition is evaluated to be true.

while Loops

while Example int x = 0; while (x < 4) { } System.out.println("Write this again"); x++; The purpose of the variable x is to act as the loop counter. It keeps track of how many times the loop has run.

How does the while work? Trace the execution of the loop. How many times does it execute? int x = 0; while (x < 4) { } System.out.println("Write this again"); x++; Step 1 Step 2 Initialize Condition Check Condition Fail Step 3 Loop body Execution Once the condition fails

Iteration??? An iteration is a single execution of the instructions in the body of a loop. The previous loop had 4 iterations: first iteration: x = 0 second iteration: x = 1 third iteration: x = 2 fourth iteration: x = 3

When is the Condition Checked? The condition of a while loop is checked once per iteration of the loop, before the block of code is executed. int x = 0; while (x < 4) { x = x + 10; System.out.println( x is now at least 10 ); x = x - 10; x++; } How many times does this loop iterate for?

Practice Exercise What does this code do? Recall that % is the remainder operator. int i = 0; while (i < 100) { if (i % 3 == 0) { System.out.println(i); } i++; }

Practice Exercise What does this code do? int x = 0; while (x < 4) { System.out.println(x); } The above code creates an infinite loop. It goes on forever because we never change the value of x!!!!

Be Careful An extra, misplaced ; can ruin your program (and your day) int x = 0; while (x < 4); { x++; } This creates an infinite loop.

How Many Iterations 1 int x = 4; while (x > 4) { System.out.println("This is the song + that never ends. ); x++; }

How Many Iterations 2 int x = 6; while (x > 4) { System.out.println("This is the song that never ends. ); x--; }

How Many Iterations 3 int x = 6; while (x > 4) { System.out.println("This is the song that never ends. ); x++; }

How Many Iterations 4 int x = 3; while (x < 11) { System.out.println("This is the song that never ends. ); x += 2; }

How Many Iterations 5 int x = 3; while (x!= 10) { System.out.println("This is the song that never ends. ); x += 2; }

Off-By-One Error This code is supposed to print all positive values of x up until 5: int x = 1; while (x < 5) { System.out.println(x); x++; } How do we fix it?

Off-By-One Error Prevention To avoid off by one errors, you should always manually confirm the first step of a loop as well as the last step of a loop. Make sure the numbers are what you are expecting.

Template for n Repetitions If you have code that you want to perform a fixed number of times, one way to do that is with a while loop and a counter: int counter = 0; while (counter < n) { //whatever you want done counter++; }

i = 0 while i < 100 end write I will complete my practice exercises regularly. i++

Try it out!!! Write a program that repeatedly asks the user for their favourite course until the user enters "COMP 202" as the input.

Common Loop Theme Very often in loops, one will do three things: 1. Perform some initialization before the loop starts 2. Check a condition before each iteration of a loop 3. Perform some update step at the end of each iteration

Template for n Repetitions If you have code that you want to perform a fixed number of times, one way to do that is with a while loop and a counter: int counter = 0; Initialization while (counter < n) Condition before each iteration { //whatever you want done counter++; } Update at the end of each iteration

for Loops Because this pattern is so common, Java has a for loop, which is similar to a while loop, but has these three parts built in to the loop. for (initialization; condition; update) { // loop body }

for i = 1 to 100 next i end write I will complete my practice exercises regularly.

for Loops for (initialization; condition; update) { Happens once per loop only, before the first check of the condition // loop body Happens at the end of every iteration. Usually used to update a variable declared in the initialization } Happens before every iteration. If it evaluates to true, the loop body will run.

How does the for work? Trace the execution of the loop. for (int x = 0; x < 4; x++) { Step 1 Initialize Step 2 Condition Check Step 4 Update Condition Fail System.out.println("Write this again"); Step 3 Loop body Execution } Once the condition fails

for vs. while for (int i = 0; i < 4; i++) { System.out.println(i); } int i = 0; while (i < 4) { System.out.println(i); i++; } The only difference is that the variable i is still defined after the while loop, whereas it is no longer in scope and therefore doesn't exist anymore after the for loop. Could be a good thing don't mix up variables!

for Loop as a while Loop int x = 0; for (; x < 4; ) { System.out.println(x); x++; } You are unlikely to do this when writing good, readable code. But you can have any block of the for loop empty. One can even have all the blocks empty. (What would happen?) for ( ; ; ) { //Some operation }

When To Use Which One Indefinite number of iterations while e.g., Keep doing something until a certain event occurs, or while a certain condition is true. Fixed or easily calculable number of iterations for e.g., Go through all elements of a list (which we will see soon), or a fixed number of elements

Which loop to use? Which loop would you use for our original problem of counting the number of apples in a basket???

Example Question 1) What will the following code print? int count = 1; while (count <= 3) { System.out.print(count + " "); count++; } A. 1 2 3 B. 1 2 C. 3 D. 1 1 1 2) What will the following code print? ANSWER: ( A ) int count = 4; while (count < 4) { ANSWER: ( B ) System.out.print(count + " "); count++; } A. 1 2 3 B. Nothing printed C. 4 D. 1 1 1

Example Question 1) What will the following code print? int count; for (count = 4; count > 1; count--) System.out.print(count + " "); ANSWER: ( C ) A. 1 2 3 4 B. 1 2 3 C. 4 3 2 D. 4 3 2 1 2) What will the following code print? int count; for (count = 8; count > 1; count--){ count--; System.out.print(count + " "); } ANSWER: ( D ) A. 8 7 6 5 B. 7 5 3 C. 8 6 4 2 D. 7 5 3 1

Try it out!! A prime number is a positive integer >= 2 whose only divisors are 1 and itself. Write a program that checks whether an integer is prime. How to start? Hints: Break it down! How do you check if the candidate number has a particular divisor? Which numbers do you have to check as possible divisors?

Loopception (Nested Loops) Loop within a loop!! You can have multiple levels of loops! This is called having nested loops. This is often useful when we have data with multiple dimensions. e.g., print the multiplication table between 1 and 9, inclusive i.e., 1x1=1, 1x2=2, 1x3=3, 1x9 = 9 2x1=2, 2x2=4, 2x3=6, 2x9 = 18

One Row of the Table Suppose we have one fixed integer: int x = 4; for (int y = 1; y < 10; y++) { System.out.print(x + "x" + y + "=" + (x * y) + ", "); } System.out.println(); // add line break

All the Rows of the Table Now, add another for loop outside to have the integer range. for (int x = 1; x < 10; x++) { for (int y = 1; y < 10; y++) { System.out.print(x + "x" + y + "=" + (x * y) + ", "); } System.out.println(); // add line break } We declare and initialize a new y variable for each iteration of the outer loop!

Try it out!! Print a multiplication table, as above, but to avoid nearduplicates like 5x4 and 4x5, only print those entries where the first number is less than or equal to the second number (i.e., 4x5). Do not use if statements.

Arrays

Computing Mean We want to ask user to enter several numbers and give the mean as output. What would we do? 1)We need to ask the user to enter numbers and store the result into a variable. 2)We need to repeat this several times 3)As we go, we should store the sum of the numbers they have entered 4)At the end, divide by the total number of numbers they entered.

Computing Mean 1)We need to ask the user to enter numbers and store the result into a variable. Scanner 2)We need to repeat this several times For Loop 3)As we go, we should store the sum of the numbers they have entered Variable that we keep adding to 4)At the end, divide by the total number of numbers they entered. Store how many numbers are entered

import java.util.scanner; public class MeanProgram { } Computing Mean public static void main(string[] args) { final int TOTAL_NUM = 100; double total = 0; Scanner reader = new Scanner(System.in); for (int i = 0; i < TOTAL_NUM; i++) { double nextnumber = reader.nextdouble(); total += nextnumber; } System.out.println(total / TOTAL_NUM); }

Computing Mean What if we wanted to store all the numbers for later use??? Store the 100 numbers into 100 different, unrelated variables. int fml1, fml2, fml3, fml4, fml5, fml6, fml7, fml8, fml9, fml10, fml11, fml12, fml13, fml14, fml15, fml16, fml17, fml18, fml19, fml20, fml21, fml22, fml23, fml24, fml25, fml26, fml27, /*okay I'm tired of typing all these fml's. I need a drink now...*/ fml99, fml100;

Storing Multiple Values We often want to store multiple values of the same type: Daily high temperature in Montreal over the past 30 years Lines of text in a chat conversation Marks of students in COMP 202 This lets us compute things about the entire sequence of data by looping through each entry.

Not the Way to Go Declare one variable per entry? double mark1, mark2, mark3, mark4, mark5, mark6, mark7, mark8, mark9, mark10, mark11, mark12, // AAAAHHHHHHHHHHH! Annoying to read and write Error-prone, impossible to edit How do we loop through these variables?

Arrays An array is a container object that holds a fixed number of values of a single type. The length of the array is established when the array is created. After its creation, the length is fixed. e.g., we can have an array of ints, an array of doubles, an array of Strings, etc., but not an array that has both ints and doubles.

Array Variables Since an array conveniently groups together multiple items, we can access the values in the array by using the same variable. You can recognize an array variable by its []. String[] an array of Strings int[] an array of ints boolean[] an array of booleans double[] an array of doubles int[][] an array of arrays of ints

One Mystery Solved public static void main(string[] args) This is a String array called args. Though we still don't know what args does yet

Declaring Array Variables Exactly the same as before: type[] var_name; This creates a variable, but we still need to create the actual array object itself.

Creating Arrays: Method 1 At the same time as you declare the variable, surrounded by {} boolean[] toocold = {true, false, true, true, false}; double[] marks = {100.0, 100.0, 100.0, 100.0}; String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; This method doesn't work if you don't know the values before the program runs.

Creating Arrays int[] myarray = {1, 5, 6, 3}; 1) Allocate this memory. Find a free spot in memory that has enough space to hold four integers. 2) Store the address of the beginning of the memory that was just allocated into the variable myarray. myarray 3) Set values to this newly allocated memory. myarray 1 5 6 3

Creating Arrays: Method 2 type[] var_name = new type[size]; (omit type[] if var_name was already declared) int NSTUDENTS = 97; String[] studentnames = new String[NSTUDENTS]; double[] studentmarks = new double[nstudents];

Creating Arrays Declaring, allocating, and initializing arrays can also be broken up into multiple steps: int[] myarray; Variable myarray is created to point to an array. myarray = new int[4]; myarray myarray[0] = 1; myarray Indices 1 [0] [1] [2] [3]

Using An Array When you create an array of size n, you are creating n contiguous places in memory to store values of the same type. Refer to each element by its index, starting from 0. String[] instructors = { Sandeep", "Jackie", Juan"}; instructors[0] instructors[1] instructors[2] Sandeep" "Jackie" Juan"

Array Example Scores of 8 students: int [ ] scores = {100, 95, 25, 99, 39, 100, 100, 90} scores Indices 100 95 25 99 39 100 100 90 [0] [1] [2] [3] [4] [5] [6] [7] Here is an array with 8 values in it. Each spot of the array has a value and an index. The value is any legitimate value of the type of the array, in this case int. The index is an integer. Interestingly the counting starts from 0 instead of 1. To get or set values of an array, we will use a similar syntax to a normal variable, except we have to specify which value of the array we wish to get or set. We do this by using the index.

Example: Compute Mean Mean of the class scores: int [ ] scores = {100, 95, 25, 99, 39, 100, 100, 90}; int sumscores = scores[0] + scores[1] + scores[2] + scores[3] + scores[4] + scores[5] + scores[6] + scores[7]; double avgscore = sumscores / 8; System.out.println(avgScore); I feel like there's a smarter way to do this

Example: Compute Mean int [ ] scores = {100, 95, 25, 99, 39, 100, 100, 90}; int i = 0; int sumscores = 0; while (i < 8) { sumscores = sumscores + scores[i]; i++; } double avgscore = sumscores / 8; System.out.println(avgScore);

Try it out: Be Even Smarter The previous code does not generalize: Assumes a fixed number of student scores (8) Use array_name.length to get the length of an array Change the previous example: To use a for loop instead of a while loop To use.length so that it works for arrays of any length.

Need to Initialize Values What happens if we do this? String[] names = new String[35]; // print first name System.out.println(names[0]); We get a null because we've created a place to store a String, but we haven't set its value yet. Remember to initialize the entries of your arrays if you use method 2!

Objects Arrays, Scanners, and Strings are Objects. You can tell because you need new to create them. (Well, except Strings. Strings are special.) In fact, except for the primitive data types (the ones that start with lowercase, like int, double, float, byte, boolean, etc.), everything in Java is an Object. Objects are data bundled with methods to work with the data, and properties.

Methods of Objects Some String methods:.equals(),.length(),.tolowercase() Some Scanner methods:.nextline(),.nextint(),.nextdouble() In general: object.method_name() Arrays have no methods. Instead, they have a property called length.length Because this is not a method, there is no () after

Example Question 1) Which of the following statements are valid array declarations? A. int number(); B. int number[]; C. double[] marks; D. number int[]; ANSWER: ( B and C ) 2) What will be the output of following Java code block? public static void main(string argv[]) { int ary[]=new int[]{1,2,3}; System.out.println(ary[1]); } A. 1 B. Compilation Error: Incorrect Syntax C. 2 D. Compilation Error: size of array must be defined ANSWER: ( C )

Example Question 3) What is the value of a[1] after the following code is executed? int[] a = {0, 2, 4, 1, 3}; for (int i = 0; i < a.length; i++) { a[i] = a[ a[ i ] ]; } A) 0 B) 1 C) 2 D) 3 E) 4 ANSWER: ( E )

Summary Control Flow While Loop For Loop Arrays