I want to draw a triangle with stars like below using for loop, but i really don\'t have any idea of how to do this ? Triangle is going to be like this:
*
**
**
You will need two for-loops; one to print the line, and one to print the characters in a line. The number of the current line can be used to print a certain number of stars.
Use System.out.print("*")
to print without adding a new line, at the end of the second loop do a System.out.println()
I'll leave the implementation of the loops as an exercise, here is the syntax: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
import java.util.*;
class StarForloop
{
public static void main(String arg[])
{
Scanner ob=new Scanner(System.in); //getting input
System.out.println("Enter any NO");
int count=ob.nextInt();
String ab="*"; // initialize string variable
for(int i=1; i<=count; i++)
{
ab=ab+"*"; // here you add one another string
System.out.println(ab);
}
}
}
you just need two loops for your required goal the third loop is useless the first outer loop is for rows and the inner loop is for printing "*".The outerloop is used here for changing the rows and maintaining the number of required rows.
public static void tri()
{
for(int i=0;i<8;i++)
{
for(int j=0;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
}