C++ Code Example: Left Arrow Pattern

This program generates a left arrow pattern based on the number of rows specified by the user. The pattern is symmetric, with a top half and a bottom half.

Code Example

#include <iostream>
using namespace std;

int main() {
    // Get the number of rows from the user
    int num_rows;
    cout << "Enter the number of rows: ";
    cin >> num_rows;

    // Display the left arrow pattern
    for (int i = 1; i <= num_rows; i++) {
        for (int j = 1; j <= num_rows - i; j++) {
            cout << " ";
        }
        for (int k = 1; k <= i; k++) {
            cout << "*";
        }
        cout << endl;
    }

    for (int i = num_rows - 1; i >= 1; i--) {
        for (int j = 1; j <= num_rows - i; j++) {
            cout << " ";
        }
        for (int k = 1; k <= i; k++) {
            cout << "*";
        }
        cout << endl;
    }

    return 0;
}

Output

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

Code Explanation

In this code, the user is prompted to enter the number of rows for the left arrow pattern. The first for loop is responsible for printing the top half of the pattern, and the second for loop prints the bottom half.

The inner for loops within each outer loop are used to print spaces and asterisks (*) for each row. The cout << " "; statement prints a space, and the cout << "*"; statement prints an asterisk. The endl statement is used to move to the next line after each row.