Subscribe

Enter your email address:

Categories

 

May 2012
M T W T F S S
« Dec    
 123456
78910111213
14151617181920
21222324252627
28293031  

Archives

Disclaimer

© 2009 Zero Intellect. All rights reserved. The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway. This material is not sponsored or endorsed by any of the vendors mentioned in this website and their Logos are trademarks of their own and their affiliates.

C++ printing out a specific pattern

 

Sometimes we come across elementary C++ programming tasks but which require you to tax your brain because of the logic involved

 

I came across a question which asked the user to write a c++ program to print the pattern above for any value of N (where N are the number of rows)

1234554321

1234**4321

123****321

12******21

1********1

 

The solution to the problem can be tackled in many ways. I would like to demonstrate one method and logic to get the desired output

Firstly, the sequence can be broken down as two separate problems as per the figure below

 

 

Various types of loops can be used but the central idea is the row is incremented from 1 to N, column 1 is incremented from 1 to N and column 2 is decremented from N to 1

 

I quickly wrote the program below using the logic above with the help of for loops

 

# include <iostream.h>

# include <conio.h>

 

void main()

{

   clrscr();

 

   int max=5;

 

   for(int row=1;row<=max;row++)

   {

         for(int column1=1;column1<=max;column1++)

         {      

               if(column1<=max-row+1)

               cout<<column1;

               else

               cout<<”*”;

         }

 

         int drawstars=row-1;

 

         for(int column2=max;column2>=1;column2–)

         {

               if(drawstars>0)

               cout<<”*”;

               else

               cout<<column2;

 

               drawstars–;

         }

         cout<<”\n”;

   }

   getch();

}

 

 The program is self explanatory and a screenshot of the output of the sample above is as under

 

 

 

Many similar questions are asked where different outputs are desired, but the central idea to solving the question is figuring out a pattern that is being followed

 

Happy Coding 

2 comments to C++ printing out a specific pattern