Home > C++ > A simple square pattern in C++

A simple square pattern in C++

Here’s a small C++ program which outputs a square pattern according to the size entered. Code is given below :


/*
* sqpattern.cpp
*
* Copyright 2010 Ershad K ershad92@gmail.com
* Licensed under GPL Version 3
*
* To compile - g++ -o sqpattern sqpattern.cpp
* To execute - ./sqpattern
*/

#include <iostream>
using namespace std;

int main()
{
  int size;
  cout << "Enter size: ";
  cin >> size;

  int count = 1;
  cout << " ";
  while (count++ < size) cout << " _";

  for (int i = 1; i < size; i++)
    {
      int numOfCharsPerLine = 0;
      cout << "\n";
      for (int j = 0; j < i; j++)
        {
          cout << " |";
          numOfCharsPerLine += 2;
        }

      cout << "_";
      numOfCharsPerLine += 1;

      int k = 1;
      while (k++ < (size*2) - numOfCharsPerLine )
      cout << " ";
      cout << "|";
    }

  count = 1;
  cout << "\n ";
  while (count++ <= (size)-1 ) cout << "|_";

  cout << "|\n";

return 0;
}

Output:

The programs draws  squares of any size entered. The code needs improvement, please feel free to give suggestions. Click here for ‘experiments’ git repo. Thank you 🙂

Advertisements
Categories: C++ Tags: , ,
  1. July 29, 2010 at 1:49 am

    Cool !! 🙂

  2. Eason Zhang
    July 29, 2010 at 11:37 am

    very cool~~

    • July 29, 2010 at 11:45 am

      @Hrishiettan, @Eason_Zhang, Thank you 🙂

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: