Drawing A shape

Lesson 5
Author : Afrixi
Last Updated : November, 2022
C++ - Programming Language
This course covers the basics of programming in C++.
Table of Content

Drawing A shape

To draw a shape in C++, you can use nested loops to print spaces and asterisks in a pattern that forms a shape shape. Here’s an example code:

#include <iostream>

int main() {
    int n;

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

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            std::cout << "* ";
        }
        std::cout << std::endl;
    }

    return 0;
}

In this code, the user is prompted to enter the number of rows they want for the right triangle. Then, two nested loops are used to print asterisks in a pattern that forms a right triangle shape. The outer loop iterates through each row of the triangle, and the inner loop prints asterisks and a space for each column in the row.

When you run the code and enter the number of rows you want for the right triangle, it will output the right triangle shape in the console. For example, if you enter 5, it will output:

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

Note that the number of asterisks in each row is based on the row number, so that the triangle forms a right angle.