Powered by Blogger.

Java Program to Print Square Pattern with Stars

>> Wednesday, August 8, 2018

This is a very basic program for beginners who starts learning for loop. This is the best example to understand how the nested loops works. In our program we are going to print the below square star (* ) pattern as shown in the image.
SquarePattern_JavabynataraJ

In the below program we will be using the print( ) and println( ) methods to print the data on Screen. Normally both print( ) and println( ) methods are same with small differences between them.

Difference between print( ) and println( ) methods:

print( ) method: this method will print the data on the same line again and again on the Screen. We can see the cursor at the end of the same line.

println( ) method: this method will be printing the data in the new line.

In the below program we are using the nested for loop, means for each iteration of i, the '*' value prints 5 times in the same line and the println method passes the cursor to next line and the next iteration will be done up to i<=5 condition fails. So totally 5 rows with stars will print on screen.

//javabynataraj.blogspot.com
public class SquarePattern {
 public static void main(String[] args) {
  for(int i=1;i<=5;i++){
   for(int j=1;j<=5;j++){
    System.out.print(" * ");
   }
   System.out.println(" ");
  }
 }
}
Output:



Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.