COMP-202 Unit 4: Programming with Iterations

Size: px
Start display at page:

Download "COMP-202 Unit 4: Programming with Iterations"

Transcription

1 COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

2 Repetition Statements Repetition statements allow us to execute a block of code or (set of) statement(s) multiple times; -These statements are normally called loops COMP Programm 2

3 Repetition Statements in Java -Java has two main kinds of repetition statements: the while loop and the for loop - While and for loops are equivalent However, in certain circumstances, choosing one of these statements over the other results in a program that is easier to understand. COMP Programm 3

4 Part 1: While loops

5 Recall : If statement if (condition) { //some code here... //code here happens regardless COMP Programm 5

6 Recall : If statement if (condition) { //some code here... //code here happens regardless An if statement defines a block of code. COMP Programm 6

7 Recall : If statement if (condition) { //some code here... //code here happens regardless We test a condition which can be any boolean expression. COMP Programm 7

8 Recall : If statement if (condition) { //some code here... //code here happens regardless If the condition evaluates to true then we execute the block of code once. Otherwise we do not. COMP Programm 8

9 Benefits of If Statements We can perform actions or commands some of the time but not all. Forces us to organize things : Certain events will only happen in one case. This creates a clear division. COMP Programm 9

10 Doing the same thing many times Sometimes, we will want to execute the same block of code many times. How can we do that? COMP Programm 10

11 Copy / Paste The naïve thing to do is copy paste your code. What are some problems with this? COMP Programm 11

12 Copy / Paste 1)Annoying : Who wants to copy / paste that much 2)Error prone : Easy to make a mistake 3)Difficult to maintain : Hard to edit or fix mistakes (you have to edit the same code many times which can lead to more errors) 4)What if you don't know ahead of time how many steps you need? COMP Programm 12

13 while loops In Java, we can create a while loop. A while loop is a statement that defines a block of code that continues to execute until a condition is false. COMP Programm 13

14 if statement vs while loop if (condition) { //block of code //Go here //no matter what while (condition) { //block of code //repeat condition // check //Go here //only after //condition is false COMP Programm 14

15 Syntax difference Syntactically, the only difference between a while loop and an if statement is the word while instead of if. The effect of this change is that the block of code continues to be repeated as long as condition is evaluated to be true. COMP Programm 15

16 Doing things multiple times There is no command in Java to perform the same thing many times. However, if we are clever with our variables, we can write code that will execute many times. Remember we will keep on repeating the body of a while loop as long as a condition is true. COMP Programm 16

17 Use a variable to count Idea: 1)Create a variable and set it equal to 0. 2)Every time our loop body executes, add one to this variable 3)At any point, the variable's value will be equal to the number of steps we've done so far. We can then check as a condition for the while loop that the number of steps is less than any desired number. COMP Programm 17

18 Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; COMP Programm 18

19 Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; The purpose of the variable x here is to act as a loop counter It keeps track of how many times the loop has executed COMP Programm 19

20 Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; Initially, we set the variable x equal to 0. This means the first time we check the condition x < 4, the condition is true, so we execute the loop body. COMP Programm 20

21 Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; Next, we execute the loop body, which first involves printing to the screen. COMP Programm 21

22 Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; The next command of the loop body is increment x. This gives x the value of 1. COMP Programm 22

23 Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; Once the loop body finishes at the, the condition is then rechecked. Since x = 1 and 1 < 4, the block of code happens again. COMP Programm 23

24 Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; This procedure happens 2 more times. On the 4 th step, we test the condition and x = 3. Then after printing and adding 1 to x, x is now 4. COMP Programm 24

25 Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; If x == 4, then the condition is false, so we exit the loop and resume the code after the loop block has finished. COMP Programm 25

26 Definition: iteration An iteration is a single execution of the instructions in the loop body. The previous loop had 4 iterations. One each for x=0, x=1, x=2, x=3

27 Important Clarification The condition of the while loop is only evaluated 1 time per step or iteration of the loop right before the block of code executes. The significance of this is if the condition changes inside the loop, the loop will keep going. COMP Programm 27

28 Important Clarification int x = 0; while (x < 4) { x = x + 10; System.out.println( x is now 10 ); x = x - 10; x++; COMP Programm 28

29 Important Clarification int x = 0; while (x < 4) { x = x + 10; System.out.println( x is now 10 ); x = x - 10; x++; Although x = 10 at this point, the loop condition is not tested until later, when x=1 again COMP Programm 29

30 Practice Exercise: Figure out what the following loop does. int i = 0; while (i < 100) { if ( i % 3 == 0) { System.out.println(i); i++; COMP Programm 30

31 Practice Exercise: Since i % 3 == 0 for any numbers that are multiples of 3, that loop prints all the multiples of 3. An alternate way to do the same thing is to replace i++ with i = i + 3 COMP Programm 31

32 What will this loop do? int x = 0; while (x < 4) { System.out.println(x); COMP Programm 32

33 It goes on forever! The above is what is known as an infinite loop It will go on forever because we never change the value of x, which will always be less than 4 We will keep printing 0 to the screen. This is known as an infinite loop COMP Programm 33

34 Tangent: Halting Problem (1) Alan Turing investigated the problem of: Given a computer program in a language like Java, can you detect if there is an infinite loop in it? He proved that you can not write a computer program to test definitively whether any computer program has an infinite loop. You'll know if the program ends, but not if it has an infinite loop COMP Programm 34

35 Tangent: Halting Problem (2) This seems like a useless thing to prove, but it has consequences: 1)Philosophically, computers can't solve everything 2)Sometimes, we can take a more useful problem and prove that we can't solve it either, because if we could, then we'd be able to solve the Halting Problem COMP Programm 35

36 How many iterations does the following loop consist of? int x = 4; while (x > 4) { System.out.println( I have to write + this over and over. ); x++;

37 How many iterations does the following loop consist of? int x = 4; while (x > 4) { System.out.println( I have to write + this over and over. ); x++; 0 iterations because x is not > 4 at the beginning

38 How many iterations does the following loop consist of? int x = 6; while (x > 4) { System.out.println( I have to write + this over and over. ); x--;

39 How many iterations does the following loop consist of? int x = 6; while (x > 4) { System.out.println( I have to write + this over and over. ); x--; 2 iterations : 1 for x = 6, 1 for x = 5

40 How many iterations does the following loop consist of? int x = 6; while (x > 4) { System.out.println( I have to write + this over and over. ); x++;

41 If you add one to the biggest value that can fit into an int, you'll cycle around to the most negative # possible (e.g. negative 2 billion) How many iterations does the following loop consist of? int x = 6; while (x > 4) { System.out.println( I have to write + this over and over. ); x++; It seems infinite. However, be careful to remember that ints have a max value.

42 How many iterations does the following loop consist of? int x = 3; while (x < 11) { System.out.println( I have to write + this over and over. ); x += 2;

43 How many iterations does the following loop consist of? int x = 3; while (x < 11) { System.out.println( I have to write + this over and over. ); x += 2; 4 iterations: x=3, x=5, x=7, x=9

44 Off-By-One Errors It is a common logical error or bug to write loop conditions that result in the loop body being executed one time too few, or one time too many You should always test your code to check that your loops conditions do not cause such errors. COMP Programm 44

45 Off-By-One Errors Example //this code is supposed to print all positive //values of x up until 5: What is wrong with it? int x = 1; while (x < 5) { System.out.println(x); x++; COMP Programm 45

46 Off-By-One Errors Example The problem is the last iteration is x = 4. We should change the condition to: (x <= 5) OR (x < 6) COMP Programm 46

47 Off-By-One Errors Tips 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. COMP Programm 47

48 What will this loop do? int x = 0; while (x < 4) { System.out.println(x); This is an infinite loop that goes on forever! COMP Programm 48

49 One command while loops Like if statements, if you put a command following the while loop without a {, it will only include 1 line in your loop. -A very bad thing to do: int x = 0; while (x < 4); { // this is an infinite loop now! x++ COMP Condition 49

50 General loop tips Try to think of exactly what it is that you want to do over and over again Figure out the range of values you want to try again and again. Is the loop counter also used in the computation? Make sure that your loop starts or initializes with the right result Make sure that your loop terminates with the correct result COMP Programm 50

51 Programming Idioms We would like to build up a list of idioms for programming These are programming structures that initially may be complex and require us to figure out what they mean. However once we've seen them before, we'll learn them and not need to look at them very carefully. COMP Programm 51

52 Idiom: Repeating the same thing n times int i = 0; while (i < numdesiredexecutiontimes) { action(s) to perform multiple times i++; The idea is that we will see this so many times we don't need to think about if i should start from 0 or 1, should it be < or <=, etc. COMP Programm 52

53 Example: Printing Exams int i = 0; while (i < NUMBER_STUDENTS_IN_CLASS) { printpaper(); i++; Here we are doing the same exact thing NUMBER_STUDENTS_IN_CLASS times COMP Programm 53

54 Idiom 2: Doing something for every number in a range int i = 1; while (i <= n) { some statements that depend on i i++; This loop would do something for every value of i from 1 until n (inclusive) COMP Programm 54

55 Example: Print every integer from 1 to n int i = 1; while (i <= n) { System.out.println(i); i++; COMP Programm 55

56 Exercise: While loop In unit 3, we looked at an example where we wanted to read 10 numbers and convert all of them from Fahrenheit to Celcius. Write a program using a while loop that reads 10 numbers from the keyboard, converts them one at a time to Fahrenheit, and prints the result to the screen. (Answers on next slide: no peaking!) COMP Programm 56

57 import java.util.scanner; public class FahrenheitConverter { public static final double NUM_CONVERSIONS = 10; public static void main(string[] args) { int i = 0; Scanner reader = new Scanner(System.in); while (i < NUM_CONVERSIONS) { System.out.println(convertToCelcius(reader.nextInt())); i++; public static double converttocelcius(double fahrenheit){ return (fahrenheit 32.0) * 5.0 / 9.0; COMP Programmin 57

58 Exercises: -Write a method that counts the number of factors of a number n (input) and returns the value. -Write a method that takes the sum of all the factors of a number n (input). COMP Programm 58

59 Part 2: Class Variables and Constants

60 Class Constants (final) Very often, you will have a constant that you want to use throughout your entire class in many different methods. -Improves readability -Avoid errors -Easier to maintain Remember that we can declare a constant the same way as a variable, except we add the word final before the type. COMP Programm 60

61 Class Constants (final) Sometimes, you'll declare a constant inside a method as normal, but you can also declare a final static constant outside of any method, but inside of a class: public class ConstantExample { public static final int NUM_STATES = 50; public static final int NUM_PROVINCES = 10; public static void main(string[] args) {... COMP Programm 61

62 Class Constants (final) Now, throughout you code you won't have mysterious magic numbers like 50 and 10 throughout your code. It's easier to say for sure which 50's refer to the number of states and which 50's refer to something entirely different. Also will be much easier if the constant changes over time for whatever reason. COMP Programm 62

63 Scope of variables and constants Remember, that any time you create a variable or constant, it's scope is only within the block of code it was declared in. This means that anywhere inside that block of code, the variable or constant is available and outside the block it is not. COMP Programm 63

64 Scope of variables and constants public class CustomerService { public static final String COMPANY_NAME = Videotron ; public static void answercall() { System.out.println( Your call is very important to us. +Please stay on the line and a + COMPANY_NAME + representative will be with your shortly public static void humanpicksup() { System.out.println( You owe + COMPANY_NAME + money for random + surcharges. We hope you'll continue to enjoy our service. ) waitforswearing(); //The identifier COMPANY_NAME is now available throughout your entire class // CustomerService COMP Programm 64

65 Scope of class variables public class Scope { public static String companyname = Videotron ;... Variables work the same way. This means that one thing you can do to share a variable between methods is create a variable outside of any method. In this case, you'll still want to write static. This is not generally good practice unless you know what you are doing! COMP Programm 65

66 Class Variables These sorts of variables (or constants) are known as class variables (or class constants). They are called this because they belong to the entire class as opposed to one method. COMP Programm 66

67 Example of bad use of class variables import java.util.scanner; public class BadFahrenheitConversion { public static double degrees = 0.0; public static Scanner reader = new Scanner(System.in); public static void main(string[] args) { degrees = reader.nextdouble(); converttocelcius(); System.out.println(degrees); public static void converttocelcius() { degrees = (degrees 32.0) * 5.0 / 9.0; COMP Programm 67

68 Problems with this: Leads to bugs! 1)The variable degrees is used for different purposes (first it is fahrenheit then it is degrees) Confusing! 2)The method converttocelcius() has a side effect which is unexpected. 3)The code is not reusable. What if you copied this into a different program that already had a variable degrees defined? 4)Because you are doing 2 things with 1 variable, the print statement could be separated from when the value is set. 5)reader can be used by a different method and the main() method wouldn't know. COMP Programm 68

69 Better (no class variables) import java.util.scanner; public class BadFahrenheitConversion { public static void main(string[] args) { Scanner reader = new Scanner(System.in); double fahrenheitdegrees = reader.nextdouble(); double celciusdegrees = converttocelcius(fahrenheitdegrees); System.out.println(celciusDegrees); public static double converttocelcius(double degrees) { return (degrees 32.0) * 5.0 / 9.0; COMP Programm 69

70 Static constants Static constants do not normally have this problem since their values don't change. There are still cases where it is better to pass a constant to a method rather than use it. We will see later on that there are indeed times to create static variables, but for starters we should not use static variables and should only use static constants with simple types (i.e. int, double, float, boolean, etc. String is OK too despite the capital S) COMP Programm 70

71 Part 3: Top Down Programming

72 Example A prime number is a positive integer >= 2 whose only divisors are 1 and itself. Write a method that calculates whether a number is prime or not using a while loop. The method should take as input an int and return a boolean value of true if the number is prime and false otherwise. COMP Programm 72

73 Steps to solve this: First, you should figure out the input and the output of the method. This is normally given in this course, sometimes in words, sometimes in Java terminology With this knowledge, you can write the method header. If this step is not easy, then you need to think about the problem more to understand what it is you are trying to solve! COMP Programm 73

74 Steps to solve this: public static boolean isprime(int n) { COMP Programm 74

75 Steps to solve this: The next thing to figure out is an algorithm to solve the problem. This is not always easy. In the case of prime numbers, how can we figure out if a number n is prime (if we were doing it by hand)? COMP Programm 75

76 Steps to solve this: 1)Check every number from 2 up until n 1. 2)If any of these numbers evenly divide n (i.e. are factors of n), then n is not prime 3)If none of them divide n, then n is prime COMP Programm 76

77 Steps to solve this: 1)Check every number from 2 up until n 1. 2)If any of these numbers evenly divide n (i.e. are factors), then n is not prime 3)If none of them divide n, then n is prime The word every strongly implies you'll need some sort of loop. COMP Programm 77

78 Steps to solve this: 1)Check every number from 2 up until n 1. 2)If any of these numbers evenly divide n (i.e. are factors), then n is not prime 3)If none of them divide n, then n is prime The if means we'll need some sort of if statement. n not equals prime is our conclusion and in Java will translate to a return statement with the value false COMP Programm 78

79 Steps to solve this: 1)Check every number from 2 up until n 1. 2)If any of these numbers evenly divide n (i.e. are factors), then n is not prime 3)If none of them divide n, then n is prime One thing to be very careful of is that none means we have to check ALL of the numbers to make the conclusion. That is, if we see 1 factor, we can conclude it's not prime, but if we see 1 non-factor, we can't conclude it's prime COMP Programm 79

80 Now lets analyze each step in detail 1)Check every number from 2 up until n 1. 2)If any of these numbers evenly divide n (i.e. are factors), then n is not prime 3)If none of them divide n, then n is prime We know how to do something for every number. This is idiom #2. We know the code for printing every number from 1 to n. We just have to modify it to go from 2 until n-1 and to do other stuff instead of print! COMP Programm 80

81 Steps to solve this: 1)Check every number from 2 up until n 1. 2)If any of these numbers evenly divide n (i.e. are factors), then n is not prime 3)If none of them divide n, then n is prime How can we check if a number x evenly divides n? COMP Programm 81

82 Steps to solve this: How can we check if a number x evenly divides n? 1)Use int division. If x / n * n is equal to x, then x must be a multiple of n. Otherwise, we'd have lost information on the division. ex: 6 / 3 * 3 = 6 (6 is a multiple of 3) 5 / 3 * 3 = 3 (since 5 / 3 = 1 in integer division) 2)Use modulo % operator. x % n == 0 if x is a multiple of n. (ex: 48 hours after midnight is 0:00, since 48 is a multiple of 24) COMP Programm 82

83 Solution public static boolean isprime(int n) { int x = 2; while (x < n) { if (n % x == 0) { return false; x++; return true; COMP Programm 83

84 Even better solution public static boolean isprime(int n) { if (n < 2) { return false; int x = 2; while (x < n) { if (n % x == 0) { return false; x++; return true; COMP Programm 84

85 Careful not to make this mistake! public static boolean isprime(int n) { if (n < 2) { return false; int x = 2; while (x < n) { if (n % x == 0) { return false; else { return true; x++; COMP Programm 85

86 Careful not to make this mistake! public static boolean isprime(int n) { if (n < 2) { return false; int x = 2; while (x < n) { if (n % x == 0) { return false; else { return true; /* This code returns true if the first number for x (2) isn't a factor of n. For example, 9 is not prime, but 9 % 2!= 0*/ x++; COMP Programm 86

87 Asymmetry This asymmetry occurs because a number is prime if none of the numbers preceding it are factors. A number is composite (that is, not prime) if any of the numbers preceding it are factors. none is not the opposite of any so we have an asymmetry in the problem. COMP Programm 87

88 Idiom number 3 : All/None vs any The following idiom returns true if any numbers between 1 and max satisfy a condition. False otherwise. (Could modify accordingly to make none instead of all or flip true/false) int i = 1; while (i <= max) { if (some condition) { i++; return false; return true; COMP Programm 88

89 Top Down Programming The way we solved this problem is using a technique called topdown programming. We started out with a big goal (determine if a number is prime) Then we looked at the various steps we needed to solve that. (loop through all numbers, check conditions, return statement) We then examined how to solve those various steps (counter + while loop, % operator) COMP Programm 89

90 Exercise Now that you have a method isprime, write another method printprimes. Your method should take as input an int n and return void. Your method should then print the first n prime numbers. When you write this method, for practice with taking an exam, try to write it on a piece of paper (or without seeing what the computer does). When you do this, call the method isprime(). But try not to think about how the method isprime() works. Focus only on what it does. COMP Programm 90

91 Exercise Write a method that takes as input a String s and returns a boolean representing whether ALL characters are uppercase or not. Note: whenever you have a String, you can access individual characters by writing the name of the String followed by.charat(count) where count is the numberth letter you want. One thing to keep in mind with count is it starts from 0 and ends at the Strings length 1. String foo = hello ; foo.charat(0) ---> letter h foo.charat(4) --> letter o foo.charat(5) --> run time exception since no such character foo.length() ---> gives 5 (one more than the largest index) Hint : If you are having trouble, use top down programming and split your problem into smaller pieces. Start by assuming you have a method isuppercase(char c) COMP Programm 91

92 Part 4: The for Statement

93 Common loop theme Very often in loops, one will do 3 things: 1)Perform some initialization before the loop starts. 2)Check a condition before an iteration of the loop starts. 3)Perform some finalization at the end of each iteration. COMP Programm 93

94 Example loop int x = 0; //initialization while (x < 4) //condition { System.out.println(x); x++; //finalization at the end of each step COMP Programm 94

95 for loop As this theme was so commonly used, Java added a for loop. A for loop is mostly the same as a while loop, but it adds as part of the for loop syntax an initialization and finalization step. for (initialization; condition; finalization) { //loop body COMP Programm 95

96 for loop for (initialization; condition; finalization) { //loop body The initialization step happens once per loop. It happens right before the first step of the for loop COMP Programm 96

97 for loop for (initialization; condition; finalization) { //loop body The condition is checked before each iteration of the loop. This is the same as in a while loop. COMP Programm 97

98 for loop for (initialization; condition; finalization) { //loop body The finalization happens at the very end of every iteration of the loop. COMP Programm 98

99 for loop for (int i = 0; i < 4; i++) { System.out.println(i); This does the same as the while loop prior. It prints the numbers 0,1,2,3 COMP Programm 99

100 for loop vs while loop for (int i = 0; i < 4; i++) { System.out.println(i); int i = 0; while (i < 4) { System.out.println(i); i++; COMP Programm 100

101 Benefit of for loop for loops are more readable than while loops in some cases. For example, in the previous case, it is obvious when looking at the statement int i = 0; that the statement is part of the loop. In the case of the while loop it isn't as obvious. COMP Programm 101

102 Accidental error in while loop int x = 0; while (x < 4) { System.out.println(x); x++; Here it is not quite as obvious that int x = 0; is related to the loop. This means you or someone else could carelessly separate the 2 parts and cause a mistake (for example while copying and pasting) COMP Programm 102

103 Benefit of while loop Typically, one chooses a while loop over a for loop if there is an indefinite number of iterations one wants to execute. For example, if you wanted to continue to do something until a certain event occurs. This translates better with a while loop because you don't have a loop counter anyway. COMP Programm 103

104 Benefit of while loop int lastleafcupchampionship = 1967; while (lastleafcupchampionship == 1967) { System.out.println( Wow, even the Rangers are better. ); COMP Programm 104

105 Infinite loop? int lastleafcupchampionship = 1967; while (lastleafcupchampionship == 1967) { System.out.println( Wow, even the Rangers are better. ); COMP Programm 105

106 Treating a for loop like a while loop The statements in a for loop header can be anything including the empty statement: int x = 0; for (; x < 4; ) { System.out.println(x); x++; COMP Programm 106

107 COMP Programm 107

108 Exercise: Rewrite the isprime() method that we wrote to use a for loop instead of a while loop. Rewrite the printprimes() method as well. COMP Programm 108

109 Part 5: Nested Loops

110 Nested Loops Sometimes, we will put a loop inside of a loop. When this happens...sometimes our brain is tied in a bit of a knot (buda-dum-dum-chi) COMP Programm 110

111 Example : Print coordinate table Suppose we want to print all non-negative combinations of x and y in a grid. We can use 1 for loop inside another to do this. COMP Programm 111

112 Example : Print coordinate table First, think about y being fixed. For any given y, if I want to print a range of x's, I can do this using a for loop. int y = 1; for (int x = 0; x < 10; x++) { System.out.print( ( + y +, + x + ), ); System.out.print( \n ); COMP Programm 112

113 Example : Print coordinate table int y = 1; for (int x = 0; x < 10; x++) { System.out.print( ( + y +, + x + ), ); System.out.print( \n ); We know that this code will loop over x from 0 up until and including 9, and print: (1,0), (1,1), (1,2), (1,3), (1,4), (1,5), (1,6), (1,7), (1,8), (1,9) COMP Programm 113

114 Example : Print coordinate table Now, I want to do this for every y from 0 to 10 as well. So we need to replace the y = 1 part with a loop that changes the value of y. COMP Programm 114

115 Example : Print coordinate table for (int y = 0; y < 10; y++) { for (int x = 0; x < 10; x++) { System.out.print( ( + y +, + x + ), ); System.out.print( \n ); COMP Programm 115

116 Using constants for (int y = 0; y < 10; y++) { for (int x = 0; x < 10; x++) { System.out.print( ( + y +, + x + ), ); System.out.print( \n ); It's better to replace the number 10 with a constant describing why we are using the number 10. It may be as simple as NUM_Y_COORDS, but it should be something COMP Programm 116

117 Using constants final int VERTICAL_SIZE = 10; //could also be class constants? final int HORIZONTAL_SIZE = 10; for (int y = 0; y < VERTICAL_SIZE; y++) { for (int x = 0; x < HORIZONTAL_SIZE; x++) { System.out.print( ( + y +, + x + ), ); System.out.print( \n ); COMP Programm 117

118 Using Methods to Avoid Nested Loops Many times, we can use a method to hide a nested loop. public static void main(string[] args) { for (int y = 0; y < VERTICAL_SIZE; y++) { printrow(y); public static void printrow(int y) { for (int x = 0; x < HORIZONTAL_SIZE; x++) { System.out.print( ( + y +, + x + ), ); System.out.println( \n ); COMP Programm 118

119 Avoiding nested loops There still is a nested loop technically in that you are executing a loop inside of a loop. However, the method allows us to hide this aspect. -We look at the printrow() method and can test to make sure it works. -Less chance to get the variables mixed up somehow. (For example to change x when we want to change y) -Miller's law in play (less to keep track of at a time) COMP Programm 119

120 Practice with loops -Write a method that takes as input a positive int n and calculates the sum of n. (Do this using a loop first and then do this using a formula) -Write a method called power that takes as input 2 positive integers base and power and computes base^power. How could you extend this so that the method worked with negatives as well? -Write a method that prints all the powers of two. Do this first using nested loops and then do it using your method power written above. COMP Programm 120

121 Exercise: While loop vs for loop Rewrite the above code using: 1)a while loop on the outside and a for loop on the inside 2)a for loop on the outside and a while loop on the inside 3)2 while loops COMP Programm 121

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

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

More information

Warm-Up: COMP Programming with Iterations 1

Warm-Up: COMP Programming with Iterations 1 Warm-Up: Suppose I have a method with header: public static boolean foo(boolean a,int b) { if (a) return true; return b > 0; Which of the following are valid ways to call the method and what is the result?

More information

Warmup : Name that tune!

Warmup : Name that tune! Warmup : Name that tune! Write, using a loop, Java code to print the lyrics to the song 99 Bottles of Beer on the Wall 99 bottles of beer on the wall. 99 bottles of beer. Take one down, pass it around,

More information

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

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 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.

More information

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

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Methods Assignment 1 Assignment 1 posted on WebCt and course website. It is due May 18th st at 23:30 Worth 6% Part programming,

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables COMP-202 Unit 2: Java Basics CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables Part 1: Printing to the Screen Recall: HelloWorld public class

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables COMP-202 Unit 2: Java Basics CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables Assignment 1 Assignment 1 posted on WebCt and course website.

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

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

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables COMP-202 Unit 2: Java Basics CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables Tutorial 0 Help with setting up your computer to compile and

More information

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

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016 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

More information

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables COMP-202 Unit 2: Java Basics CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables Part 1: Printing to the Screen Recall: HelloWorld public class

More information

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions COMP-202 Unit 9: Exceptions Course Evaluations Please do these. -Fast to do -Used to improve course for future. (Winter 2011 had 6 assignments reduced to 4 based on feedback!) 2 Avoiding errors So far,

More information

Top-Down Program Development

Top-Down Program Development Top-Down Program Development Top-down development is a way of thinking when you try to solve a programming problem It involves starting with the entire problem, and breaking it down into more manageable

More information

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++ Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

More information

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions COMP-202 Unit 9: Exceptions Announcements - Assignment 4: due Monday April 16th - Assignment 4: tutorial - Final exam tutorial next week 2 Exceptions An exception is an object that describes an unusual

More information

Java Coding 3. Over & over again!

Java Coding 3. Over & over again! Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

More information

Repetition, Looping CS101

Repetition, Looping CS101 Repetition, Looping CS101 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

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

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice CONTENTS: Arrays Strings COMP-202 Unit 5: Loops in Practice Computing the mean of several numbers Suppose we want to write a program which asks the user to enter several numbers and then computes the average

More information

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

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 Announcements Slides will be posted before the class. There might be few

More information

Last Class. While loops Infinite loops Loop counters Iterations

Last Class. While loops Infinite loops Loop counters Iterations Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();

More information

COMP 202 Java in one week

COMP 202 Java in one week CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

More information

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

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn CPS109 Course Notes 6 Alexander Ferworn Unrelated Facts Worth Remembering Use metaphors to understand issues and explain them to others. Look up what metaphor means. Table of Contents Contents 1 ITERATION...

More information

Scope of this lecture. Repetition For loops While loops

Scope of this lecture. Repetition For loops While loops REPETITION CITS1001 2 Scope of this lecture Repetition For loops While loops Repetition Computers are good at repetition We have already seen the for each loop The for loop is a more general loop form

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 06 / 04 / 2015 Instructor: Michael Eckmann Today s Topics Questions / comments? Calling methods (noting parameter(s) and their types, as well as the return type)

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

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

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics COMP-202 Unit 1: Introduction Announcements Did you miss the first lecture? Come talk to me after class. If you want

More information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

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

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2 CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

More information

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out. Nested Loops To investigate nested loops, we'll look at printing out some different star patterns. Let s consider that we want to print out a square as follows: We know we can print out one line of this

More information

COMP 202. Java in one week

COMP 202. Java in one week COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language

More information

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

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java

More information

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

Example: Computing prime numbers

Example: Computing prime numbers Example: Computing prime numbers -Write a program that lists all of the prime numbers from 1 to 10,000. Remember a prime number is a # that is divisible only by 1 and itself Suggestion: It probably will

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops. CSE 114, Computer Science 1 Stony Brook University Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

More information

! 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

! 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 Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is

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

Repetition with for loops

Repetition with for loops Repetition with for loops So far, when we wanted to perform a task multiple times, we have written redundant code: System.out.println( Building Java Programs ); // print 5 blank lines System.out.println(

More information

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in

More information

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

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

Building Java Programs Chapter 2

Building Java Programs Chapter 2 Building Java Programs Chapter 2 Primitive Data and Definite Loops Copyright (c) Pearson 2013. All rights reserved. Data types type: A category or set of data values. Constrains the operations that can

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

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

1. An operation in which an overall value is computed incrementally, often using a loop.

1. An operation in which an overall value is computed incrementally, often using a loop. Practice Exam 2 Part I: Vocabulary (10 points) Write the terms defined by the statements below. 1. An operation in which an overall value is computed incrementally, often using a loop. 2. The < (less than)

More information

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

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw. Building Java Programs Chapter 2 bug Primitive Data and Definite Loops Copyright (c) Pearson 2013. All rights reserved. 2 An Insect Software Flaw 3 4 Bug, Kentucky Bug Eyed 5 Cheesy Movie 6 Punch Buggy

More information

Building Java Programs Chapter 2

Building Java Programs Chapter 2 Building Java Programs Chapter 2 Primitive Data and Definite Loops Copyright (c) Pearson 2013. All rights reserved. bug 2 An Insect 3 Software Flaw 4 Bug, Kentucky 5 Bug Eyed 6 Cheesy Movie 7 Punch Buggy

More information

Iteration statements - Loops

Iteration statements - Loops Iteration statements - Loops : ) הוראות חזרה / לולאות ( statements Java has three kinds of iteration WHILE FOR DO... WHILE loop loop loop Iteration (repetition) statements causes Java to execute one or

More information

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Chapter 4 Lab. Loops and Files. Objectives. Introduction

Chapter 4 Lab. Loops and Files. Objectives. Introduction Chapter 4 Lab Loops and Files Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write a do-while loop Be able to write a for loop Be

More information

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

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters Programming Constructs Overview Method calls More selection statements More assignment operators Conditional operator Unary increment and decrement operators Iteration statements Defining methods 27 October

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to A PROGRAM IS A SEQUENCE of instructions that a computer can execute to perform some task. A simple enough idea, but for the computer to make any use of the instructions, they must be written in a form

More information

St. Edmund Preparatory High School Brooklyn, NY

St. Edmund Preparatory High School Brooklyn, NY AP Computer Science Mr. A. Pinnavaia Summer Assignment St. Edmund Preparatory High School Name: I know it has been about 7 months since you last thought about programming. It s ok. I wouldn t want to think

More information

Post Experiment Interview Questions

Post Experiment Interview Questions Post Experiment Interview Questions Questions about the Maximum Problem 1. What is this problem statement asking? 2. What is meant by positive integers? 3. What does it mean by the user entering valid

More information

Chapter 3. Selections

Chapter 3. Selections Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

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

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15 Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

More information

AP Programming - Chapter 6 Lecture

AP Programming - Chapter 6 Lecture page 1 of 21 The while Statement, Types of Loops, Looping Subtasks, Nested Loops I. The while Statement Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly.

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

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

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

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Assignment 1 Assignment 1 posted on WebCt. It will be due January 21 st at 13:00 Worth 4% Last Class Input and Output

More information

Lab # 2. For today s lab:

Lab # 2. For today s lab: 1 ITI 1120 Lab # 2 Contributors: G. Arbez, M. Eid, D. Inkpen, A. Williams, D. Amyot 1 For today s lab: Go the course webpage Follow the links to the lab notes for Lab 2. Save all the java programs you

More information

Over and Over Again GEEN163

Over and Over Again GEEN163 Over and Over Again GEEN163 There is no harm in repeating a good thing. Plato Homework A programming assignment has been posted on Blackboard You have to convert three flowcharts into programs Upload the

More information

3 The L oop Control Structure

3 The L oop Control Structure 3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

More information

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

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. Dec. 9 Loops Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. What is a loop? What are the three loops in Java? What do control structures do?

More information

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

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail. OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce

More information

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1 CSC 1051 Algorithms and Data Structures I Midterm Examination February 24, 2014 Name: KEY 1 Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

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

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac

More information

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

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting Unit 2, Part 2 Definite Loops Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting Let's say that we're using a variable i to count the number of times that

More information

Math Modeling in Java: An S-I Compartment Model

Math Modeling in Java: An S-I Compartment Model 1 Math Modeling in Java: An S-I Compartment Model Basic Concepts What is a compartment model? A compartment model is one in which a population is modeled by treating its members as if they are separated

More information

Lecture Transcript While and Do While Statements in C++

Lecture Transcript While and Do While Statements in C++ Lecture Transcript While and Do While Statements in C++ Hello and welcome back. In this lecture we are going to look at the while and do...while iteration statements in C++. Here is a quick recap of some

More information

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style CS125 : Introduction to Computer Science Lecture Notes #4 Type Checking, Input/Output, and Programming Style c 2005, 2004, 2002, 2001, 2000 Jason Zych 1 Lecture 4 : Type Checking, Input/Output, and Programming

More information

Topic 6 Nested for Loops

Topic 6 Nested for Loops Topic 6 Nested for Loops "Complexity has and will maintain a strong fascination for many people. It is true that we live in a complex world and strive to solve inherently complex problems, which often

More information

Intro. Speed V Growth

Intro. Speed V Growth Intro Good code is two things. It's elegant, and it's fast. In other words, we got a need for speed. We want to find out what's fast, what's slow, and what we can optimize. First, we'll take a tour of

More information

Control Statements: Part 1

Control Statements: Part 1 4 Let s all move one place on. Lewis Carroll Control Statements: Part 1 The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert Frost All

More information

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

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection

More information

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING INPUT AND OUTPUT Input devices Keyboard Mouse Hard drive Network Digital camera Microphone Output devices.

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

CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

More information

CS112 Lecture: Repetition Statements

CS112 Lecture: Repetition Statements CS112 Lecture: Repetition Statements Objectives: Last revised 2/18/05 1. To explain the general form of the java while loop 2. To introduce and motivate the java do.. while loop 3. To explain the general

More information

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

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics COMP-202 Unit 1: Introduction Assignment 1 Assignment 1 posted on WebCt and course website. It is due September 22nd

More information

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

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 Announcements Midterm Exams on 4 th of June (12:35 14:35) Room allocation will be announced soon

More information

COMP-202 More Complex OOP

COMP-202 More Complex OOP COMP-202 More Complex OOP Defining your own types: Remember that we can define our own types/classes. These classes are objects and have attributes and behaviors You create an object or an instance of

More information

Chapter Goals. Contents LOOPS

Chapter Goals. Contents LOOPS CHAPTER 4 LOOPS Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30, 2011 Chapter Goals To implement while, for, and do loops To hand-trace the execution of a program To become familiar with common

More information

3.4. FOR-LOOPS 65. for <v a r i a b l e > in < sequence >:

3.4. FOR-LOOPS 65. for <v a r i a b l e > in < sequence >: 3.4. FOR-LOOPS 65 3.4 For-loops In the previous section we looked at while-loops, Python s basic looping structure. There is a second loop construct in Python called a for-loop. This is more specialized.

More information

Garbage Collection (1)

Garbage Collection (1) Coming up: Today: Finish unit 6 (garbage collection) start ArrayList and other library objects Wednesday: Complete ArrayList, basics of error handling Friday complete error handling Next week: Recursion

More information

Algorithms and Conditionals

Algorithms and Conditionals Algorithms and Conditionals CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Primitive Data, Variables, and Expressions; Simple Conditional Execution Unit 2, Part 1 Primitive Data, Variables, and Expressions; Simple Conditional Execution Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Overview of the Programming Process Analysis/Specification

More information

CS 177 Week 5 Recitation Slides. Loops

CS 177 Week 5 Recitation Slides. Loops CS 177 Week 5 Recitation Slides Loops 1 Announcements Project 1 due tonight at 9PM because of evac. Project 2 is posted and is due on Oct. 8th 9pm Exam 1 Wednesday Sept 30 6:30 7:20 PM Please see class

More information

1.3 Conditionals and Loops

1.3 Conditionals and Loops 1 1.3 Conditionals and Loops any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops to infinity and beyond Math primitive data types

More information

Conditionals, Loops, and Style

Conditionals, Loops, and Style Conditionals, Loops, and Style yes x > y? no max = x; max = y; http://xkcd.com/292/ Fundamentals of Computer Science Keith Vertanen Copyright 2013 Control flow thus far public class ArgsExample public

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

Chapter Fourteen Bonus Lessons: Algorithms and Efficiency

Chapter Fourteen Bonus Lessons: Algorithms and Efficiency : Algorithms and Efficiency The following lessons take a deeper look at Chapter 14 topics regarding algorithms, efficiency, and Big O measurements. They can be completed by AP students after Chapter 14.

More information