40
for Loops CSC116: Intro to Java Programming 1 • Repetitive Tasks • The for Loop Nested Loops • Constants • Scope Infinite Loops

for Loops · In-class Exercise • Write a Java class named Sequences. Use for loops in the main method to produce each of the following sequences. Use a separate for loop for

  • Upload
    others

  • View
    13

  • Download
    0

Embed Size (px)

Citation preview

for Loops

CSC116: Intro to Java Programming 1

• Repetitive Tasks

• The for Loop

• Nested Loops

• Constants

• Scope

• Infinite Loops

Review

CSC116: Intro to Java Programming 2

• Primitive Types

– int, double, char, boolean

• Arithmetic Operators

– *,/,%, +, -

• Integer Division

– truncate

• String Concatenation

– + with a String operand

• Evaluation of Expressions– Precedence

• (), *,/,% , +,-

• Left to right within level

• Variables

– Declaration (specify type)

– Assignment (=)

• Shorthand operators

– +=, -=, *=, /=

• increment/decrement

– ++x, --x ; x++, x--

• Casting/Promotion

– int promoted to double

– primitive promoted to String

– double casted to int

Repetitive Tasks

CSC116: Intro to Java Programming © Sarah Heckman 3

• Suppose you were given the programming task of printing the phrase:

The quick brown fox jumps over the lazy dog

1000 times.

• At first, the only way we knew how to do this was to write 1000 System.out.printlnstatements.

Repetitive Tasks (cont.)

CSC116: Intro to Java Programming 4

• Next, we learned that we could eliminate someredundancy with static methods:

– Create methods for subtasks and use method calls:

1. Create a print10() method to print out the phrase 10 times

2. Create a print100() method with 10 method calls tothe print10() method

3. Create a print1000() method with 10 method callsto the print100() method

Iteration

CSC116: Intro to Java Programming © Sarah Heckman 5

• Now, we will learn how to eliminate redundancy for iterative tasks.

• Iteration is the process of doing something over and over again.

• In programming, we execute this concept through the use of loops.

Loop Control Structures

CSC116: Intro to Java Programming 6

• for loop

– this lecture

• Later

– while loop

– do-while loop

for Loops

7

• for loops provide a mechanism for doing similar thingsmany times

– Used when you know how many iterations of a statement or group of statements that you want to execute

• Control Variable: int variable used to control the loop (i,j,k, etc.)

• Parts of the for loop

– Initialization (of the loop control variable)

– Continuation test (execute another iteration?)

– Update (the loop control variable value)

– Body (statements to be iterated)CSC116: Intro to Java Programming

for loop syntax

CSC116: Intro to Java Programming 8

for(initialization; test; update) {

statement;

statement;

...

statement;

}

for(int i = 0; i < 1000; i++) {

System.out.println("The quick brown … lazy dog");}

for(int i = 1; i <= 1000; i++) {

System.out.println("The quick brown … lazy dog");

}

for Loop Walkthrough

CSC116: Intro to Java Programming

1. Perform Initialization Once

2. Test true?

3. Execute the controlled statement(s)

4. Perform the update

5. Execute statement after for loop

Yes

9

No

More Loop Tracing Practice

CSC116: Intro to Java Programming © Sarah Heckman 10

System.out.println("+-----+");

for (int i = 1; i <= 3; i++) {

System.out.println("\\ /");System.out.println("/ \\");

}

System.out.println("+-----+");

• What is the control variable?

• How many iterations?

• What is the output?

print and println revisited

CSC116: Intro to Java Programming © Sarah Heckman 11

• println includes an automatic new line at the end of

the output

• print prints the text and leaves the cursor at the end

of the printed text

• A series of print statements will print on one line, until

• println completed

• "\n" concatenated to output String

Write a loop

CSC116: Intro to Java Programming © Sarah Heckman 12

• What if we wanted to print the following?

0123456789

for ( ; ; ) {

}

Decrementing Loop• What is the output of the following loop?

CSC116: Intro to Java Programming © Sarah Heckman 13

System.out.print("T-minus ");

for (int i = 5; i >= 1; i--) {

System.out.print(i + ", ");

}

System.out.println("Blastoff! ");

Output: T-minus 5, 4, 3, 2, 1, Blastoff!

Decrementing Loop

CSC116: Intro to Java Programming © Sarah Heckman 14

• What if we wanted to print the following?

9876543210

for ( ; ; ) {

}

CSC116: Intro to Java Programming © Sarah Heckman 15

• What is the output of the following?for (int i = 1; i <= 5; i++) {

System.out.print((i * 4) + " ");

}

System.out.println();

• What statement in the body would cause the loop to print:- 4 7 10 13 16

More Examples

CSC116: Intro to Java Programming © Sarah Heckman 16

• What is the output of the following?for (int i = 1; i <= 5; i++) {

System.out.print((i * 4) + " ");

}

System.out.println();

- 4 8 12 16 20

• What statement in the body would cause the loop to print:- 4 7 10 13 16

for (int count = 1; count <= 5; count++) {

System.out.print(3 * count + 1 + " ");

}

More Examples - Solution

In-class Exercise• Write a Java class named Sequences. Use for loops in the main method

to produce each of the following sequences. Use a separate for loop for

each sequence and print a blank line between each sequence. Your

control variable does not have to be initialized to 1.

• There are many ways to produce the requested output, but for this

exercise your for loops must meet the following criteria:

• The values printed should be calculated as an expression in terms

of the loop control variable.

• The for loop update clause MUST only increment or decrement the

loop control variable by 1 (e.g. i++ or i--).

1. 0 5 10 15 20 25

2. 8 4 0 -4 -8

3. 49 36 25 16 9 4 1

Nested Loops

CSC116: Intro to Java Programming © Sarah Heckman 18

• nested loop: A loop placed inside another loop.

for (int i = 1; i <= 4; i++) {

for (int j = 1; j <= 5; j++) {

System.out.print((i*j) + "\t");

}

System.out.println(); //ends line

}

• Statements in the outer loop performed 4 times

– Rows of output

• Statements in the inner loop performed 5 times– Columns of output

Pseudocode

CSC116: Intro to Java Programming © Sarah Heckman 19

• English-like description of algorithms

• Example: Draw a box with 6 rows and 10columns of asterisks

• Refine until easily translated into a Java programfor (each of 6 lines) {

for(each of 10 columns) {print one asterisk on the line

}go to the next line

}

Pseudocode to java

20

• Draw a box with 6 rows and 10 columnsof asterisks:

for (int i = 1; i <= 6; i++) {

for (int j = 1; j <= 10; j++)

{

System.out.print("*");

}

System.out.println();

}

Nested Loop Exercise

CSC116: Intro to Java Programming © Sarah Heckman 21

• What is the output of the following nested for loop?

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= i; j++) {

System.out.print("*");

}

System.out.println(); //go to next line

}

• Output:* ** *** **** *****

Nested Loop Exercise

CSC116: Intro to Java Programming © Sarah Heckman 22

• What is the output of the following nested for loop?

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= i; j++) {

System.out.print(i);

}

System.out.println();

}

• Output:

Class Constants

CSC116: Intro to Java Programming © Sarah Heckman 23

• Magic Numbers: numbers that make the program work, buthave no obvious meaning in the program

• Solution: store magic numbers in containers that don’t change– constants

• Class Constant: a named value (identifier) that cannot bechanged and may be accessed from anywhere in the class

• Declared with keyword final

• Naming convention: ALL_IN_CAPS with words separated by anunderscore

Class Constants Declaration andAssignment

CSC116: Intro to Java Programming © Sarah Heckman 24

//creating a constant within a

//method – this is not a class constant!!

//Do not do this in this course

final <type> <name> = <expression>;

//creating a class Constant

public static final <type> <name> = <expression>;

//Example class constants

public

public

public

static

static

static

final

final

final

int MAX_VALUE = 10;

int DAYS_IN_WEEK = 7;

double SPEED_OF_LIGHT = 3.0e8;

//place outside of methods

Always Use Constants Instead of Magic Numbers

• A better way to write our 6x10 box of asterisksexample :

public static final int ROWS = 6;

public static final int COLUMNS = 10;

for (int i = 1; i <= ROWS; i++) {

for (int j = 1; j <= COLUMNS, j++) {

System.out.println("*");

}

System.out.println();

}

Scope

• scope: The part of a program where a variable exists.

• The scope of a variable is from the declaration statement to theright curly brace that encloses it

– for loop control variable only has scope within the for loop

• Local Variable: variable declared in a method that can only beaccessed in the method

• Localizing Variables: declaring variables in the innermost scopepossible– Security

– Minimize interference from other program parts

– Efficiency

CSC116: Intro to Java Programming © Sarah Heckman 28

Scope Example

public class Scope {

public static void main(String [] args) {

printStars();

}

public static void printStars() {

for (int i = 0; i <

for (int j = 0; j

x; i++) {

< y; j++)

//illegal

{ //illegal

System.out.print("*");

}

System.out.println();

}

}

}CSC116: Intro to Java Programming © Sarah Heckman 29

int x = 3;

int y = 7;

Scope implications• Variables without overlapping scope can have same

name.for (int i = 1; i <= 100; i++) {

System.out.print("/");

}

for (int i = 1; i <= 100; i++) {

System.out.print("\\");

// OK

}

int i = 5; // OK: outside of loop's scope

• A variable can't be declared twice or used out of itsscope.for (int i = 1; i <= 100 * line; i++) {

int i = 2; // ERROR: overlapping scope

System.out.print("/");

}

i = 4; // ERROR: outside scope

Using "i" outside the for loop

public static final int MAX = 10;

int i;

for (i = 1; i <= MAX; i++) {

System.out.println(i);

}

System.out.println(i);

Infinite Loops

CSC116: Intro to Java Programming © Sarah Heckman 33

• Infinite loop: A loop that never terminates

– Referring to the wrong loop variable

– No ending condition

• Example:

for (int i = 1; i <= 10; i++) {

for (int j = 1; i <= 5; j++) {

System.out.print(j);

}

System.out.println();

}

More Error Examples

CSC116: Intro to Java Programming34

for (int i = 1; i <= 10; i++) {

for (int j = 1; j <= 5; i++) {

System.out.print(j);

}

System.out.println();

}

int i;

for (i = 1; i <= 10; i++) {

= 1; i <= 5; i++)for (i {

there.");System.out.println("Hi

}

}

More Complex Nested Loops• What nested for loops produce the following

output?

• We must build multiple complex lines of output using: – an outer "vertical" loop for each of the lines – inner "horizontal" loop(s) for the patterns within each line

CSC116: Intro to Java Programming © Sarah Heckman 20

Inner loop(s) (characters on each line)

....1

...2

..3

.4

5

Outer loop (number of lines). Loop 5 times because there are 5 lines.

Breaking Down Nested Loops

CSC116: Intro to Java Programming 33

• First write the outer loop, from 1 to the number of lines.

for (int line = 1; line <= 5; line++) {

...

}

• Now look at the line contents. Each line has a pattern:

• some dots (0 dots on the last line), then a number

• Observation: the number of dots is related to the

line number

....1 line 1

...2 line 2

..3 line 3

.4 line 4

5 Line 5

Breaking Down Nested Loops

CSC116: Intro to Java Programming 34

• Use a table to analyze patterns

Line# Dots Number

1 4 12 3 23 2 34 1 45 0 5

....1 line 1

...2 line 2

..3 line 3

.4 line 4

5 Line 5

Breaking Down Nested Loops

CSC116: Intro to Java Programming 35

• Write the code:

public static final int LINES = 5;

for (int i = 1; i <= LINES; i++) { for (int j = 1; j <= LINES - i; j++) {

System.out.print(".");} System.out.println(i);

}

Another Pattern

CSC116: Intro to Java Programming 36

• Use a table to analyze pattern

Line# Dots Numbers

1 4 12 3 23 2 34 1 45 0 5

....1 line 1

...22 line 2

..333 line 3

.4444 line 4

55555 Line 5

Write the code

CSC116: Intro to Java Programming 37

public static final int LINES = 5;

for (int i = 1; i <= LINES; i++) { for (int j = 1; j <= LINES - i; j++) {

System.out.print(".");} for (int j = 1; j <= i; j++) {

System.out.print(i); } System.out.println();

}

Determining Relationships

CSC116: Intro to Java Programming 38

Pseudocode:

for (each of 4 lines) {

write some \\’s (maybe 0)

write some !!’s

write some //’s (maybe 0)

go to a new line

}

Draw the following shape:

!!!!!!!!!!!!!!

\\!!!!!!!!!!//

\\\\!!!!!!////

\\\\\\!!//////

Line# \\ !! //

0 0 7 01 1 5 12 2 3 23 3 1 3

Write the code

CSC116: Intro to Java Programming 39

for (int i = 0; i < 4; i++) { for (int j = 0; j < i; j++) {

System.out.print("\\\\");}

for (int j = 0; j < 2*(4 - i) - 1; j++) {System.out.print("!!");

} for (int j = 0; j < i; j++) {

System.out.print("//");} System.out.println();

}

In-class Exercise

• Go to the moodle page and work on the SlashFigure.java assignment.