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

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

Warmup : Name that tune!

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

Topic 5: Enumerated Types and Switch Statements

COMP-202 Unit 4: Programming with Iterations

COMP-202: Foundations of Programming

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

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

Warm-Up: COMP Programming with Iterations 1

Bjarne Stroustrup. creator of C++

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

Repetition Structures

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

Last Class. While loops Infinite loops Loop counters Iterations

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

Timing for Interfaces and Abstract Classes

Introduction to the Java Basics: Control Flow Statements

COMP-202: Foundations of Programming. Lecture 6: Conditionals Jackie Cheung, Winter 2016

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

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

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

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Example: Monte Carlo Simulation 1

Repetition with for loops

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

H212 Introduction to Software Systems Honors

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

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

Repetition, Looping CS101

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

Visual Programming. Lecture 3: Loops, Arrays. Mahmoud El-Gayyar

Lesson 36: for() Loops (W11D1)

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

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

Control Structures in Java if-else and switch

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

Tutorial 06. Conditional statement: if then, if else, switch

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

CS 106 Introduction to Computer Science I

CS1150 Principles of Computer Science Loops (Part II)

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

Repetition, Looping. While Loop

Recap: Assignment as an Operator CS 112 Introduction to Programming

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

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

CS 106 Introduction to Computer Science I

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

! 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

Final Exam Practice. Partial credit will be awarded.

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

Math Modeling in Java: An S-I Compartment Model

Introduction to Computing Lecture 05: Selection (continued)

CS 112 Introduction to Programming

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

COMP-202: Foundations of Programming. Lecture 7: Strings and Methods Jackie Cheung, Winter 2015

Building Java Programs Chapter 2

Building Java Programs

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

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Lecture Set 4: More About Methods and More About Operators

Scope of this lecture. Repetition For loops While loops

Building Java Programs

CompSci 125 Lecture 11

Building Java Programs

COS 126 Exam Review. Exams overview Example programming exam Example written exam questions (part 1)

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

Computer Programming I - Unit 5 Lecture page 1 of 14

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2015

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

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

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

COMP 202 Java in one week

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

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

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

Building Java Programs

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Building Java Programs Chapter 2

CS110D: PROGRAMMING LANGUAGE I

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true;

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

New York University Introduction to Computer Science Midterm2 Sample Problems 2013 Andrew I. Case. Instructions:

CE221 Programming in C++ Part 1 Introduction

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

Final Examination Semester 2 / Year 2011

Activity 6: Loops. Content Learning Objectives. Process Skill Goals

COMP-202: Foundations of Programming. Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016

CS125 : Introduction to Computer Science. Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals

Computer Science is...

Iteration statements - Loops

CIS November 14, 2017

CIS 1068 Netflix Challenge New assignment posted soon Lab grades November 14, 2017

Object Oriented Programming. Java-Lecture 6 - Arrays

Lecture 17. Instructor: Craig Duckett. Passing & Returning Arrays

COMP 111. Introduction to Computer Science and Object-Oriented Programming

Transcription:

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

Review What is the difference between a while loop and an if statement? What is an off-by-one error? 2

while Loops while (condition) { // block of code } // go here only after // we fail the condition check 3

Initiation, condition, update FOR LOOPS 4

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 5

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++; Initialization Condition before each iteration Update at the end of each iteration 6

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 7

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

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! 9

Can Use for Loop as while Loop int x = 0; for (; x < 4; ) { System.out.println(x); x++; } You are unlikely to do this when writing good, readable code. 10

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 11

Exercise A prime number is a positive integer >= 2 whose only divisors are 1 and itself. Write a method 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? 12

Exercise Part 2 Write a program that calls the method you just wrote in order to print all the prime numbers from 1 to 1000. Use a for loop. 13

A loop inside a loop NESTED LOOPS 14

Loopception 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 15

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 16

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! 17

Exercise Print a multiplication table, as above, but to avoid near-duplicates 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. 18

Storing more than one thing ARRAYS 19

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. 20

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? 21

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. 22

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 23

Our Old Friend public static void main(string[] args) This is a String array called args. args contains the inputs you gave when running the program 24

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. 25

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 length or values before the program runs. 26

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

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 = { Yang", "Jackie", Melanie"}; instructors[0] instructors[1] instructors[2] Yang" "Jackie" Melanie" 28

Example: Compute Mean Highs in Montreal over seven days: double[] temps = {-4.2, -1.9, -17.0, -14.4, -4.7, -2.4, -14.9}; double sumtemps = 0.0; sumtemps = temps[0] + temps[1] + temps[2] + temps[3] + temps[4] + temps[5] + temps[6]; double avgtemps = sumtemps / 7; System.out.println(avgTemps); I feel like there's a smarter way to do this 29

Example: Compute Mean double[] temps = {-4.2, -1.9, -17.0, -14.4, -4.7, - 2.4, -14.9}; int i = 0; double sumtemps = 0.0; while (i < 7) { sumtemps += temps[i]; i++; } double avgtemps = sumtemps / 7; System.out.println(avgTemps); 30

Exercise: Be Even Smarter The previous code does not generalize: Assumes a fixed number of days (7) 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. 31