Introdução
Neste laboratório, aprenderemos como imprimir uma estrutura de Pirâmide Invertida pela Metade usando Números, na linguagem de programação C++. Usaremos as estruturas de loop aninhadas para iterar e imprimir o padrão.
Neste laboratório, aprenderemos como imprimir uma estrutura de Pirâmide Invertida pela Metade usando Números, na linguagem de programação C++. Usaremos as estruturas de loop aninhadas para iterar e imprimir o padrão.
Vá para o terminal e crie um novo arquivo chamado main.cpp no diretório ~/project usando o seguinte comando:
touch ~/project/main.cpp
Após criar o arquivo, abra-o usando um editor de texto.
Adicione o seguinte código ao arquivo main.cpp.
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " ===== Program to print a Reverse Half Pyramid using Numbers ===== \n\n";
//i to iterate the outer loop and j for the inner loop
int i, j, rows;
//to denote the range of numbers in each row
int last;
cout << "Enter the number of rows in the pyramid: ";
cin >> rows;
cout << "\n\nThe required Reverse Pyramid pattern containing " << rows << " rows is:\n\n";
//outer loop is used to move to a particular row
for (i = 1; i <= rows; i++)
{
//to display that the outer loop maintains the row number
cout << "Row ## " << i << " contains numbers from 1 to " << (rows - i + 1) << " : ";
last = rows -i + 1;
//inner loop is used to decide the number of * in a particular row
for (j = 1; j<= last; j++)
{
cout << j << " ";
}
cout << endl;
}
cout << "\n\n";
return 0;
}
Compile e execute o código usando os seguintes comandos:
g++ main.cpp -o main
./main
Você verá a seguinte saída:
Welcome to LabEx :-)
===== Program to print a Reverse Half Pyramid using Numbers =====
Enter the number of rows in the pyramid: 6
The required Reverse Pyramid pattern containing 6 rows is:
Row ## 1 contains numbers from 1 to 6 : 1 2 3 4 5 6
Row ## 2 contains numbers from 1 to 5 : 1 2 3 4 5
Row ## 3 contains numbers from 1 to 4 : 1 2 3 4
Row ## 4 contains numbers from 1 to 3 : 1 2 3
Row ## 5 contains numbers from 1 to 2 : 1 2
Row ## 6 contains numbers from 1 to 1 : 1
Neste laboratório, aprendemos como imprimir uma estrutura de pirâmide invertida com números usando laços aninhados na linguagem de programação C++.