More Java 101: Printing Left/Right Aligned Triangles

Fun with asterisks!

Here’s some more crap code I wrote for my Java class. This time, I had to print several triangles made of asterisks. I’ve seen this problem a LOT on the web, and it took me a while to figure out how to set up the algorithm.

Nested for loops are where it’s at.

The outer for loop controls the number of rows — in this case, 10.

The inner for loop(s) control the number of asterisks (or spaces, because we were told to use print and println statements only.)

For right-aligned triangles, you’ll need TWO inner for loops, and the way to get ’em working just the way you want is to initialize one inner loop’s counter to the outer loop’s counter, then initialize the other inner loop’s counter to ( x – outerLoopCounter), where x is the desired length of the row.

Trickay!

Parts of this are still butt-ugly and kinda backwards, but I’m still cleaning it up. Let me know if you have any helpful hints.


//Triangles program

public class Triangles
{
	public static void main( String[] args )

	// drawing a triangle of asterisks
	// growing vertically from one to 10 asterisks
	{

	for( int counter = 1; counter = 1; --number)
				System.out.print( "*" );
				System.out.println();
		}
	

	// drawing a triangle of asterisks
	// shrinking vertically from 10 to one asterisks
	
	for( int counter2 = 10; counter2 >= 0; --counter2 )
		{
			for(int number2 = counter2; number2 >= 1; --number2)
				System.out.print( "*" );
				System.out.println();
		}


	// draw a triangle of asterisks
	// growing, right aligned
	for( int counter3 = 1; counter3 = 1; --number3)
				System.out.print( " " );

			for(int number4 = counter3; number4 >= 1; --number4)
				System.out.print( "*" );

			System.out.println();
		}

	// draw a triangle of asterisks
	//shrinking, right aligned
	for( int counter4 = 1; counter4 = 1; --number5)
				System.out.print( " " );

			for(int number6 = (10 - counter4 ); number6 >= 1; --number6 )
				System.out.print( "*" );

			System.out.println();
		}

	} // end method main
} // end class Triangles

Image courtesy of journeyscoffee.

13 thoughts on “More Java 101: Printing Left/Right Aligned Triangles

  1. I wrote something similar for my Java 101.

    public class star1
    {
    public static void main(String[] args)
    {
    for (int row=1; row<6; row ++)
    {
    for (int col=0; col< row; col++)
    System.out.print("*");
    System.out.println();
    }

    }

    }

  2. Fun!

    One comment — variable names should be descriptive, so, for example counter might be better as verticalAscendingCounter, and counter4 might be better as descendingRightAlignedCounter, or something like that. The more descriptive your variable names (within reason), the less you will need to comment, because the intent of your code will be clear.

    Avoid variable names that differ only by numeric suffixes (like counter1, counter2, counter3…) like the PLAGUE.🙂

  3. Interestingly, this isn’t really a Java-specific problem at all. But it’s a great way to learn about interacting FOR loops, which work pretty much the same way in $LANGUAGE_OF_CHOICE.

  4. For simple for statements I typically use i, j, k etc… for variables. It is true though that you should use variables with names that are a bit more descriptive in general. I avoid variables with numbers as well.

    Here’s an example of how I’d do the first triangle.


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

    • public class Triangles {
      	public static void main( String[] args ) {
      		for (int i = 1, j = 5; i < 10; i += 2, j--) {
      			for (int k = 0; k < j; k++) {
      				System.out.print(" ");
      			}
      			for (int k = 0; k < i; k++) {
      				System.out.print("*");
      			}
      			System.out.println();
      		}
      	}
      }
      
  5. Err, of course I realize after posting my example that none of your triangles are center aligned. All the better I guess since it doesn’t directly give you an answer.😐

  6. Nice! Verbose, though. Here’s another implementation, that your teacher may or may not reject (due to its use of the String api):

    public class Triangles {
        public static void main(String[] args) {
            String asterisks = "***********";
            String spaces = "           ";
    
            // left aligned, growing
            for (int i = 0; i <= 10; i++) {
                System.out.println(asterisks.substring(10-i));
            }
    
            // left aligned, shrinking
            for (int i = 0; i <= 10; i++) {
                System.out.println(asterisks.substring(i));
            }
    
            // right aligned, growing
            for (int i = 0; i <= 10; i++) {
                System.out.println(spaces.substring(i) + asterisks.substring(10-i));
            }
    
            // right aligned, shrinking
            for (int i = 0; i <= 10; i++) {
                System.out.println(spaces.substring(10-i) + asterisks.substring(i));
            }
        }
    }
    • Ah, but it’s the age-old problem of computer science *class* as opposed to real computer science: I’m not allowed to use techniques we haven’t covered yet.😉

      I’d actually lose points for substrings.

  7. Hi Haider, you can use two loops like this:

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

    • import java.util.Scanner;
      public class Triangle2 {
      public static void main(String[] args) {
      String asterisks = “***********”;
      String spaces = ” “;

      // left aligned, growing
      for (int i = 0; i <= 10; i++) {
      System.out.println(asterisks.substring(10-i));
      }

      // left aligned, shrinking
      for (int i = 0; i <= 10; i++) {
      System.out.println(asterisks.substring(i));
      }

      // right aligned, growing
      for (int i = 0; i <= 10; i++) {
      System.out.println(spaces.substring(i) + asterisks.substring(10-i));
      }

      // right aligned, shrinking
      for (int i = 0; i <= 10; i++) {
      System.out.println(spaces.substring(10-i) + asterisks.substring(i));
      }
      }
      }

      can somebody can coonect this two outputs..?

  8. int x =5 ;
    for (int row = 0; row < x; row++) {

    for (int space=x-row; 0 < space; space–)
    {
    System.out.print(" ");
    }

    for (int col = 0; col <= row*2; col++) {
    System.out.print("*");
    }

    System.out.print("\n");
    }

Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s