Nested For Loop in Java


This is a Java program that uses nested for loops to print a rectangle made of asterisks (*) to the console. Here's a breakdown of how the program works:

  • We declare a class called "nested_for".
  • We define a main method that takes an array of strings as its parameter.
  • We use a for loop to iterate from 1 to 5 (inclusive) using the variable "i".
  • For each iteration of the outer loop, we use another for loop to iterate from 1 to 5 (inclusive) using the variable "j".
  • For each iteration of the inner loop, we print an asterisk (*) to the console using the System.out.print method.
  • After the inner loop has finished iterating, we print a newline character ("\n") to the console using the System.out.println method to move to the next line.
  • The outer loop continues until all iterations have been completed, resulting in a rectangle made of asterisks being printed to the console.

Overall, this program demonstrates how to use nested for loops to print patterns to the console. In this case, we print a rectangle made of asterisks, but other patterns could be created using different loops and print statements.

Source Code

public class nested_for {
    public static void main(String args[]) {
 
        for(int i=1;i<=5;i++)//1<=5 2<=5
        {
            for(int j=1;j<=5;j++)
            {
                System.out.print("*");
            }
            System.out.println("");
        }
    }
}
 

Output

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
To download raw file Click Here

Basic Programs