Search code examples
javaloopsif-statementtriangle-count

How do I let my program print a complete right angle triangle for certain values?


enter image description here

I tested the program out with 88 and it was left with one star to complete the triangle. 87, two stars 86 three stars. This went on for certain numbers.

These are the two options for programming generate function

• One is to compute the length of the last line, say maxLen, and use a double for-loop to generate a line of one star, a line of two stars, a line of three starts, and so on, ending with a line of maxLen stars. The value of maxLen is the smallest integer that is greater than or equal to the larger solution of the quadratic equation x ( x + 1 ) = 2 * num.

• The other is to use one for-loop to print num stars while executing System.out.println()wherever the newline is needed. The point at which the newline is needed can be computed using two accompanying integer variables, say len and count. Here the former is the length of the line being generated and the count is the number of stars yet to be printed in the line. We start by setting the value of 1 to both integer variables. At each round of the iteration, we decrease the value of count, if the value of count becomes 0, we insert the newline, increase the value of len and then copy of the value of len to count. When the loop terminates, if the value of count is neither equal to 0 nor equal to count, we extend the present line by adding more stars.

    import java.util.*;
    public class TriangleSingle
    {
        public static void generate(int x) //Generates the Triangle
        {
        int len, count;
        len = 1;
        count = 1;
        for (int k = 1; k <= x; k++)
        {
                System.out.print("*");

                count --;

                if (count == 0)
                {
                    System.out.println();
                    len ++;
                    count = len;
                }



        }

        if (count!= 0 || count != len)
                {

            System.out.println("*"); //Completes the triangle if needed
                                       // This is the **problem spot**
                }

Solution

  • Try this:-   
    
      public static void generate(int x) //Generates the Triangle
                {
                int len, count;
                len = 1;
                count = 1;
                for (int k = 1; k <= x; k++)
                {
    
                    for (int i = 1; i <= k; i++) {
                        System.out.print("*");
                    }
                    System.out.println();
    
    
                }
    
                }