Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

C: Printing A Hollow Square

This program will demonstrate how a hollow square can be printed with the help of the C progrmming language, using nested loops.


Let us start with the headers.
//WinterNurf Productions

#include<stdio.h>

#include<conio.h>

We will now start the main() function and declare two loop control variables for the inner and outer loops.
int main()
{
      //Delclare loop control variables
      inti = 0;

      intj = 0;

We will now declare and initialize a character variable with the ASCII value 219. This character is a block, and gives a better visual impact. Any character may be used instead of this.
      //Declare and initialize the character to be displayed

      charchBlock = 219;

Now, create the outer loop to iterate rows and print a newline charater inside it. This can also be done after the inner loop.
      //Create outer loop to iterate rows
      for(i = 0; i < 20; i++)
      {
            //Give a newline

            printf ("\n  ");

Now, create an inner loop to iterate columns.
            //Create an inner loop to iterate columns

            for(j = 0; j < 30; j++)

Since we are printing a hollow square, we will print our character only when the loop variables are at their initial or final values (because these will signify the sides of the square).
                  //If edge of square, print the character
                  if(i == 0 || i == 19 || j == 0 || j == 29)
                        printf ("%c", chBlock);
                  //If not, print a space character
                  else
                        printf (" ");

      }

We finally end the program.
      _getch();
      return 0;

}

Here is the full code.
//WinterNurf Productions

#include<stdio.h>
#include<conio.h>

int main()
{
      //Delclare loop control variables
      inti = 0;
      intj = 0;

      //Declare and initialize the character to be displayed
      charchBlock = 219;

      //Create outer loop to iterate rows
      for(i = 0; i < 20; i++)
      {
            //Give a newline
            printf ("\n  ");

            //Create an inner loop to iterate columns
            for(j = 0; j < 30; j++)
                  //If edge of square, print the character
                  if(i == 0 || i == 19 || j == 0 || j == 29)
                        printf ("%c", chBlock);
                  //If not, print a space character
                  else
                        printf (" ");
      }

      _getch();
      return 0;

}

This program has been written in Microsoft Visual Studio for Desktop. It may not work in older compilers. However, simple editing will make the code compatible.


This post first appeared on Code Walk, please read the originial post: here

Share the post

C: Printing A Hollow Square

×

Subscribe to Code Walk

Get updates delivered right to your inbox!

Thank you for your subscription

×