Session 6 - Looping Statements
Session 6 - Looping Statements
THROUGH JAVA
UNIT - I
Overview
Iteration statements, also known as loops, are fundamental constructs in Java that allow
the repeated execution of a block of code as long as a specific condition is met. These
statements are crucial for automating repetitive tasks, handling dynamic input sizes, and
reducing code redundancy. They are integral to various programming scenarios, such
as traversing data structures, performing repetitive calculations, and creating time-
based events.
Key Concepts
1. Looping Condition: Every iteration statement relies on a condition to determine
whether the loop should continue executing or terminate. Depending on the type
of loop, this condition is evaluated before or after each iteration.
2. Initialization: Many iteration statements require an initial setup, such as
initializing a counter or setting up an initial condition. This step occurs before the
loop starts running.
3. Iteration: During each loop cycle, a specific set of instructions is executed. After
each iteration, the condition is re-evaluated to decide whether to continue
looping.
and continue, to control the flow of loops. These can be used to exit a loop
prematurely or skip the current iteration.
Iteration statements provide the foundation for writing efficient, maintainable, and
dynamic code in Java. By understanding how these statements work and their
underlying principles, programmers can harness the full power of Java to solve complex
problems and automate repetitive tasks. The detailed study of specific looping
constructs will further explore the different types of loops available in Java, their syntax,
use cases, and best practices.
2. while Expression
while Loop
The while loop is a fundamental iteration statement in Java that allows a block of code
to be executed repeatedly based on a given boolean condition. It is one of the simplest
looping constructs in Java and is particularly useful when the number of iterations is not
known in advance. Understanding how to effectively use the while loop is crucial for
engineering students, as it lays the foundation for more advanced programming
concepts and problem-solving techniques.
while (condition) {
// Statements to be executed
}
- condition: A boolean expression that is evaluated before each iteration of the
loop. If the condition is true, the loop body is executed; if false, the loop
terminates.
- loop body: The block of code inside the curly braces {} that is executed as long
as the condition is true.
2. Execution of the Loop Body: If the condition evaluates to true, the statements
inside the loop body are executed.
3. Re-Evaluation: After the loop body is executed, the condition is re-evaluated.
4. Termination: If the condition evaluates to false, the loop terminates, and the
program execution continues with the statement following the loop.
Flowchart
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
In this example, the loop continues to run as long as the count variable is less than or
equal to 5. On each iteration, it prints the current value of count and then increments it
by 1.
1. Pre-test Loop: The while loop is a pre-test loop, meaning the condition is
tested before the loop body is executed. If the condition is false initially, the
loop body will not execute at all.
2. Indeterminate Loop: The while loop is ideal when the number of iterations is
not known beforehand. It runs until the specified condition becomes false.
3. Potential for Infinite Loops: If the loop condition never becomes false, the
Example Scenarios
1. Reading Input Until a Condition is Met
import java.util.Scanner;
while (!input.equalsIgnoreCase("exit")) {
System.out.print("Enter text (type 'exit' to quit): ");
input = scanner.nextLine();
System.out.println("You entered: " + input);
}
scanner.close();
System.out.println("Program terminated.");
}
}
In this example, the loop continues prompting the user for input until the user types
"exit".
2. Calculating Factorial of a Number
This program calculates the factorial of a given number using a while loop.
- Risk of Infinite Loops: If the condition never becomes false, the loop can
become infinite, leading to program crashes or freezes.
- Less Predictable Execution: Compared to a for loop, a while loop may be
less predictable if the condition relies on variables that change outside the loop
or through complex logic.
1. Ensure Termination: Always ensure that the loop condition will eventually
become false to avoid infinite loops. This typically involves modifying a variable
that affects the condition.
2. Use Clear and Simple Conditions: The loop condition should be simple and
easy to understand to prevent logical errors.
3. Initialize Variables Properly: Ensure all variables used in the loop condition are
initialized correctly before the loop starts.
4. Limit Loop Body Complexity: Keep the code within the loop body as simple as
possible to make the loop’s purpose and operation clear.
The while loop is a powerful and versatile iteration statement in Java. It allows for
dynamic and flexible repetition of code blocks, making it suitable for a wide range of
programming scenarios. By understanding how to properly use and control while
loops, engineering students can write more efficient and robust Java programs, laying a
strong foundation for advanced programming concepts.
Do It Yourself
1. Write a program that prints the following pattern using while loops:
*
**
***
****
*****
2. Create a program to find the sum of even numbers up to a given limit.
3. Develop a simple interest calculator using a while loop.
Quiz
3. Question: What is the potential risk of using a while loop without proper loop
control?
a. Infinite loop
b. Syntax error
c. Runtime error
d. Incorrect output
4. Question: How can you ensure that a while loop eventually terminates?
a. By using a counter variable
b. By checking for a specific condition
c. By using a break statement
d. All of the above
3. do–while Loop
do-while Loop
Introduction
The do-while loop is a variant of the while loop in Java, designed to execute a block
of code at least once before checking its condition. This loop guarantees that the loop
body will run at least once, making it distinct from the while loop, where the condition
is checked before any execution. The do-while loop is particularly useful in scenarios
where a block of code must be executed at least once, regardless of the condition.
do {
// Statements to be executed
} while (condition);
- do: Indicates the start of the loop block.
- condition: A boolean expression evaluated after the loop body has executed.
If the condition is true, the loop continues; if false, the loop terminates.
- Loop body: The block of code inside the curly braces {} that is executed at
least once and then repeatedly as long as the condition is true.
1. Execution of the Loop Body: The statements inside the loop body are executed
first.
2. Evaluation of the Condition: After executing the loop body, the condition is
evaluated.
3. Repetition: If the condition evaluates to true, the loop body is executed again.
program execution continues with the statement following the do-while loop.
Flowchart
do {
System.out.println("Count is: " + count); // Loop body
count++; // Increment
} while (count <= 5); // Condition
}
}
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
In this example, the loop body is executed first, printing the current value of count.
Afterward, count is incremented, and the condition count <= 5 is checked. The loop
continues as long as the condition is true.
1. Post-test Loop: The do-while loop is a post-test loop, meaning the loop body
is executed before the condition is tested. This ensures that the loop body
executes at least once, regardless of whether the condition is initially true or
false.
2. Guaranteed Execution: The loop guarantees at least one execution of the loop
body, making it suitable for cases where the code block must run at least once.
3. Potential for Infinite Loops: Similar to other loops, if the condition never
becomes false, the do-while loop can result in an infinite loop. Proper care is
needed to ensure loop termination.
Common Use Cases
- Menu-Driven Programs: Displaying a menu and prompting the user for input
until they choose to exit.
- Input Validation: Prompting the user for input at least once and continuing until
a valid input is provided.
- Repeated Actions: Performing an action at least once and repeating it as long
as certain conditions are met.
Example Scenarios
1. Menu-Driven Program Example
import java.util.Scanner;
do {
System.out.println("Menu:");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Option 1 selected.");
break;
case 2:
System.out.println("Option 2 selected.");
break;
case 3:
System.out.println("Exiting the program.");
break;
default:
System.out.println("Invalid choice. Please try again.");
break;
}
} while (choice != 3);
scanner.close();
}
}
In this example, the menu is displayed at least once, and the user is prompted for input
until they choose to exit by entering 3.
import java.util.Scanner;
do {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
if (number <= 0) {
System.out.println("Invalid input. Please enter a positive
number.");
}
} while (number <= 0);
This example demonstrates how to prompt the user for a positive number and repeat
the prompt until a valid input is provided.
- Ensures Minimum Execution: The do-while loop ensures that the loop body
is executed at least once, which is useful in scenarios where the action must be
performed before any condition check.
- Suitable for User Interaction: It is particularly useful for menu-driven programs
and user input validation, where the loop should execute at least once to present
options or prompt for input.
- Flexibility: Like the while loop, the do-while loop allows for dynamic and
flexible conditions.
- Potential for Infinite Loops: If the condition is never met, the loop can run
indefinitely, leading to potential program crashes or unresponsiveness.
- Less Commonly Used: Compared to other loops like for and while, the do-
while loop is less commonly used, making it less familiar to some programmers.
Best Practices for Using do-while Loops
1. Ensure Loop Termination: Make sure that the loop condition will eventually
The do-while loop is a powerful construct in Java that provides guaranteed execution
of a code block at least once. It is especially useful for scenarios requiring at least one
iteration, such as user input validation or menu-driven applications. Understanding
when and how to use the do-while loop enables engineering students to write more
effective and flexible Java programs, enhancing their problem-solving skills and
programming versatility.
Do It Yourself
1. Write a program to input a number and check if it is prime using a do-while loop.
2. Write a Java program that calculates the sum of the digits of a positive integer
using a do-while loop.
3. Create a simple number-guessing game where the program randomly selects a
number between 1 and 100, and the user has to guess the number. The program
should give feedback if the guessed number is too high or too low using a do-
while loop.
Quiz
1. Question: What is the key difference between a while loop and a do-while
loop?
○ The condition is checked before the loop in while and after in do-while
○ while is more efficient
○ do-while can only be used for infinite loops
○ There is no difference
Answer: The condition is checked before the loop in while and after in
do-while
2. Question: When would you prefer to use a do-while loop over a while loop?
○ When the loop body must execute at least once
○ When the loop condition is complex
○ When you want to avoid infinite loops
○ There is no specific preference
Answer: Yes
4. Question: What is the minimum number of times a do-while loop body will
execute?
○ 0
○ 1
○ 2
○ Depends on the condition
Answer: 1
4. for Loop
The for loop is one of the most commonly used iteration statements in Java. It is
designed to execute a block of code a specific number of times. By combining
initialization, condition-checking, and iteration in a single line, the for loop provides a
concise way of writing the loop structure. This makes the for loop ideal for scenarios
where the number of iterations is known beforehand.
- Initialization: This part is executed once when the loop starts. It is used to
declare and initialize any loop control variables. This section is optional.
- Condition: The loop condition is evaluated before each iteration. If it evaluates to
true, the loop body is executed; if it evaluates to false, the loop terminates.
This section is mandatory.
- Update: This section is executed after each iteration of the loop body. It is
typically used to update the loop control variable(s). This section is optional.
- Body of the loop: This contains the set of statements that are repeatedly
executed as long as the condition is true.
Flow of Execution
1. Initialization: The loop control variable is initialized. This happens only once at
the beginning of the loop.
2. Condition Checking: The condition is checked. If the condition is true, the
control moves to the body of the loop. If the condition is false, the loop
terminates.
3. Execution of the Loop Body: If the condition is true, the statements inside the
loop body are executed.
4. Update: After executing the loop body, the update statement is executed.
Typically, this modifies the loop control variable.
5. Repeat: Steps 2 through 4 are repeated until the condition becomes false.
Flowchart:
Here's a simple example to demonstrate a for loop that prints the numbers from 1 to 5:
Explanation:
1. Omitting Initialization: The initialization part can be left out if the control variable
is already initialized before the loop. For example:
int i = 1;
for (; i <= 5; i++) {
System.out.println(i);
}
2. Omitting Condition: If the condition part is omitted, it is considered to be true
by default, which may lead to an infinite loop unless there is a break statement
in the loop body:
3. Omitting Update: The update part can also be omitted if the update is performed
inside the loop body:
4. Infinite for Loop: A for loop can be made infinite by omitting all three parts:
for (;;) {
System.out.println("This is an infinite loop");
}
This loop will run indefinitely unless interrupted by a break statement or a
return statement in a method.
1. Iterating Over Arrays: The for loop is commonly used to iterate over arrays to
access each element sequentially.
2. Calculating Factorials: The for loop is often used in mathematical
computations, such as calculating the factorial of a number.
int num = 5;
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
System.out.println("Factorial of " + num + " is: " + factorial);
Advantages of the for Loop
4. Using for vs. while: Choose the for loop when the number of iterations is
known beforehand. If the loop should continue until a certain condition is met but
the number of iterations is unknown, consider using a while or do-while loop
instead.
The for loop is a powerful and versatile construct in Java, well-suited for scenarios
where the number of iterations is known ahead of time. By understanding its syntax,
flow of execution, and various use cases, programmers can leverage the for loop to
write efficient, readable, and maintainable code. Proper use of the for loop helps in
minimizing errors and achieving the desired output in an optimal manner.
Do It Yourself
1. Write a program to calculate the sum of all odd numbers between 1 and n, where
the user provides n. Use a for loop to iterate with an increment of 2 to
skip even numbers.
2. Write a Java program that calculates and prints the sum of numbers from 1 to 10
using a for loop. Use the loop control variable to accumulate the sum.
3. Write a Java program to print multiples of 3 between 3 and 30 (inclusive). Use a
for loop and initialize the loop control variable to 3 and increment by 3.
4. Write a Java program that prints numbers from 10 down to 1 in reverse order
using a for loop. Start the loop control variable at 10 and decrement by 1.
5. Write a Java program to print the square of each number from 1 to 5 using a for
loop. Calculate the square inside the loop body and print it.
Quiz
3. Question: Can you modify the loop counter variable within the loop body of a
for loop?
○ A. Yes
○ No
○ Depends on the programming language
○ Depends on the compiler
Answer: Yes
A nested for loop is a loop within another for loop. In Java, nested loops are used to
perform more complex iterations where multiple dimensions or levels of iteration are
required. Nested loops are particularly useful in scenarios such as working with multi-
dimensional arrays, generating patterns, or solving complex algorithmic problems that
require multiple layers of loops.
Understanding Nested for Loops
A nested for loop consists of an outer loop and one or more inner loops. Each time the
outer loop iterates, the inner loop completes all its iterations. This means the inner loop
runs completely every time the outer loop runs once.
Each loop has its own initialization, condition, and update parts. The outer loop controls
the number of times the inner loop is executed.
Flow of Execution
1. Outer Loop Initialization: The outer loop initializes its control variable.
true, the control moves inside the outer loop; if false, the loop terminates.
3. Inner Loop Initialization: When the outer loop is executed, the inner loop
initializes its control variable.
4. Inner Loop Condition Checking: The inner loop's condition is checked. If true,
the control moves inside the inner loop; if false, the inner loop terminates, and
the control moves back to the outer loop.
5. Execution of Inner Loop Body: If the inner loop condition is true, the
statements inside the inner loop body are executed.
6. Inner Loop Update: After executing the inner loop body, the update statement of
the inner loop is executed.
7. Repeat Inner Loop Steps: Steps 4 through 6 are repeated until the inner loop
Let's consider a simple example to demonstrate the use of a nested for loop to print a
multiplication table:
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Explanation:
● Outer Loop (for (int i = 1; i <= rows; i++)): Controls the number of
rows.
● Inner Loop (for (int j = 1; j <= columns; j++)): Controls the
number of columns for each row.
● The inner loop runs from 1 to 5 for each outer loop iteration. Each time the inner
loop completes, the outer loop increments, and the inner loop starts again.
2. Generating Patterns: Nested loops are ideal for generating patterns, such as
triangles, squares, or pyramids of characters or numbers.
int n = 5;
for (int i = 1; i <= n; i++) { // Outer loop for number of rows
for (int j = 1; j <= i; j++) { // Inner loop for columns
System.out.print("* ");
}
System.out.println(); // Move to the next line after each row
}
Output:
*
* *
* * *
* * * *
* * * * *
3. Handling Complex Data Structures: Nested loops can navigate complex data
structures, such as nested lists or JSON objects.
3. Use Appropriate Variable Naming: Use meaningful variable names for loop
control variables to enhance code readability, especially when dealing with
nested loops.
4. Break Down Complex Logic: If nested loops become too complex, consider
breaking down the logic into separate methods or using other data structures.
Nested-for loops are powerful tools in Java programming. They enable developers to
perform multi-level iterations required for complex tasks such as handling
multidimensional data, generating patterns, and implementing algorithms. Engineers
can write more robust and efficient programs by understanding how to use nested loops
effectively. Proper use and awareness of nested loop pitfalls ensure code that is both
performant and easy to maintain.
Do It Yourself
1. Write a Java program to Print a Checkerboard Pattern Using Nested for Loops
2. Write a Java program to Generate a Pascal's Triangle Up to 5 Rows Using Nested for
Loops
Quiz
1. How many times will the inner loop execute in the following code?
A) 2
B) 3
C) 6
D) 9
Correct Answer: C
2. What will be the output of the following code?
A) * * *
B) * * * (two lines)
C) * * (three lines)
D) * (three lines)
Correct Answer: B
Correct Answer: C
A) The outer loop must run fewer times than the inner loop.
B) The inner loop is executed once for each iteration of the outer loop.
C) The outer loop is executed once for each iteration of the inner loop.
Correct Answer: B
The enhanced for loop, commonly known as the "for-each" loop, is a specialized
version of the for loop introduced in Java 5. It provides a simplified syntax for iterating
over arrays and collections. This loop is particularly useful when you need to iterate
through each element of a collection or array without needing to manage an index or
loop counter.
How It Works
The enhanced for loop can also be used with Java Collections, such as ArrayList:
import java.util.ArrayList;
elements. If you need to modify elements during iteration, a traditional for loop
or forEach method with lambda expressions should be used.
Limitations
1. No Access to Index: The enhanced for loop does not provide direct access to
the index of the current element. If you need to know the index, you should use a
traditional for loop or a different approach.
2. Read-Only Iteration: It does not allow modification of the collection or array
structure (e.g., adding or removing elements) while iterating. If you need to
modify the collection, consider using an iterator.
Example of Using forEach with Lambda Expressions (Java 8+)
For more advanced use cases, such as modifying elements or performing operations in
a functional style, Java 8 introduced the forEach method with lambda expressions:
import java.util.Arrays;
The enhanced for loop is a powerful feature in Java that simplifies iteration over arrays
and collections. It streamlines the process of accessing elements and improves code
clarity. While it provides a straightforward approach for iteration, understanding its
limitations and using it appropriately based on your application's needs is essential for
writing effective and efficient code.
Do It Yourself
1. Write a Java program to Iterate Over a List of Student Grades and Print Each Grade
Using a For-Each Loop
2. Write a program that finds and prints the maximum value in an integer array.
Quiz
2. Question: Can you modify the elements of an array while using a for-each loop?
○ A. Yes
○ No
○ Depends on the programming language
○ Depends on the compiler
Answer: No
4. Question: Can you use a for-each loop with primitive data types?
○ A. Yes
○ No
○ Only with arrays
○ Only with collections
Answer: No (only with arrays and collections)
References
Enhanced for-each loop - For Each Loop in Java#97 forEach Method in Java
End of Session - 6