Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4: Loops and Files

Similar presentations


Presentation on theme: "Chapter 4: Loops and Files"— Presentation transcript:

1 Chapter 4: Loops and Files
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis This slide show consists of excerpts from the orginal Chapter 4 slide set.

2 Chapter Topics Chapter 4 discusses the following main topics:
A few preliminary topics Generating Random Numbers with the Random class The Increment and Decrement Operators Loops in java The while Loop The do-while Loop The for Loop

3 Generating Random Numbers with the Random Class
Some applications, such as games and simulations, require the use of randomly generated numbers. A simple example is the “I’m thinking of number between 1 and 10”, (or some other variation), where the program must generate a random number between 1 and 10 for the user to guess. The program reads the user’s guess and then tells them if they are right or not. For such programs, the Java API has a class named Random, that provides a method to use for generating random numbers.

4 Generating Random Numbers with the Random Class
To use the Random class, you would first include the import statement: import java.util.Random; And secondly, instantiate a object of the Random class: Random ran = new Random(); After that is done, anytime your program needs random number, you can call a method depending on what type of number you need.

5 Generating Random Numbers with the Random Class
For example: To obtain an integer, use: int randomInt = ran.nextInt(); To obtain an integer within a specific range, use: int randomInt = ran.nextInt(11); // returns an int from 0 to 10 Method Description nextInt() Returns the next random number as an int. The number will be within the range of an int, which is –2,147,483,648 to +2,147,483,648. nextInt(int n) This method accepts an integer argument, n. It returns a random number as an int. The number will be within the range of 0 to n-1.

6 Some Methods of the Random Class
Description nextInt() Returns the next random number as an int. The number will be within the range of an int, which is –2,147,483,648 to +2,147,483,648. nextInt(int n) This method accepts an integer argument, n. It returns a random number as an int. The number will be within the range of 0 to n. See example: RollDice.java

7 The Increment and Decrement Operators
In many of the programs that use loops, you will see the use of two operators that you may not have encountered yet. They are: Incrementation operator Decrementation operator Let’s take a look at the meaning of these operators before reading the sample codes of chapter 4.

8 The Increment and Decrement Operators
Here Increment means add 1 and decrement means subtract 1. There are numerous times where a variable must simply be incremented or decremented. number = number + 1; number = number – 1; Java provide shortened ways to increment and decrement a variable’s value. Using the ++ or -- unary operators, this task can be completed quickly. number++; or ++number; number--; or --number; There is an Example Program in the Chapter 4 Source Code folder online named: IncrementDecrement.java A version of that follows on the next page.

9 OUTPUT number starts out at 4 After incrementation number is 5
/** This program demonstrates the ++ and -- operators. */ public class IncrementDecrement2 { public static void main(String[] args) int number = 4; // number starts out with 4 System.out.println("number starts out at " + number); number++; // Increment number. System.out.println(" After incrementation number is " + number); number--; // Decrement number. System.out.println(" After decrementation number is " + number); } OUTPUT number starts out at 4 After incrementation number is 5 After decrementation number is 4

10 Loops Frequently in programming, you want certain segments of code to be repeated without having to write the same code multiple times. In programming, a loop is a statement that will cause a segment of code to be repeated (i.e. iterated). For example, think back to Project 1 where you calculated the BMI for 5 persons. Recall that the same code that worked for 1 person had to be written 4 more times. By using a looping statement, we could have written this code segment once and then placed in a looping construct and specify that it be repeated 5 times.

11 Loops Java provides three different looping structures. The while loop
The do-while loop The for loop

12 The while Loop Java provides three different looping structures.
The while loop has the form: while(condition) { statement1; statement2; } While the condition is true, the statements will execute repeatedly. The while loop is a pretest loop, which means that it will test the value of the condition prior to executing the loop.

13 The while loop Flowchart
Statement1; Statement2; true boolean expression? false

14 The while Loop Care must be taken to set the condition to false somewhere in the loop so the loop will end. Loops that do not end are called infinite loops. A while loop executes 0 or more times. If the condition is false, the loop will not execute. Example: WhileLoop.java

15 Infinite Loops In order for a while loop to end, the condition must become false. The following loop will not end: int x = 20; while(x > 0) { System.out.println("x is greater than 0"); } The variable x never gets decremented so it will always be greater than 0. Adding the x-- above fixes the problem.

16 This version of the loop decrements x during each iteration:
Infinite Loops This version of the loop decrements x during each iteration: int x = 20; while(x > 0) { System.out.println("x is greater than 0"); x--; }

17 Block Statements in Loops
Curly braces are required to enclose block statement while loops. (like block if statements) while (condition) { statement; }

18 The do-while Loop The do-while loop is a post-test loop, which means it will execute the loop prior to testing the condition. The do-while loop (sometimes called called a do loop) takes the form: do { statement(s); }while (condition); Example: TestAverage1.java

19 The do-while Loop Flowchart
statement(s) true boolean expression? false

20 The for Loop The for loop is a pre-test loop.
The for loop allows the programmer to initialize a control variable, test a condition, and modify the control variable all in one line of code. The for loop takes the form: for(initialization; test; update) { statement(s); } See example: Squares.java

21 The for Loop Flowchart statement(s) true boolean expression? false
update

22 The Sections of The for Loop
The initialization section of the for loop allows the loop to initialize its own control variable. The test section of the for statement acts in the same manner as the condition section of a while loop. The update section of the for loop is the last thing to execute at the end of each loop. Example: UserSquares.java

23 The for Loop Initialization
The initialization section of a for loop is optional; however, it is usually provided. Typically, for loops initialize a counter variable that will be tested by the test section of the loop and updated by the update section. The initialization section can initialize multiple variables. Variables declared in this section have scope only for the for loop.

24 The Update Expression The update expression is usually used to increment or decrement the counter variable(s) declared in the initialization section of the for loop. The update section of the loop executes last in the loop. The update section may update multiple variables. Each variable updated is executed as if it were on a line by itself.

25 When to use each type of loop… Page 233
The while loop is a pre-test loop ideal for cases where where you do not want the loop to iterate if the condition is false from the beginning. The do-while loop is a post-test loop and is used in situations where you always want the loop to iterate at least once. The for loop is a pretest loop that is used for simple counting loops, ideal when the exact number of iterations is known or can be calculated before the loop begins.


Download ppt "Chapter 4: Loops and Files"

Similar presentations


Ads by Google