Java Program: Printing an Inverted Triangle using Asterisks

Feb 19th, 2009 by ddenz11

If this is a homework or a lab exercise for your computer science subject read on and get the solution!

"For" loops are efficient if you know how many times you want to repeat or execute the statement or group of statements, so here the counters (i and j) will start at 1 and end with the desired width of the inverted triangle. Remember, that if your counters start at 1 (i.e. i=1) it will terminate at a value less than or equal to that value (i.e. i<=width) to avoid "Off by One" errors.

//the class starts here!

public class InvertedTriangle{

    private int width;

//we will use a constructor to set the value of "width"

    public InvertedTriangle (int _width){

        width = _width;

    }

//the method to create the inverted triangle with "width"

    public String toString(){

        String r = "";

        int num = width;

        for(int i=1; i<=width; i++){

            for(int j=1; j<=num; j++){

                r = r + "*";

            }

            num = num - 1;

            r = r + "\n";

        }

        return r;

    }

}

so that's that.. :D So we make another class to test "Inverted Triangle". We will make another class "TestInvertedTriangle" with the main method (using 10 as width, you can change this value if you want..)

public class TestInvertedTriangle{

    public static void main(String[] args){

        InvertedTriangle c = new InvertedTriangle(10);

        System.out.print(c.toString());

    }

}

if you have any questions, please do leave a message!

NOTE: This is a program that I made myself. I have tested it and came out with the desired output. I am also new in Java programming and I may not have applied the "elegant way" of writing Java programs. So please do understand. :D

ddenz11

Written by ddenz11

Rate this Article:

Rating: 4.9/5 (11 votes cast)

Add new comment

* You must be logged in order to leave comments, please Sign in or join us.

Comments

Sankar Bose, over a year ago
Report comment

Hai ddenz,

I came across ur article in net,it was useful to me.But i am beginner in programming,i am really afraid of the for loops especially one that prints different shapes like triangle ,paralellogram etc.,i have lot of school assignments of these kind.I want to know how to print different structures using for loops..can u please make me understand..by sending some articles to my mail ..i feel really inferior when my class mates finish them so quickly than me.. Expecting ur reply

Rexaniel Saburnido, over a year ago
Report comment

nice article!!! 5 stars for this. WE can be a good partners here in bukisa. Lets view each others articles.