Â
In this, we are going to see how to print the above pattern of Diamond of palindrome numbers, 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 a = 1, num, space;
cout << "Enter the number of Rows \n";
cin >> num;
space = num - 1;
while (space != 0)
{
cout << " ";
space--;
}
cout << a << "\n";
space = num - 2;
for (int i = 1; i < num; i++)
{
a = 1;
for (int k = 1; k <= space; k++)
{
cout << " ";
}
for (int j = 0; j <= i * 2; j++)
{
if (j < i)
{
cout << a;
a++;
}
else
{
cout << a;
a--;
}
}
cout << "\n";
space--;
}
for (int i = num - 1; i >= 1; i--)
{
space = num - i;
a = 1;
for (int k = 1; k <= space; k++)
{
cout << " ";
}
for (int j = 1; j <= i * 2 - 1; j++)
{
if (j < i)
{
cout << a;
a++;
}
else
{
cout << a;
a--;
}
}
cout << "\n";
space--;
}
getch();
}
The code given below can be used for g++/gcc Compiler:-
// pattern 18
#include<iostream>
using namespace std;
int main()
{
int a = 1, num, space;
cout << "Enter the number of Rows \n";
cin >> num;
space = num - 1;
while (space != 0)
{
cout << " ";
space--;
}
cout << a << "\n";
space = num - 2;
for (int i = 1; i < num; i++)
{
a = 1;
for (int k = 1; k <= space; k++)
{
cout << " ";
}
for (int j = 0; j <= i * 2; j++)
{
if (j < i)
{
cout << a;
a++;
}
else
{
cout << a;
a--;
}
}
cout << "\n";
space--;
}
for (int i = num - 1; i >= 1; i--)
{
space = num - i;
a = 1;
for (int k = 1; k <= space; k++)
{
cout << " ";
}
for (int j = 1; j <= i * 2 - 1; j++)
{
if (j < i)
{
cout << a;
a++;
}
else
{
cout << a;
a--;
}
}
cout << "\n";
space--;
}
return 0;
}
#ENJOY CODING
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP