Thursday, January 18, 2018

Print diamond using two for loops only

This code is implemented and provided by Ajit Srivastava from Gniet college, Greater Noida.

Note : Create a Java project in Eclipse IDE and save this class inside PrintDiamondUsingTwoLoops.java file.

import java.util.Scanner;

public class PrintDiamondUsingTwoLoops
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the number of terms for the Diamond pattern :");
int term = s.nextInt(); // fetch int value from the keyboard and store

int copyOfTerm = term;

for (int i = 1; i < 2 * term; i++)
{
for (int j = 1; j <= (term + 1); j++)
{
if (j <= copyOfTerm)
{
System.out.print(" ");
}
else
{
System.out.print("* ");
}

} // end  of inner for loop

System.out.println();

if (i < term)
{
copyOfTerm--;
}
else
{
copyOfTerm++;
}

} // end of outer for loop

} // end of main method

} // end of class

No comments:

Post a Comment