## DEV Community

MrSoUndso

Posted on

Hi everybody!

This is the first post of my new series: "Adventures in learning C".
First of all, please let my introduce myself: I'm Mr SoUndso and I currently study "Technische Informatik" (probably best translated as "technical computer science") in Germany. One of my lectures teaches me how to program in C. To pass the class, I'll have to complete different exercises. This series will be a write up on the different challenges I faced, and the ways I used to overcome them.

#### Write a program that prints a rectangle to the console

This sounds like a simple task, and it is. But i made a mistake along the way, that made my attempt at the next test way harder.

I started out with three different for loops, one for the top row, one for the side walls and one for the bottom.

``` for (int i = 0; i < y; i++) { //print first row } printf("/n"); for (int i = 1; i < x; i++) { //print the sides } for (int i = 0; i < y; i++) { //print last row } ```

The top and bottom rows were simple: I just added a ` printf(%c,c); ` into the loop and was set.

The sides were harder nuts to crack. I could not simply add a ` printf("%c %c \n",c, c);` to the loop, as a requirement of the test was to make a the hight and width configurable.
So I added a second for loop into the mix.
My second loop now looked like this:
``` for (int i = 1; i < x; i++) { for (int b = 0; b < y; b++) { printf("%c", c); } printf("\n"); } ```

This would give me a completely filled rectangle. I realized I wasn't far from my goal, I only needed to fill the center with spaces instead of chars.

To do this, I added a if to check if the second iterator (b) is equal to 0 or y.
This resulted in a strange output:
``` xxxxx x x x x x xxxxx ```

I realized that b could never be equal to y, as the for loop would stop if
` b == y `.
So I changed the check from ` b == y ` to `b == y - 1` and voilà: My code worked!

But wait: I told you earlier that I made a mistake making my next attempt way harder. Using 3 for loops instead of 2 nested ones made me scratch my head a lot when working on the next test. But this is a story for another post.

Have a nice day.