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
#include <stdio.h>
int main()
{
int n = 5, rows, columns;
for (rows = 1; rows <= n; rows++) {
for (columns = n; columns > rows; columns--) {
printf(" ");
}
printf("*");
for (columns = 1; columns < (rows - 1) * 2;
columns++) {
printf(" ");
}
if (rows == 1) {
printf("\n");
}
else {
printf("*\n");
}
}
for (rows = n - 1; rows >= 1; rows--) {
for (columns = n; columns > rows; columns--) {
printf(" ");
}
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
#include <stdio.h>
int main()
{
int n = 5, rows = 1, columns;
while (rows <= n) {
columns = n;
while (columns > rows) {
printf(" ");
columns--;
}
printf("*");
columns = 1;
while (columns < (rows - 1) * 2) {
printf(" ");
columns++;
}
if (rows == 1) {
printf("\n");
}
else {
printf("*\n");
}
rows++;
}
rows = n - 1;
while (rows >= 1) {
columns = n;
while (columns > rows) {
printf(" ");
columns--;
}
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!
Last Updated :
27 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...