Creating a triangle with for loops
Asked Answered
D

13

10

I don't seem to be able to find the answer to this-

I need to draw a simple triangle using for loops.

    *
   ***
  *****
 *******
*********

I can make a half triangle, but I don't know how to add to my current loop to form a full triangle.

*
**
***
****
*****
for (int i = 0; i < 6; i++) {
    for (int j = 0; j < i; j++) {
        System.out.print("*");
    }
    System.out.println("");
}
Dahomey answered 10/7, 2012 at 8:43 Comment(2)
Here you can find your solution- java4732.blogspot.in/2016/08/pyramid-programs-in-java.htmlUntouched
I’m voting to close this question because it should exist on code golfJus
E
18

First of all, you need to make sure you're producing the correct number of * symbols. We need to produce 1, 3, 5 et cetera instead of 1, 2, 3. This can be fixed by modifying the counter variables:

for (int i=1; i<10; i += 2)
{
    for (int j=0; j<i; j++)
    {
        System.out.print("*");
    }
    System.out.println("");
}

As you can see, this causes i to start at 1 and increase by 2 at each step as long is it is smaller than 10 (i.e., 1, 3, 5, 7, 9). This gives us the correct number of * symbols. We then need to fix the indentation level per line. This can be done as follows:

for (int i=1; i<10; i += 2)
{
    for (int k=0; k < (4 - i / 2); k++)
    {
        System.out.print(" ");
    }
    for (int j=0; j<i; j++)
    {
        System.out.print("*");
    }
    System.out.println("");
}

Before printing the * symbols we print some spaces and the number of spaces varies depending on the line that we are on. That is what the for loop with the k variable is for. We can see that k iterates over the values 4, 3, 2, 1 and 0 when ì is 1,3, 5, 7 and 9. This is what we want because the higher in the triangle we are, the more spaces we need to place. The further we get down the triangle, we less spaces we need and the last line of the triangle does not even need spaces at all.

Editorialize answered 10/7, 2012 at 8:52 Comment(0)
L
21

A fun, simple solution:

for (int i = 0; i < 5; i++) 
  System.out.println("    *********".substring(i, 5 + 2*i));
Lauber answered 10/7, 2012 at 9:20 Comment(0)
E
18

First of all, you need to make sure you're producing the correct number of * symbols. We need to produce 1, 3, 5 et cetera instead of 1, 2, 3. This can be fixed by modifying the counter variables:

for (int i=1; i<10; i += 2)
{
    for (int j=0; j<i; j++)
    {
        System.out.print("*");
    }
    System.out.println("");
}

As you can see, this causes i to start at 1 and increase by 2 at each step as long is it is smaller than 10 (i.e., 1, 3, 5, 7, 9). This gives us the correct number of * symbols. We then need to fix the indentation level per line. This can be done as follows:

for (int i=1; i<10; i += 2)
{
    for (int k=0; k < (4 - i / 2); k++)
    {
        System.out.print(" ");
    }
    for (int j=0; j<i; j++)
    {
        System.out.print("*");
    }
    System.out.println("");
}

Before printing the * symbols we print some spaces and the number of spaces varies depending on the line that we are on. That is what the for loop with the k variable is for. We can see that k iterates over the values 4, 3, 2, 1 and 0 when ì is 1,3, 5, 7 and 9. This is what we want because the higher in the triangle we are, the more spaces we need to place. The further we get down the triangle, we less spaces we need and the last line of the triangle does not even need spaces at all.

Editorialize answered 10/7, 2012 at 8:52 Comment(0)
A
4

I appreciate the OP is new to Java, so methods might be considered "advanced", however I think it's worth using this problem to show how you can attack a problem by breaking it into pieces.

Let's think about writing a method to print a single line, telling the method which number line it is:

public void printTriangleLine(int rowNumber) {
    // we have to work out what to put here
}

We have to print some number of spaces, then some number of stars.

Looking at the example, I can see that (if the first row is 0) it's (5-rowNumber) spaces and (2*rowNumber + 1) stars.

Let's invent a method that prints the rows of characters for us, and use it:

public void printTriangleLine(int rowNumber) {
    printSequence(" ", 5 - rowNumber);
    printSequence("*", 2 * rowNumber + 1);
    System.out.println(); 
}

That won't compile until we actually write printSequence(), so let's do that:

public void printSequence(String s, int repeats) {
    for(int i=0; i<repeats; i++) {
        System.out.print(s);
    }
}

Now you can test printSequence on its own, and you can test printTriangleLine on its own. For now you can just try it out by calling those methods directly in main()

public static void main(String [] args) {
    printSequence("a",3);
    System.out.println();
    printTriangleLine(2);
}

... run it and verify (with your eyes) that it outputs:

aaa
   *****

When you get further into programming, you'll want to use a unit testing framework like jUnit. Instead of printing, you'd more likely write things like printTriangleLine to return a String (which you'd print from higher up in your program), and you would automate your testing with commands like:

assertEquals("   *****", TriangleDrawer.triangleLine(2));
assertEquals("     *", TriangleDrawer.triangleLine(0))

Now we have the pieces we need to draw a triangle.

public void drawTriangle() {
    for(int i=0; i<5; i++) {
        printTriangleLine(i);
    }
}

The code we have written is a bit longer than the answers other people have given. But we have been able to test each step, and we have methods that we can use again in other problems. In real life, we have to find the right balance between breaking a problem into too many methods, or too few. I tend to prefer lots of really short methods.

For extra credit:

  • adapt this so that instead of printing to System.out, the methods return a String -- so in your main() you can use System.out.print(drawTriangle())
  • adapt this so that you can ask drawTriangle() for different sizes -- that is, you can call drawTriangle(3) or drawTriangle(5)
  • make it work for bigger triangles. Hint: you will need to add a new "width" parameter to printTriangleLine().
Agrostology answered 21/8, 2012 at 12:43 Comment(0)
B
3

First think of a solution without code. The idea is to print an odd number of *, increasing by line. Then center the * by using spaces. Knowing the max number of * in the last line, will give you the initial number of spaces to center the first *. Now write it in code.

Bedsore answered 12/6, 2015 at 2:7 Comment(0)
B
2

Try this one in Java

for (int i = 6, k = 0; i > 0 && k < 6; i--, k++) {
    for (int j = 0; j < i; j++) {
        System.out.print(" ");
    }
    for (int j = 0; j < k; j++) {
        System.out.print("*");
    }
    for (int j = 1; j < k; j++) {
        System.out.print("*");
    }
    System.out.println();
}
Bodleian answered 11/7, 2013 at 10:19 Comment(0)
L
1

Homework question? Well you can modify your original 'right triangle' code to generate an inverted 'right triangle' with spaces So that'll be like

for(i=0; i<6; i++)
{
    for(j=6; j>=(6-i); j--)
    {
        print(" ");
    }
    for(x=0; x<=((2*i)+1); x++)
    {
        print("*");
    }
    print("\n");
}
Lapham answered 10/7, 2012 at 8:51 Comment(1)
It is yes, I'm completely new to javaDahomey
M
1
  for (int i=0; i<6; i++)
  {
     for (int k=0; k<6-i; k++)
     {
        System.out.print(" ");
     }
     for (int j=0; j<i*2+1; j++)
     {
        System.out.print("*");
     }
     System.out.println("");
  }
Monadnock answered 10/7, 2012 at 8:51 Comment(0)
L
1

This will answer to your question. uncomment the commented code to display only outer line :)

public class TrianglePattern {

    public static void main(String[] args) {
        // This logic will generate the triangle for given dimension
        int dim = 10;
        for (int i = 0; i < dim; i++) {
            for (int k = i; k < dim; k++) {
                System.out.print(" ");
            }
            for (int j = 0; j <= i; j++) {
                //if (i != dim - 1)
                //  if (j == 0 || j == i)
                //      System.out.print("*");
                //  else
                //      System.out.print(" ");
                //else
                    System.out.print("*");
                System.out.print(" ");
            }
            System.out.println("");
        }
    }
}
Lorolla answered 17/11, 2013 at 10:14 Comment(0)
C
1
private static void printStar(int x) {
    int i, j;
    for (int y = 0; y < x; y++) { // number of row of '*'

        for (i = y; i < x - 1; i++)
            // number of space each row
            System.out.print(' ');

        for (j = 0; j < y * 2 + 1; j++)
            // number of '*' each row
            System.out.print('*');

        System.out.println();
    }
}
Clements answered 21/10, 2014 at 5:31 Comment(0)
L
0

This lets you have a little more control and an easier time making it:

public static int biggestoddnum = 31;

public static void main(String[] args) {
    for (int i=1; i<biggestoddnum; i += 2)
    {
        for (int k=0; k < ((biggestoddnum / 2) - i / 2); k++)
        {
            System.out.print(" ");
        }
        for (int j=0; j<i; j++)
        {
            System.out.print("*");
        }
        System.out.println("");
    }
}

Just change public static int biggestoddnum's value to whatever odd number you want it to be, and the for(int k...) has been tested to work.

Lexi answered 15/10, 2017 at 12:16 Comment(0)
C
0

Well, there will be two sequences size-n for spaces and (2*(n+1)) -1 for stars. Here you go.

public static void main(String[] args) {
    String template = "***************************";
    int size = (template.length()/2);
    for(int n=0;n<size;n++){
        System.out.print(template.substring(0,size-n).replace('*',' '));
        System.out.println(template.substring(0,((2*(n+1)) -1)));
    }
}
Coalesce answered 29/3, 2018 at 12:22 Comment(0)
D
0

Try this code

class Main{
public static void main (String[] args) {
 //[][][][][][][][][[[[[[[[[][[[[[[[]]]]]]]]]]]]]]
 String s="*";
 String s3="*";
 String s2=" ";
 for (int l=10,ln=0;l!=0 && ln!=10 ;l--,ln++) {
 System.out.println(s2.repeat(l)+s+s3);
  s+="*"; 
  s3+="*"; 
 }
 //[][][][][][][][][[[[[[[[[][[[[[[[]]]]]]]]]]]]]]
}
}

AND THIS IS MY OUTPUT>>

~ $ java Main.java
          **
         ****
        ******
       ********
      **********
     ************
    **************
   ****************
  ******************
 ********************
~ $

IN THIS CODE FIRST I HAVE WRITTEN A COMMAND TO MAKE A HALF TRIANGLE AND THEN TO DRAW ANOTHER HALF WHICH MAKE A FULL TRIANGLE.

HOPE IT WILL HELP YOU;

Definiens answered 2/6, 2022 at 14:59 Comment(0)
G
-1

Try this

class piramid 
{
    public static void main(String[] args) 
    {
        //System.out.println("Hello World!");

    int max = 7; 
    int k=max/2;
    int j ; 
    printf("\n");
    printf("\n");
    printf("\n");
    printf("\n");
    for(i=k;i>0;i--){

          for(j=0;j<k+1;j++){

                if(i==j){

                       printf("*");

                }else if(j>i){
                      printf(" ");
                      printf("*");
                }else {
                      printf(" ");

                }

           }
            printf("\n");

    }

   }

}

hope it will help you

Gist answered 30/11, 2019 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.