Elyssehui Elyssehui - 1 month ago 14
C++ Question

How do you make a rectangle and triangle shape in C++

How do i achieve this format when i keyed in int of ' 245 ':

(where if it is odd number it will be a rectangle, and even number will be triangle)

1
1 2

1
1 2
1 2 3
1 2 3 4

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5


This is my code so far:

(I can't seemed to output triangle and rectangle at the same time)

int n;
int lastDigit;

do
{
cout << "Enter a positive integer: ";
cin >> n;

}while ( n <= 1 || n == '0');

cout << endl;

// If even digit - tri
do
{
lastDigit = n%10;

if (lastDigit / 2 ==0)
{
for (int i = 1; i <= lastDigit; ++i)
for (int tri = 1; tri <= i; ++tri)
cout << "\t" << tri;

cout << endl;
}

// if odd digit - rect
else if (lastDigit / 2 != 0)
{
for (int i = 1; i <= lastDigit; i++)
{
for (int rect = 1; rect <= i; rect++)
cout << "\t" << rect;

cout << endl;
}
n = n/10;
}

cout << endl;

}while (lastDigit != 0);

n = n/10;
cout << endl;

return 0;


And, how should i code when keyed in the int, the compiler will extract the first digit (From left to right) and output it accordingly?

Any help would be appreciated!

Answer

Following is the complete code.

Step1: Take user input and check whether it's odd or even.

Step2: If it is odd then perform triangle else rectangle.

#include<iostream>
int main () {

int n;

cout<<"Enter number: ";
cin>>n;

if (n % 2 != 0)
{
    for(int i = 1; i <= n; i++)
    {
        cout<<endl;
        for(int j = 1; j <= n; j++)
        {
            cout<<j<<" ";
        }
    }
}
else
{
    for(int i = 1; i <= n; i++)
    {
        cout<<endl;
        for(int j = 1; j <= i; j++)
        {
            cout<<j<<" ";
        }
    }
}

return 0; 
}
Comments