Hi everybody!
In the last post I showed you the the way I approached the "Print a rectangle test".
The next test I'll have to tackle is:
Print a crossed square to the console
So I started with the nearly the same code I used in my last project, but I quickly realized that the three for loops I used made everything way harder than it should be.
So I switched over to two nested for loops:
for (int i = 0; i < x; i++) {
for(int b = 0; b < x; b++) {
printf(%c,c);
}
printf("\n");
}
This resulted in a completely filled rectangle, just as I intended.
So I once again added a if check to make sure only the parts I wanted to be char where chars.
I started with the walls: the top line should be filled if i == 0
, and the bottom if i = x - 1
. The walls worked after a similar principle, just replace the i
with a b
. It's also important to add a else
statement to print a space if none of the conditions on top are met.
The cross part was harder than I initially thought. While the line going from the top left corner to the bottom right one was simple as it simply follows the i == b
condition, the one going the other way made me scratch my head a lot more.
The thing I came up with was this formula: (i + b) == x - 1
This condition is meet for every point on the line between the bottom left corner and the top right one.
In the end my complete code looked like this:
for (int i = 0; i < x; i++) {
for(int b = 0; b < x; b++) {
if(i == 0 || i == x -1 || b == 0 || b == x - 1 || i == b || i + b == x - 1) {
printf("%c",c );
} else {
printf(" ");
}
}
printf("\n");
}
If you would try the same thing with 3 individual loops instead of 2 nested ones, you would run into really really unfunny issues with these simple if checks. For example, I had issues with the lines not meeting in the middle or having spaces everywhere but not where I wanted to have them.
Have a nice day!
P.S: I'm sorry for the strange formating. If you know how to fix it please leave me a comment!
P.P.S: Thanks to
for telling me how to fix my issues!
Top comments (2)
Use Markdown to format your code like this:
Thanks, I'll try this next time!