To print the hollow diamond pattern in C, we will use the following 2 approaches:
- for Loop
- while Loop
Input:
n = 5
Output:
* * * * * * * * * * * * * * * *
Approach 1: Using for loop
Example:
C
// C Program To Print Hollow Diamond // Pattern using for loop #include <stdio.h> int main()
{ int n = 5, rows, columns;
// for loop is used to identify
// the number of rows and
// it is used to print upper triangle
for (rows = 1; rows <= n; rows++) {
// used for printing the spaces
for (columns = n; columns > rows; columns--) {
printf ( " " );
}
// print star
printf ( "*" );
// again print the spaces
for (columns = 1; columns < (rows - 1) * 2;
columns++) {
printf ( " " );
}
if (rows == 1) {
printf ( "\n" );
}
else {
printf ( "*\n" );
}
}
// for loop is used to identify
// the number of rows and
// it is used to print lower triangle
for (rows = n - 1; rows >= 1; rows--) {
// used for printing the spaces
for (columns = n; columns > rows; columns--) {
printf ( " " );
}
// print star
printf ( "*" );
for (columns = 1; columns < (rows - 1) * 2;
columns++) {
printf ( " " );
}
if (rows == 1) {
printf ( "\n" );
}
else {
printf ( "*\n" );
}
}
return 0;
} |
Output
* * * * * * * * * * * * * * * *
Method : Using while loop
Example:
C
// C Program To Print Hollow Diamond // Pattern using while loop #include <stdio.h> int main()
{ int n = 5, rows = 1, columns;
// while loop is used to identify
// the number of rows and
// it is used to print upper triangle
while (rows <= n) {
columns = n;
// used for printing the spaces
while (columns > rows) {
printf ( " " );
columns--;
}
// print star
printf ( "*" );
columns = 1;
while (columns < (rows - 1) * 2) {
printf ( " " );
columns++;
}
if (rows == 1) {
printf ( "\n" );
}
else {
printf ( "*\n" );
}
rows++;
}
// while loop is used to identify
// the number of rows and
// it is used to print lower triangle
rows = n - 1;
while (rows >= 1) {
columns = n;
// used for printing the spaces
while (columns > rows) {
printf ( " " );
columns--;
}
// print star
printf ( "*" );
columns = 1;
while (columns < (rows - 1) * 2) {
printf ( " " );
columns++;
}
if (rows == 1) {
printf ( "\n" );
}
else {
printf ( "*\n" );
}
rows--;
}
return 0;
} |
Output
* * * * * * * * * * * * * * * *
Time complexity: O(n2) for given input n
Auxiliary space: O(1) as it is using constant space for variables