C++: Learning the Basics – Making Patterns

Situation: Make the following patterns –

1. Patterns with asterisks #annotated
Screen Shot 2017-08-13 at 5.45.19 PM.png

#include <iostream.h>
#include <conio.h>
void main()

{

   clrscr();
   int rows=5, counter, sym; #you can ask the user for number of rows, but I have just stated that rows=5 for simplicity

   for (counter=1; counter<=rows; counter++)
   {
        for (sym=1; sym<=counter; sym++) #sym stands for symbol. sym essentially acts as a counter for the number of asterisks.
        {
             cout<<" * ";
        }
   cout<<"\n"; #indicates to go to the next line.

   }
   getch();

}

Code without annotations:

#include <iostream.h>
#include <conio.h>
void main()

{

   clrscr();
   int rows=5, counter, sym; 

   for (counter=1; counter<=rows; counter++)
   {
         for (sym=1; sym<=counter; sym++) 
         {
                   cout<<" * ";
         }

         cout<<"\n"; 
   }
   getch();

}

2. Screen Shot 2017-08-13 at 5.45.19 PM.png

To start with a row of five, you only have to make the following changes to this part of the previous code:

for (counter=1; counter<=rows; counter++)

This changes to:

for (counter=rows; counter>=1; counter--)

Thus, the final code is:

#include <iostream.h>
#include <conio.h>
void main()

{

   clrscr();
   int rows=5, counter, sym; 

   for (counter=rows; counter>=rows; counter--)
   {
         for (sym=1; sym<=counter; sym++) 
         {
               cout<<" * ";
         }

         cout<<"\n"; 
   }
   getch();

}

 

Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s