Cover Image for Alphabet Triangle in C++
85 views

Alphabet Triangle in C++

To create an alphabet triangle in C++, you can use nested loops to print a pattern of alphabets. Here’s an example of how to create an alphabet triangle:

C++
#include <iostream>

int main() {
    int n;
    char currentChar = 'A';

    // Input the number of rows for the alphabet triangle
    std::cout << "Enter the number of rows: ";
    std::cin >> n;

    for (int i = 1; i <= n; ++i) {
        // Print spaces for formatting
        for (int j = 1; j <= n - i; ++j) {
            std::cout << "  ";
        }

        // Print alphabets in ascending order
        for (int k = 1; k <= i; ++k) {
            std::cout << currentChar << " ";
            ++currentChar; // Move to the next alphabet
        }

        // Move to the next line
        std::cout << std::endl;
    }

    return 0;
}

In this program:

  1. The user is prompted to enter the number of rows for the alphabet triangle.
  2. A variable currentChar is used to keep track of the current alphabet, initially set to ‘A’.
  3. Nested loops are used to iterate through the rows and columns of the triangle.
  4. In the inner loop, the current alphabet (currentChar) is printed, and currentChar is incremented to move to the next alphabet.
  5. The result is a pattern of alphabets forming an alphabet triangle.

For example, if you enter 5 as the number of rows, the program will generate the following alphabet triangle:

Plaintext
        A 
      B C 
    D E F 
  G H I J 
K L M N O 

You can adjust the number of rows by changing the value of n to create an alphabet triangle of the desired size.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS