Search code examples
c++alphabet

Printing triangle with given letter in C++


I would like to to print a triangle with a given letter. For example, if I input D, the program should return:

     A
     AB
     ABC
     ABCD

So far, I have managed to print all letters until the given one in my example, but as you see this method is not quite effective since I need to do this for all 26 cases since the English alphabet is 26 chars. Is there some way to optimize my code?

#include <iostream>

using namespace std;

int main() {
    char i;
    cout << "Enter char ";
    cin >> i;
    int c = static_cast<int>(i);
    if (65 < c) {
        cout << "A";
        cout << endl;
    }
    if (66 < c) {
        cout << "AB";
        cout << endl;
    }
    if (67 < c) {
        cout << "ABC";
        cout << endl;
    }

    for (int i = 64; i < c; i++) {
        cout << static_cast<char>(i + 1);
    }

    return 0;
}

Solution

  • You definitely need to work on your comprehension of loops. This one works just fine and it even has some checks on what is typed in and it eventually converts lower case letters into upper casse.

    char first = 'A';
    char last = 0;
    
    cout << "Enter a char: ";
    cin >> last;
    fflush(stdin);
    cout << "\n\n";
    
    if ((last > 96) && (last < 123)) //97 to 122 are lower case letters
    {
        last -= 32; //32 is the delta between each lower case letter and its upper case "twin"
    }
    
    if ((last > 64) && (last < 91))
    {
        for (char i = 65; i <= last; i++)
        {
            for (char j = 65; j <= i; j++)
            {
                cout << j;
            }
            cout << "\n";
        }
    }
    else
    {
        cout << "\nWrong character!!\n\n";
        return 0;
    }