I'm doing the exercises before the programming exam and I can't do this one:
"Write a program that receives a natural number and approximately paints on the screen a square figure using a given drawing pattern. For example, if the number 3 is read, the square that will be drawn is the following:
[ "
At the moment I have this:
int patron(int n);
int n;
int main()
{
printf("Introduce el numero natural deseado:\n");
scanf("%d",&n);
patron(n);
}
int patron(int n)
{
int i, j;
for(i=1; i<=n; i++)
{
for (j=1; j<=n; j++)
{
printf("+---");
}
printf("+\n");
}
printf("\n");
return 0;
}
Which returns this:
How do I make squares with exclamations? Adding line breaks messes everything up.
Thanks in advance.
With this exercise, you will paint the drawing line by line. In this case, the odd lines will always be (+---) and the even lines will be (!). Control it with the counter of the first FOR, depending on whether it is odd or even, you paint one thing or another.
I would do it this way, I would modify:
By
So that it is something like this:
In this example, it
n
is equal to 3.Thanks everyone for the input, I've fixed the problem, here's the final code:
The added was this area (the rest of the code was not modified, it was simply added under the nested for):
I leave you an alternative
I show you an alternative way, which lets you choose the internal HEIGHT and WIDTH of each cell.
Also, instead of performing multiple
for
nests, we precompute the lines to display, so instead ofx * y
iterating, we perform only 3: precompute the closing lines , precompute the inner lines , and a final loop to display them.At the
for
end, we check if we are on a line before the first crossing line ; if we already passed it, we use the modulus (remainder) of the division to know if we have to show an internal line of the cell, or a crossing line .As a last point, compile from C89 onwards.