Nested For Loops in Java - Notes for Class 9th ICSE Students
Nested For Loops in Java
Introduction:
- A nested for loop is a for loop inside another for loop.
- Commonly used for patterns, matrix operations, or other multi-level iterative tasks.
Definition and Syntax of a Nested For Loop:
A nested for loop consists of an outer loop and one or more inner loops. Each time the outer loop
executes, the inner loop completes all its iterations.
Syntax:
for(initialization; condition; update) {
for(initialization; condition; update) {
// Code to execute
Solved Programs Based on Nested Loops:
1. Right-Angled Triangle Pattern:
for(int i = 1; i <= 5; i++) {
for(int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
Output:
**
***
****
*****
2. Rectangular Pattern:
for(int i = 1; i <= 4; i++) {
for(int j = 1; j <= 5; j++) {
System.out.print("*");
System.out.println();
Output:
*****
*****
*****
*****
3. Number Pyramid Pattern:
for(int i = 1; i <= 5; i++) {
for(int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
Output:
12
123
1234
12345
4. Inverted Right-Angled Triangle:
for(int i = 5; i >= 1; i--) {
for(int j = 1; j <= i; j++) {
System.out.print("*");
System.out.println();
Output:
*****
****
***
**
5. Hollow Rectangle Pattern:
for(int i = 1; i <= 4; i++) {
for(int j = 1; j <= 5; j++) {
if(i == 1 || i == 4 || j == 1 || j == 5)
System.out.print("*");
else
System.out.print(" ");
System.out.println();
Output:
*****
* *
* *
*****
6. Alphabet Triangle:
char ch = 'A';
for(int i = 1; i <= 5; i++) {
for(int j = 1; j <= i; j++) {
System.out.print(ch + " ");
ch++;
System.out.println();
Output:
BC
DEF
GHIJ
KLMNO
Key Points to Remember:
- Nested loops are loops inside other loops, useful for multi-level iterations.
- Each iteration of the outer loop triggers a full cycle of the inner loop.
- Patterns, matrices, and data structures can be easily handled with nested loops.
- Always check loop conditions to avoid infinite loops.