Introduction to Java Programming and Data Structures - Chapter 5: Loops
Introduction to Java Programming and Data Structures
Chapter 5: Loops
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations
Problem Context
Consider the scenario where you need to print the string "Welcome to Java!" a hundred times.
Writing the statement
System.out.println("Welcome to Java!");a hundred times would be tedious.
The essential question raised: How do you solve this problem using programming?
Opening Problem
Problem Definition
Repetition of printing the same statement multiple times:
System.out.println("Welcome to Java!");Printed 100 times sequentially:
System.out.println("Welcome to Java!");This repetition illustrates the need for an automated solution through loops.
Loops Overview
Definition of Loops
Repetition statements, commonly known as loops, allow execution of a statement multiple times.
Control Mechanism
Controlled by boolean expressions just like conditional statements.
Types of Loops in Java
Three types of loops in Java:
while loop
do-while loop
for loop
while Loops
Syntax of while Loop
The general syntax:
while (condition) { statements; //change condition }Explanation:
If the condition evaluates to true, the enclosed statement is executed.
This evaluation repeats until the condition becomes false.
Example of while Loop
Code snippet demonstrating a while loop:
```java
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}
### while Loop Flow Chart
- Breakdown of flow in a while loop:
- Initial condition checked: `while (loop-continuation-condition)`
- Executes the loop-body (`Statement(s)`) if the condition is true.
- Example Explanation:
- Initialize `count = 0`.
- Repeated evaluation of `count < 100`.
- Increment `count` after each print statement.
### Tracing the while Loop
- Step-by-step analysis:
- **Initialization**:
1. `int count = 0;`
2. Loop initiates with checking `while (count < 2)` leading to multiple iterations.
- Each iteration detail is traced:
- 1st Iteration:
- Condition is true; prints "Welcome to Java!"
- Increment `count` to 1.
- 2nd Iteration:
- Condition remains true; prints again, makes `count` 2.
- 3rd Iteration:
- Condition is false; exits the loop and continues to next statement.
### Problem Example: Repeat Addition Until Correct
- Challenge presented from Listing 3.1 *AdditionQuiz.java*:
- Modify the program to allow the user to keep entering answers until the correct one is input.
- Usage of loops allows indefinite repetitions until correct input is received.
### Ending a Loop with a Sentinel Value
- Definition of Sentinel Value
- An input value that signifies the end of loop execution.
- Example Task
- Write a program to read and calculate the sum of integers until the sentinel value (0) is entered.
### Caution for Loop Control
- Issue with Floating-point Values
- Avoid using floating-point for equality checking in loops; they are approximations.
- Example Code with potential pitfalls:
java
double item = 1;
double sum = 0;
while (item != 0) {
sum += item;
item -= 0.1;
}
System.out.println(sum);
### do-while Loops
- Syntax of do-while Loop
- The syntax is:
- `do { statements; } while (condition);`
- Execution details:
- The statements inside the do block are executed at least once before evaluating the condition.
### Example of do-while Loop
- Code example:
java
int count = 0;
do {
count++;
System.out.println(count);
} while (count < 5);
### for Loops
- Syntax of for Loop
- The syntax is:
- `for (initialization; condition; increment) statement;`
- Execution flow:
- Initialization occurs once before the loop starts.
- Statements inside the loop execute until the condition is false.
- The increment section runs after each iteration.
### Example of for Loop
- Example code using a for loop:
java
for (int i = 0; i < 100; i++) {
System.out.println("Welcome to Java!");
}
### Tracing the for Loop
- Detailed breakdown:
- Initialization:
- `int i;`
- `for (i = 0; i < 2; i++)` allows execution until `i` becomes 2.
- Execution steps:
- Initializing `i`; check condition; print output; iteratively update `i`.
- Conclusion of the loop is when `i` reaches 2, resulting in termination.
### Key Notes on for Loops
- Initializations and increments can be multiple comma-separated expressions.
- Example:
- `for (int i = 1; i < 100; System.out.println(i++));`
- Omitting the loop-continuation-condition defaults to true, which can create an infinite loop.
- Correct usage advice against confusion.
### Cautions with Loop Syntax
- Common Pitfalls:
- Adding a semicolon at the end of the for statement causing premature loop ending.
- Similar requirement applies for do while loops needing an explicit semicolon.
### Choosing the Right Loop
- Equivalence:
- All three types of loops (while, do-while, for) can achieve the same results.
- Guidelines for Choosing
- Use a **for loop** when the number of iterations is known.
- Use a **while loop** when iterations are indefinite until a certain condition is fulfilled.
- Use a **do-while loop** when the condition needs to be tested after executing the loop body at least once.
### Recommendations for Loop Usage
- Examples and rewriting task with a do-while loop as per slide 19 for practice.
### break Statement in Loops
- Implementation of break in loop control:
java
public class TestBreak {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) { number++; sum += number; if (sum >= 100)
break;
}
System.out.println("The number is " + number);
System.out.println("The sum is " + sum);
}
}
### continue Statement in Loops
- Example illustrating the use of continue:
java
public class TestContinue {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
if (number == 10 || number == 11)
continue;
sum += number;
}
System.out.println("The sum is " + sum);
}
}
```
Using break and continue - Summary
Functional examples provided:
TestBreak.javademonstrates the break usage.TestContinue.javaillustrates continue implementation.
Nested Loops
Problem Statement:
An assignment to create a program using nested for loops to generate a multiplication table.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved