ch1maera
ch1maera

Reputation: 1447

Drawing Isosceles Triangle in Java Using Loops

This is the problem:
Create an IsoTri application that prompts the user for the size of an isosceles triangle and then displays the triangle with that many lines.

Example: 4

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

The IsoTri application code should include the printChar(int n, char ch) method. This method will print ch to the screen n times.

This is what I have so far:

public static void main(String[] args) {
        int n = getInt("Give a number: ");
        char c = '*';
        printChar(n, c);


    }

    public static int getInt(String prompt) {
        int input;

        System.out.print(prompt);
        input = console.nextInt();

        return input;
    }

    public static void printChar(int n, char c) {
        for (int i = n; i > 0; i--) {
            System.out.println(c);
        }

    }

I'm not sure how to get it to print the triangle. Any help is appreciated.

Upvotes: 1

Views: 7837

Answers (3)

ParkerHalo
ParkerHalo

Reputation: 4430

A little recursive solution:

private static String printCharRec(String currStr, int curr, int until, char c) {
    String newStr = "";
    for (int i = 1; i < curr; i++)
        newStr += c;
    newStr += '\n';
    currStr += newStr;

    if (curr < until) {
        currStr = printCharRec(currStr, curr+1, until, c);
        currStr += newStr;
    }

    return currStr;
}

Upvotes: 0

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22224

First of all your printChar is wrong. It will print every * in a new line. You need to print the * character n times and then a new line. E.g.

public static void printChar(int n, char c) {
    for (int i = n; i > 0; i--) {
        System.out.print(c);
    }
    System.out.println();
}

After that given you have to use printChar I would recommend 2 for loop one one incrementing one deincrementing

public static void main(String[] args) {
    int n = getInt("Give a number: ");
    char c = '*';

    // first 3 lines
    for (int i = 1; i < n; ++i)
        printChar(i, c);

    // other 4 lines
    for (int i = n; i > 0; --i)
        printChar(i, c);
}

Upvotes: 2

Bon
Bon

Reputation: 3103

You need two nested for loops:

public static void printChar(int n, char c) {
    // print the upper triangle
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < i + 1; ++j) {
            System.out.print(c);
        }
        System.out.println();
    }

    // print the lower triangle
    for (int i = n - 1; i > 0; --i) {
        for (int j = 0; j < i; ++j) {
            System.out.print(c);
        }
        System.out.println();
    }
}

Upvotes: 2

Related Questions