Search code examples
javafor-loopcharacterangletriangular

Print right angle triangle with characters


I want to create a right angled triangle made out of characters. The code asks you how many rows you want the triangle to be, and the maximum is 26 of course. When I test the code I input 5 (for no reason). This is my code so far:

import java.util.*;

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

        Scanner input = new Scanner (System.in);

        System.out.print("Ange längden på de 2 lika långa sidorna (avsluta med -1): ");
        int rader = input.nextInt();

        int i = 0;
        int j = 0;
        int k = 0;
        char bokstav = (char)( i + 'A');

        for (i=0; i<rader; i++) {
            for (j=0; j<i+1; j++) {
                System.out.print(bokstav);

            }bokstav++;
            System.out.println();

        }

    }

}

This is the output I am after (if you input 5):

A
AB
ABC
ABCD
ABCDE

This is what I get when I input 5 in the code above:

A
BB
CCC
DDDD
EEEEE

Can someone please help me? Am I on the right track, or am I completely lost? Feels like the latter... And yes, this is for school. I have tried as much as I can, and I am now stuck.

Much appreciated!


Solution

  • The problem with your solution is that you only increment the character after each line is written; You should be incrementing the character after each character is written. Upon a successful line write, you should reset the character to 'A'.

        for (int i = 0; i < 5; i++) {
            char c = 'A';
            for (int j = 0; j < i+1; j++) {
                System.out.print(c);
                c++;
            }
            System.out.println();
        }
    

    I will also point out that this solution is not recursion. A simple definition of recursive method is one that will call itself to find the solution to smaller segments of the problem. For example, a recursive solution to printing a similar pyramid make look something like this.

    public static void print(int level) {
        if (level <= 0 || level > 26) {
            return;
        }
        print(level - 1);
        System.out.println(line(level));
    }
    
    public static String line(int level) {
        String line = "";
        if (level > 0 && level <= 26) {
            line = line(level--) + (char)('A' + level);
        }
        return line;
    }