C++ gurus and learners, we program ourselves :P all work is CC licensed

Saturday, November 23

Hollow Square & Hollow diamond & Hollow Triangle

Hollow Square & Hollow diamond & Hollow Triangle

It's basically a request from a student as we go further in loops and functions we need to know more tricks and practise more for these things which eventually leads to good programming;
Basic concept to understand;
  1. Notice if any line of the shape is going to match original filled shape; i.e. in square the first line and last line are filled!
  2. Make sure you know the ration of spaces for hollow part to the number of characters in the corresponding filled space i.e. if your square is of the size of 5x5 so it is going to be 5 characters in a single line; but in hollow shape you are going to print only 2 characters ; the first one and last one no matter how much long line is this; but here in 5 character line the total spaces would be countable as spaces=one side length - 2;
Prepare for the basic shapes looping that will be joined together to make final shape i.e. to make diamond you place 4 triangles together if you ever made it:

Hence by mixing these points you can make logic of this king of shapes.

Basic Hollow looping;
In this kind of looping you have to make sure that ration of lines is safely described to make appropriate loop
Square concept:
  1. int main()
  2. {
  3.         int size;            //suppose it is 5
  4.         cin>>size;
  5.         for (int i = 0 ; i < size ; i++ ) //runs 5 times
  6.          {
  7.                  cout  <<  "*" ;          //first char
  8.                  for (int j=2;j<size;j++) //runs 5-2 times
  9.                  {
  10.                      cout<<" ";
  11.                  }
  12.                  cout  <<  "*" ;          //last char
  13.           }
  14.    return 0;
  15. }
Now here in line 8 you can see that formula which subtracts number of characters from hollow line to make it even to the rest of shape, it could be 5 - 3  or maybe  5-4  required for the program hence the distribution of spaces and loops as well; depending on the shape.
And for first and last line here is simple method:
  1.  if ( line 1 || last line ) //mean i==1 or i==size-1 according to loop iteration
  2.  {
  3.          for ( int a=0;a<size;a++ )
  4.          {
  5.              cout<< "*" ;
  6.          }
  7.       cout << endl ; continue ;
  8.  }
Put it in main loop Before the space loop so that if first line is being print it would print it and skip the space printing for first and last line.
i guess it is enough for the basic concept and you will be able to make assignment ;; I'll give complete codes after exams;; thanks for reading and for feedback or any questions:
Join the group  on facebook for constant news about new posts..

3 comments :