How can i print a triangle with “*”s using for loop in java?

前端 未结 9 959
情话喂你
情话喂你 2021-01-29 10:35

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:

*
**
**         


        
相关标签:
9条回答
  • 2021-01-29 11:25

    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

    0 讨论(0)
  • 2021-01-29 11:28
              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);
    
    
            }           
        }
    }
    
    0 讨论(0)
  • 2021-01-29 11:30

    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();
                         }
    }
    
    0 讨论(0)
提交回复
热议问题