Wednesday, March 5, 2014

Printing Pattern 10

      1
    121
  12321
1234321
------------- for n values

The above pattern can be divided into two parts

        1             
       12             1
     123      +     21
   1234             321

outer loop i should run n times.
inner loop comprises of 2 loop variable for printing 1st and 2nd half of the pattern.
Number of spaces printed depends on number of values in that line
Maximum value in a line is the line number.



Outer loop
for(i=1;i<=n;i++)
{ ... }



Inner loop for spaces
Number of spaces = max lines in pattern - Values printed in that line

for(j=1;j<=n-i;j++)
printf(" ");

here 'n' number of lines in pattern which user enters and also the maximum value that appears in the pattern.

'i' is the line number of that line or number of values printed in that line.



Inner loop for 1st pattern
starts with 1 and goes till line number value for that line or max value of that line.

for(k=1;k<=i;k++)
printf("%d",k);






Inner loop for 2nd pattern

start with maximum value of that line -1 and decrements down to 1.

for(t=i-1;t>=1;t--)
printf("%d",t);




Program

#include<stdio.h>

int main()
{
int i,j,k,t,n;

//ask user to enter number of lines
printf("\nEnter the number of lines in the pattern:");
scanf("%d",&n);

//outer loop
for(i=1;i<=n;i++)
{

//loop for spaces 
        for(j=1;j<=n-i;j++)
              printf(" ");

//loop for 1st part of pattern
        for(k=1;k<=i;k++)
              printf("%d",k);

//loop for 2nd part of pattern
        for(t=i-1;t>=1;t--)
              printf("%d",l);

//move to next line
         printf("\n");
}

return 0;
}






No comments:

Post a Comment