Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Working with for loop in Java

[post-views]

 

In this lesson, you will learn.

  • The For loop
  • Multiple Statements in For Loop
  • Nested For Loop
  • For Loops and While Loop
  • Examples

 

The for Loop

  • A for loop in Java is a control flow statement that allows code to be executed repeatedly for a certain number of times, based on a given condition.

 

Note: The for loop is often used when the number of iterations is known before entering the loop.

Note: While loop is preferred when the number of iterations is not known beforehand or depends on dynamic conditions.

 

Syntax

for (initialization; condition; update) {
    // Statements to be executed
}

 

Explanation

  • Initialization: This expression initializes the loop and is executed once at the beginning of the loop.
  • Condition: This is a boolean expression that is checked before each iteration of the loop. If true, the loop continues; if false, the loop ends.
  • Update: This expression is executed after each iteration of the loop. It’s typically used to update or increment the loop variable.

 

Example 1: Simple Counter

package ch5;

public class SimpleCounter {

	public static void main(String[] args) {
		for (int i = 0; i < 5; i++) {
		    System.out.println("Count: " + i);
		}
	}
}

 

Output

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

 

This loop prints numbers from 0 to 4. The loop initializes i to 0 and increments it by 1 each time until it reaches 4.

 

Example 2: Sum of Numbers

package ch5;

public class SumOfNumbers {

	public static void main(String[] args) {
		int sum = 0;
		for (int i = 1; i <= 10; i++) {
		    sum += i;
		}
		System.out.println("Sum: " + sum);
	}
}

 

Output

Sum: 55

This loop calculates the sum of numbers from 1 to 10.

 

Example 4: Reverse Loop

package ch5;

public class ReverseLoop {

	public static void main(String[] args) {
		for (int i = 10; i > 0; i--) {
		    System.out.println("Reverse Count: " + i);
		}
	}
}

 

Output

Reverse Count: 10
Reverse Count: 9
Reverse Count: 8
Reverse Count: 7
Reverse Count: 6
Reverse Count: 5
Reverse Count: 4
Reverse Count: 3
Reverse Count: 2
Reverse Count: 1

 

This loop counts down from 10 to 1, decrementing i in each iteration.

 

Example 5: Looping Through a String

package ch5;

public class LoopinString {

	public static void main(String[] args) {
		String greeting = "Hello";
		for (int i = 0; i < greeting.length(); i++) {
		    System.out.println(greeting.charAt(i));
		}
	}
}

 

Output

H
e
l
l
o

 

This loop prints each character of the string “Hello”.

 

Multiple Statements in For Loop

In Java, you can use multiple statements in the initialization and update parts of a for loop by separating them with commas.

Note: This is useful when you need to work with multiple variables within the loop. However, it’s important to note that the conditional part of the for loop can only contain one boolean expression.

 

Syntax

for (initial1, initial2; condition; update1, update2) {
    // Code block to be executed
}

 

Example 1: Using Two Variables

package ch5;

public class MultipleStatementLoop {

	public static void main(String[] args) {
		for (int i = 0, j = 10; i < j; i++, j--) {
		    System.out.println("i = " + i + ", j = " + j);
		}
	}
}

 

Output

i = 0, j = 10
i = 1, j = 9
i = 2, j = 8
i = 3, j = 7
i = 4, j = 6

 

In this example, i is initialized to 0 and j to 10. The loop runs until i is less than j. In each iteration, i is incremented and j is decremented.

 

Example 2: Sum and Average Calculation

package ch5;

public class SumAndAverage {

	public static void main(String[] args) {
		int sum = 0, count = 0;
		for (int i = 1, j = 10; i <= j; i++, j--, count++) {
		    sum += i + j;
		}
		double average = (double) sum / count;
		System.out.println("Sum: " + sum + ", Average: " + average);
	}
}

 

Output

Sum: 55, Average: 11.0

 

Here, the loop calculates the sum of the numbers from 1 to 10 and their reverse (10 to 1) in each iteration. It also counts the number of iterations to calculate the average.

 

Nested for Loop

A nested for loop in Java refers to a for loop within another for loop.

Note: Nested for loop allows you to perform complex iterations, and it’s commonly used in scenarios where you need to work with multi-dimensional data structures like arrays.

 

Example 1: Printing a Multiplication Table

package ch5;

public class NestedLoop {

	public static void main(String[] args) {
		for (int i = 1; i <= 10; i++) {      // Outer loop
		    for (int j = 1; j <= 10; j++) {  // Inner loop
		        System.out.print(i * j + "t"); // Print the product
		    }
		    System.out.println(); // New line after each row
		}
	}
}

 

Output

1	2	3	4	5	6	7	8	9	10	
2	4	6	8	10	12	14	16	18	20	
3	6	9	12	15	18	21	24	27	30	
4	8	12	16	20	24	28	32	36	40	
5	10	15	20	25	30	35	40	45	50	
6	12	18	24	30	36	42	48	54	60	
7	14	21	28	35	42	49	56	63	70	
8	16	24	32	40	48	56	64	72	80	
9	18	27	36	45	54	63	72	81	90	
10	20	30	40	50	60	70	80	90	100	

 

This code prints a 10×10 multiplication table.

 

Example 2: Creating Patterns

package ch5;

public class CreatingPatternForLoop {

	public static void main(String[] args) {
		int rows = 5;

		for (int i = 1; i <= rows; i++) {      // Outer loop for rows
		    for (int j = 1; j <= i; j++) {     // Inner loop for columns
		        System.out.print("* ");        // Print a star
		    }
		    System.out.println(); // New line after each row
		}
	}
}

 

Output

* 
* * 
* * * 
* * * * 
* * * * * 

 

This code will print a left-aligned pyramid of stars with 5 rows.

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review