Â
In this, we are going to see how to print the above pattern of pyramid/triangle of special character, using nested for loops in C++.
The code given below can be used for TURBO C++ Compiler:-
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int rows;
cout << "\nEnter the number of rows\n";
cin >> rows;
for (int i = 0; i <= rows - 1; i++)
{
//This loop is to print spaces in begining for the required pattern
for (int j = 1; j <= rows - i + 1; j++)
{
cout << " ";
}
//This loop is for the 1st half of the pyramid
for (int k = 0; k <= i; k++)
{
if (i % 2 == 0)
{
cout << "#";
}
else
{
cout << "#";
}
}
//This loop is for the 2nd half of the pyramid
for (int l = i - 1; l >= 0; l--)
{
if (i % 2 == 0)
{
cout << "#";
}
else
{
cout << "#";
}
}
cout << endl;
}
getch();
}
The code given below can be used for g++/gcc Compiler:-
#include<iostream>
using namespace std;
int main()
{
int rows;
cout << "\nEnter the number of rows\n";
cin >> rows;
for (int i = 0; i <= rows - 1; i++)
{
//This loop is to print spaces in begining for the required pattern
for (int j = 1; j <= rows - i + 1; j++)
{
cout << " ";
}
//This loop is for the 1st half of the pyramid
for (int k = 0; k <= i; k++)
{
if (i % 2 == 0)
{
cout << "#";
}
else
{
cout << "#";
}
}
//This loop is for the 2nd half of the pyramid
for (int l = i - 1; l >= 0; l--)
{
if (i % 2 == 0)
{
cout << "#";
}
else
{
cout << "#";
}
}
cout << endl;
}
return 0;
}
#ENJOY CODING
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP