About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Tuesday, September 3, 2013

C Program to Print the Double Pyramid Pattern

Problem Statement : Program to Print the Double Pyramid Pattern


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

void main()
{
int i,j,k;
int blank=0;
int lines = 6;
char symbol='A';
int temp ;
int diff[7]= {0,1,3,5,7,9,11};
clrscr();
k=0;
//Step 0

    for(i=lines;i>=0;i--)
    {
       printf("\n");
       symbol = 'A';

       for(j=i;j>=0;j--)    //step 1
            printf("%c ",symbol++);

       blank = diff[k++];   //step 2

       for(j=0;j<blank;j++)
            printf(" ");    //step 3


       symbol = 'F' - (blank/2);

       if (blank== 0)
           temp = i-1;
       else
           temp = i;

       for(j=0;j<=temp;j++)  //step 4
           printf("%c ",symbol--);

    }
getch();
}

Output :
A B C D E F G F E D C B A
A B C D E F   F E D C B A
A B C D E       E D C B A
A B C D           D C B A
A B C               C B A
A B                   B A
A                       A

Explain Me ?


As the above coding is very difficult to understand , so I have divided Program in 5 Steps.Easy steps are as follow ,
Step 0 :
Program has 7 lines i.e (0 to 6)
int i,j,k;
Variables : i is used to trace the Current Line
Variables : j is used for Subscript variable for Different Loops
Variables : k is used to trace the diff array , for each new value of i (new line) k is incremented
int diff[7]= {0,1,3,5,7,9,11};
Variable : diff[7] is used for Storing the number of blanks
eg.
A B C D E F   F E D C B A      // 2nd Line
Here G is Missing so blank = 1;
Step 1 :
A B C D E F G
A B C D E F
A B C D E
A B C D
A B C
A B
A
Will be Printed
Step 2 : Initialize Blank i.e for first line blank = 0 , for second line it will be 1 and so on 
A B C D E F G
A B C D E F
A B C D E
A B C D
A B C
A B
A
Will be Printed, Blanks are denoted by     
Step 3 :
symbol = 'F' - (blank/2);
Here symbol variable is initialized , Consider first Line , We are printing Letter ‘F’ after ‘G’ so initialize it .
for 3rd line
>> blank = 3 , so
>> symbol = ‘F’ – 1 = ‘E’
step 4 :
for(j=0;j<=temp;j++)
   printf("%c ",symbol--);
Here print remaining characters , until we print ‘A’

No comments: