The for loop reading 2 3 1 So














































- Slides: 46
The for loop reading: 2. 3 1
So far, when we wanted to perform a task multiple times, we have written redundant code: System. out. println("I am so smart"); System. out. println("S-M-R-T"); System. out. println("I mean S-M-A-R-T"); Output: I am so smart I am so smart S-M-R-T I mean S-M-A-R-T 2
for loops Java has a statement called a for loop statement that instructs the computer to perform a task many times. // repeat 5 times initialize test Update (or, often, increment) for (int i = 1; i <= 5; i++) { System. out. println("I am so smart"); } System. out. println("S-M-R-T"); System. out. println("I mean S-M-A-R-T"); What happens? i = 1; 1 <= 5? , 2 <= 5? , 3 <= 5? , 4 <= 5? , 5 <= 5? , 6 <= 5? , true; System. out. println(“…; false; exit the loop i = 2 i = 3 i = 4 i = 5 i = 6 System. out. println("S-M-R-T"); System. out. println("I mean S-M-A-R-T"); 3
for loop syntax for (initialization; test; update) { statement; . . . statement; } – Perform initialization once. – Repeat the following: • Check if the test is true. If not, stop. • Execute the statements. • Perform the update. header body
for loop flow diagram Behavior of the for loop: Start out by performing the <initialization> once. Repeatedly execute the <statement(s)> followed by the <update> as long as the <test> is still a true statement. 5
for loop flow diagram for (int i = 1; i <= 5; i++){ System. out. println("I…"); } I is called the loop counter or index i is calledloopthe loop counter or the loop index.
Loop walkthrough Let's walk through the following for loop: for (int i = 1; i <= 3; i++) { System. out. println(i + " squared is " + (i*i)); } Output 1 squared is 1 2 squared is 4 3 squared is 9 7
The body of a for loop can contain multiple lines. Example: System. out. println("+----+"); for (int i = 1; i <= 3; i++) { System. out. println("\ /"); System. out. println("/ \"); } System. out. println("+----+"); Output: +----+ / / +----+ 8
The update can also be a -- or other operator, to make the loop count down instead of up. This also requires changing the test to say >= instead of <=. System. out. print("T-minus "); for (int i = 10; i >= 1; i--) { System. out. print(i + ", "); } System. out. println("blastoff!"); Output: T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff! 9
When a for loop only has one statement in its body, the { } braces may be omitted. for (int i = 1; i <= 6; i++) System. out. println(i+" squared is " + (i * i)); However, this can lead to mistakes where a line appears to be inside a loop, but is not: for (int i = 1; i <= 3; i++) System. out. println("This is printed 3 times"); System. out. println("So is this. . . or is it? "); Output: This is printed 3 times So is this. . . or is it? Indentation is just “white space” and is just ignored by the compiler. The 2 statements must be within the {}. 10
White space Blanks, tabs and new lines are referred to as white space because they leave white space on the screen. Any amount of white space can be used between tokens (reserved words, variable names, literals, etc. ) but cannot be within most literals. Java statements are ended by a ; (semicolon), not by the end of a line. Example 1 for ( int count = This is fine, the white space is between tokens, but it is not a good format. 1 ; count <= 500 ; count ++) … Example 2 f or (int count = 1; count < = 5 00; co unt + +) … Compiler messages about these errors, actually quite good. 1. Syntax error on tokens, they can be merge to form for 2. Syntax error on tokens, they can be merge to form <= 3. Syntax error on token "00", delete this token 4. co cannot be resolved 5. unt cannot be resolved 6. Syntax error on tokens, they can be merge to form ++ What are the syntax errors here? 11
White space within a String literal A string can have any white space escape character controls in it, but it must fit on one line. Example, legal String my. String = "This string t has spaces and tabs in it. " ; Example, illegal String bad. String = “This string t has spaces and tabs in it and it is split over 2 lines. ”; Can this be fixed? Yes, use String concatenation to form a long String good. String = “This string t has spaces and tabs in it” + “ and it is (no longer) split over 2 lines. ”; Of course, a String can contain any number of special characters that create white space on the printer. String white. Space = “tt This nn generates nntt much white space”; System. out. println(white. Space); This generates much white space 13
Modify-and-assign shortcuts to modify a variable's value Shorthand Equivalent longer version variable += value; variable = variable + value; variable -= value; variable = variable - value; variable *= value; variable = variable * value; variable /= value; variable = variable / value; variable %= value; variable = variable % value; x += 3; // x = x + 3; gpa -= 0. 5; // gpa = gpa - 0. 5; number *= 2; // number = number * 2; Text: page 83
Write a loop that produces the following output. On On On day day day . . . #1 #2 #3 #4 #5 of of of Christmas, Christmas, my my my true true love love sent sent to to to me me me On day #12 of Christmas, my true love sent to me for ( int i = 1; i <= 12; i++ ) System. out. println(“On day #” + i + “of Christmas, my true love sent to me”); Write a loop that produces the following output. 2 4 6 8 Who do we appreciate? for ( int i = 1; i <= 4; i++ ) System. out. print(2 * i + “ “); 15 System. out. print “n Who do we appreciate? ”);
• A loop that never terminates is called an infinite loop. This is always true. for (int i = 10; 1 >= 1; i++) { System. out. println("Runaway Java program!!!"); } People rarely write loops as explicitly incorrect as this but sometimes make errors that have this affect. • Loop that runs a very long time for (int i = 0; i >= 0; i++) { System. out. println(i + “Problem Java program!!!"); } i = -2147483648 when the loop exits. Due to integer overflow. See Lab 2, part 6. Sum integers from 1 to 1, 000. 16
//Body Mass Index = weight/(height*height) * 703 public class BMICalculator { public static void main(String[] args) { // declare variables double height; double weight; double bmi; // CONVERSION is the factor needed to convert from // pounds and inches to meters and kilograms // to allow international BMI comparisons. final int CONVERSION = 703; // compute BMI height = 70; weight = 195; bmi = weight / (height * height) * CONVERSION; } } // print results System. out. print("Current BMI: "); System. out. println(bmi); Output: Current BMI: 27. 976530612244897 According to http: //www. nhlbi. nih. gov/guidelines/obesity/bmi_tbl. pdf this person is on the high side of overweight.
Why the constant 703? U. S. and Great Britain BMI = (weight in pounds * 703 /height in inches² ( kg/m² ) Others BMI = weight in kilograms /height in meters² ( kg/m² ) 1 meter = 39. 37 inches 1 kilogram = 2. 2046 pounds BMI = (weight/2. 2046)/(height/39. 37)2 = (weight/2. 2046) * (39. 37) 2 / height 2 = weight * (39. 37) 2 /2. 2046 / height 2 height = 70; // inches ~= weight *1550/2. 2046/height 2 weight = 195; // pounds ~= 703 weight / height 2 BMI = 195 * 703/ 702 = 27. 976530612244897 39. 372/2. 2046 = 703 height = 70. 0/39. 37; // height in meters = 1. 778 meters weight = 195/2. 2046; // weight in kg = 88. 4514 kg BMI = 88. 4514/(1. 778)2 BMI = 27. 976530612244897 for a person 70 inch, 195 pounds BMI = 27. 97947478093115 for a person 1. 7780035560071121 meters 88. 45141975868638 kg
System. out. print • Prints without moving to a new line – allows you to print partial messages on the same line int highest. Temp = 2, lowest. Temp = -3; // degrees Celsius System. out. println("The Fahrenheit temperatures for -3…”); for (int i = lowest. Temp; i <= highest. Temp; i++) { System. out. print((i * 1. 8 + 32) + " "); } • Output: The Fahrenheit temperatures for -3, -2, -1, 0, 1, 2 degrees Celsius are: 26. 6 28. 4 30. 2 32. 0 33. 8 35. 6 • Concatenate " " to separate the numbers
Counting down • The update can use -- to make the loop count down. – The test must say > instead of < System. out. print("T-minus "); for (int i = 10; i >= 1; i--) { System. out. print(i + ", "); } System. out. println("blastoff!"); System. out. println("The end. "); – Output: T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff! The end.
• nested for loop: Loops placed inside one another. The inner loop's counter variable must have a different name. for (int i = 1; i <= 3; i++) { System. out. println("i = " + i); for (int j = 1; j <= 2; j++) { System. out. println(" j = " + j); } } Let’s go through it a step at a time. Pay attention to the blank spaces. Output: i = 1 j = i = 2 j = i = 3 j = 1 2 1 2 21
In this example, all of the statements in the outer loop's body are executed 5 times. The inner loop prints 10 numbers Thus, there is a total of 50 numbers printed. for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 10; j++) { System. out. print((i * j) + " "); } System. out. println(); // to end each line } Output: 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 22
What is the output of the following nested for loops? for (int i = 1; i <= 6; i++) { for (int j = 1; j <= 10; j++) { System. out. print("*"); } System. out. println(); } Output: ********** ********** 23
What is the output of the following nested for loops? for (int i = 1; i <= 6; i++) { for (int j = 1; j <= i; j++) { System. out. print("*"); } System. out. println(); } Output: * ** ****** 24
What is the output of the following nested for loops? for (int i = 1; i <= 6; i++) { for (int j = 1; j <= i; j++) { System. out. print(i); } System. out. println(); } Output: 1 22 333 4444 55555 666666 25
Common errors • Both of the following sets of code produce infinite loops: for (int i = 1; i <= 5; i++) { for (int j = 1; i <= 10; j++) { System. out. print("*"); } System. out. println(); } Why? i is always 1 in the inner loop, the test does not test j. What is printed? *************** … for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 10; i++) { System. out. print("*"); } System. out. println(); } Why? j is never incremented in the inner loop.
Nested for loop exercise • What nested for loops produce the following output? Inner loops how many times? . . 1. . . 2. . 3. 4 5 outer loop (loops 5 times because there are 5 lines) • This is an example of a nested loop problem where we build multiple complex lines of output: – outer "vertical" loop for each of the lines – inner "horizontal" loop(s) for the patterns within each line 27
Nested for loop exercise • First we write the outer loop, which always goes from 1 to the number of lines desired: for (int line = 1; line <= 5; line++) {. . . } • We notice that each line has the following pattern: – some number of dots (0 dots on the last line) – a number. . 1. . . 2. . 3. 4 5 28
Next we make a table to represent any necessary patterns on that line # of dots line: Dots formula value displayed . . 1 1 4 5 - line 1 . . . 2 2 3 5 - line 2 . . 3 3 2 5 - line 3 . 4 4 1 5 - line 4 5 0 5 - line 5 5 Answer: for (int line = 1; line <= 5; line++) { for (int j = 1; j <= (5 - line); j++) { } } System. out. print(". "); System. out. println(line); 29
A for loop can have more than one loop nested in it. What is the output of the following nested for loops? for (int i = 1; i <= 5; i++) { for (int j = 1; j <= (5 - i); j++) { System. out. print(" "); } for (int k = 1; k <= i; k++) { System. out. print(i); } System. out. println(); } Answer: 1 22 Note: This comment would be placed just before the i loop // Print the following sets of numbers 1, 22, 333, 4444, // 55555, right justified, one set on each line. 333 4444 55555 30
Scope reading: 2. 4 31
scope: The part of a program where a variable exists. A variable exists wherever it has memory space assigned to it. A variable's scope is from its declaration to the end of the { } braces in which it was declared. If a variable is declared in a for loop, it exists only within that loop. If a variable is declared in a method, it exists only in that method. public static void example() { int x = 3; for (int i = 1; i <= 10; i++){ System. out. println(x); } // i no longer exists here } // x ceases to exist here i's scope Even though i is defined in the for loop, the compiler treats it as being defined within the {} following the for loop. x's scope 32
It is illegal to try to use a variable outside of its scope. public static void main(String[] args) { int z = 12; // z is declared here. example(); System. out. println(x); // illegal, undeclared // x is defined in the example method, not here. for (int i = 1; i <= 10; i++) { int y = 5; System. out. println(y); } System. out. println(y); // illegal, defined in brackets } public static void example() { int x = 3; // x is declared here. System. out. println(x); System. out. println(z); // illegal z is defined in main } Helps with modularization. 33
It is legal to declare variables with the same name, as long as their scopes do not overlap: public static void main(String[] args) { int x = 2; for (int i = 1; i <= 5; i++) { int y = 5; System. out. println(y); } for (int i = 3; i <= 5; i++) { int y = 2; // legal, not in scope of the other y int x = 4; // illegal, within scope of the other x System. out. println(y); } } public static void another. Method() { int i = 6; // legal int y = 3; // legal System. out. println(i + ", " + y); } 34
Literal numbers in code are often called “magic numbers”. Note the repetition of numbers based on 5 in the code: public static void draw. Figure 1() { draw. Plus. Line(); draw. Bar. Line(); draw. Plus. Line(); } public static void draw. Plus. Line() { System. out. print("+"); for (int i = 1; i <= 5; i++) { System. out. print("/\"); } System. out. println("+"); } public static void draw. Bar. Line() { System. out. print("|"); for (int i = 1; i <= 10; i++) { System. out. print(" "); } System. out. println("|"); } Output: +///+ | | +///+ The number of spaces between the bars (|) is twice the number of /s. // 10 = 2 * 5 If you want to change the width of the box from 5 to 7 you might notice that the 10 is based on the 5, so 10 should become 14. 35
A class constant will fix the "magic number" problem. It’s scope is the entire class, main() and any other methods. public static final int FIGURE_WIDTH = 5; public static void draw. Figure 1() { draw. Plus. Line(); This allows us to change draw. Bar. Line(); only one value to change it draw. Plus. Line(); throughout the program. } public static void draw. Plus. Line() { System. out. print("+"); for (int i = 1; i <= FIGURE_WIDTH; i++) { System. out. print("/\"); } System. out. println("+"); } public static void draw. Bar. Line() { System. out. print("|"); for (int i = 1; i <= 2 * FIGURE_WIDTH; i++) { System. out. print(" "); } System. out. println("|"); 36 }
“Magic Numbers” within a method. Method constant A constant that can be used only in one method. It is illegal for these constants to be public, static. public static void my. Method() { final int DAYS_IN_WEEK = 7; final double INTEREST_RATE = 3. 5; final int SSN = 658234569; . . . } The scope of these constants is just this method. They cannot be accessed from any other method.
Drawing complex figures and Pseudocode (using the for loop) reading: 2. 5 38
Drawing complex figures • Write a program that produces the following output. 39 – Use nested for loops to capture the repetition. #========# | <><> | | <>. . . <> | |<>. . . <>| | <>. . . . <> | | <><> | #========#
Drawing complex figures • When the task is as complicated as this one, it may help to write down steps on paper before we write our code: – 1. A pseudo-code description of the algorithm (written in English) – 2. A table of each line's contents, to help see the pattern in #========# the input | <><> | | <>. . . <> | |<>. . . <>| | <>. . . . <> | | <><> | #========# 40
Pseudo-code • pseudo-code: A written English description of an algorithm to solve a programming problem. • Major reason for writing pseudo-code: make you think before sitting down at the computer. – Small errors in your code can take up much time in debugging. – Reduce or eliminate errors through thought and planning. • Example: Suppose we are trying to draw a box of stars on the screen which is 12 characters wide and 7 tall. – A possible pseudo-code for this algorithm: print 12 stars. 41 for (each of 5 lines) { print a star. print 10 spaces. print a star. } print 12 stars. ****** * * ******
A pseudo-code algorithm • A possible pseudo-code for our complex figure task: 1. Draw top line with # , 16 =, then # 2. Draw the top half with the following on each line: | spaces (decreasing in number as we go downward) <> dots (decreasing in number as we go downward) <> #========# spaces (same as number of spaces above) | <><> | | | <>. . <> | 3. Draw the bottom half, which is the same | <>. . . . <> | as the top half but upside-down |<>. . . <>| 4. Draw bottom line with # , 16 =, then # |<>. . . <>| | <>. . . . <> | – Our pseudo-code suggests that we | <>. . <> | should construct a table to specify the | <><> | pattern in the top and bottom #========# 42 halves of the figure.
Tables to examine output • A table of the contents of the lines in the "top half" of the figure: – What expressions connect each line with its number of spaces and dots? line spaces line *(-2) + 8 dots 4 * line - 4 1 6 6 0 0 2 4 4 3 2 2 8 8 4 0 0 12 12 43 #========# | <><> | | <>. . . <> | |<>. . . <>| | <>. . . . <> | | <><> | #========#
Implementing the figure • Let's implement the code for this figure together. • Some questions we should ask ourselves: – How many loops do we need on each line of the top half of the output? #========# <><> | – Which loops are nested inside which | | <>. . <> | other loops? | <>. . . . <> | – How should we use static methods to |<>. . . <>| represent the structure and redundancy| <>. . . . <> | | <>. . <> | of the output? 44 | <><> | #========#
Partial solution /* Prints the expanding pattern of <> for the top half of the figure. */ public static void draw. Top. Half() { for (int line = 1; line <= 4; line++) { System. out. print("|"); for (int space = 1; space <= (line * -2 + 8); space++) { System. out. print(" "); } System. out. print("<>"); for (int dot = 1; dot <= (line * 4 - 4); dot++) { System. out. print(". "); } System. out. print("<>"); for (int space = 1; space <= (line * -2 + 8); space++) { System. out. print(" "); } 45 } System. out. println("|");
Partial solution w/class constant public static final int SIZE = 4; // Prints the expanding pattern of <> for the top half of the figure. public static void draw. Top. Half() { for (int line = 1; line <= SIZE; line++) { System. out. print("|"); for (int space = 1; space <= (line * -2 + (2 * SIZE)); space++) { System. out. print(" "); } System. out. print("<>"); for (int dot = 1; dot <= (line * 4 - 4); dot++) { System. out. print(". "); } System. out. print("<>"); for (int space = 1; space <= (line * -2 + (2 * SIZE)); space++) { System. out. print(" "); } System. out. println("|"); } } 46