I need to put a star frame around this diamond. The output should be like this. This is an example for input ‘9’.
*
*.*
*. .*
*. . .*
*. . . .*
*. . . . .*
*. . . .*
*. . .*
*. .*
*.*
*
Here is the code without the frame:
int main()
{
int d = 0;
scanf("%d", &d);
int d2 = (d / 2) + 1;
for(int i = 1; i <= d2;i++)
{
for(int c = 1; c<=d2-i;c++)
{
printf(" ");
}
for(int j = 0;j < i;j++)
{
printf(".");
printf(" ");
}
printf("\n");
}
for(int i = d2-1; i >= 1;i--)
{
for(int c = 1; c<=d2-i;c++)
{
printf(" ");
}
for(int j = i;j > 0;j--)
{
printf(".");
printf(" ");
}
printf("\n");
}
}
This is the output for the code without the frame:
.
. .
. . .
. . . .
. . . . .
. . . .
. . .
. .
.
And this is the code I wrote for the frame put it isn’t working properly. The spaces aren’t correctly printed and the dots aren’t correct as well. I couldn’t fix it. Any help will be appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int d = 0;
scanf("%d", &d);
int d2 = (d / 2) + 1;
int s = 0;
// Printing the upper half of the diamond and the frame
for(int i = 1; i <= d2; i++)
{
for(int c = 1; c <= d2 - i; c++)
{
printf(" ");
}
printf("*");
if (i > 1)
{
for (int j = 0; j < i - 1; j++)
{
printf(".");
printf(" ");
}
printf("*");
}
printf("\n");
}
// Printing the lower half of the diamond and the frame
for(int i = d2 - 1; i >= 1; i--)
{
for(int c = 1; c <= d2 - i; c++)
{
printf(" ");
}
printf("*");
if (i > 1)
{
for (int j = i - 2; j >= 0; j--)
{
printf(".");
printf(" ");
}
printf("*");
}
printf("\n");
}
}
The output for the code above is like this:
*
*. *
*. . *
*. . . *
*. . . . *
*. . . *
*. . *
*. *
*
>Solution :
In your inner for loops, you unconditionally print a space after each .. You shouldn’t do that in case it’s the last . on the line. You could fix it by adding a check. It also helps with readability if you make the upper and lower loop use the same conditions.
It could look like this:
for (int j = i - 2; j >= 0; j--) {
putchar('.');
if (j) putchar(' '); // don't print a space unless j>0
}
To make space for the frame, you could also add 2 to the inputted n.
if(scanf("%d", &d) != 1) exit(1);
d += 2;