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