C++ Program To Print The Diamond Shape
Given a number n, write a program to print a diamond shape with 2n-1 rows.
Examples :
Input: 5
Output:
C++
#include <bits/stdc++.h>
using namespace std;
void printDiamond( int n)
{
int space = n - 1;
for ( int i = 0; i < n; i++)
{
for ( int j = 0;j < space; j++)
cout << " " ;
for ( int j = 0; j <= i; j++)
cout << "* " ;
cout << endl;
space--;
}
space = 0;
for ( int i = n-1; i > 0; i--)
{
for ( int j = 0; j < space; j++)
cout << " " ;
for ( int j = 0;j < i;j++)
cout << " *" ;
cout << endl;
space++;
}
}
int main()
{
printDiamond(5);
return 0;
}
|
Output
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
Time Complexity: O(n*n) since we are traversing rows and columns of a grid for printing spaces ‘ ‘ and star ‘*’.
Auxiliary Space: O(1), No extra space used.
Last Updated :
25 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...