C Program To Print Diamond Pattern
Last Updated :
04 Jul, 2022
Here, we will see how to print a full diamond shape pyramid using the C program. Below are the examples:
Input: 6
Output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
Input: 8
Output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
Approach:
1. The first step is to print the upper part of the diamond using three nested loops.
- The first loop handles the number of rows.
- The Second loop is for the initial space before the stars.
- The third loop print the stars.
2. Now Repeat again steps 1, 2, and 3 in reverse order to print the lower part of the diamond.
Below is the C program to print full diamond shape pyramid:
C
#include <stdio.h>
void printDiamond( int n)
{
int space = n - 1;
for ( int i = 0; i < n; i++)
{
for ( int j = 0; j < space; j++)
printf ( " " );
for ( int j = 0; j <= i; j++)
printf ( "* " );
printf ( "\n" );
space--;
}
space = 0;
for ( int i = n; i > 0; i--)
{
for ( int j = 0; j < space; j++)
printf ( " " );
for ( int j = 0; j < i; j++)
printf ( "* " );
printf ( "\n" );
space++;
}
}
int main()
{
printDiamond(8);
return 0;
}
|
Output
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
Time Complexity: O(n*n) since here we are traversing the rows and columns of a grid for printing spaces ‘ ‘ and star ‘*’.
Auxiliary Space: O(1), No extra Space is used.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...