Have you wondered how to crack problems like generating patterns from C code or Java code ?? Here, I am presenting a methodology to crack simple pattern problems.
Write an algorithm to generate following pattern:
*
* *
* *
* *
*
for n=any odd number say 5.
To understand the behavior of pattern put them inside grid a follows:
Now we will check what trend above pattern is following. On close observation we find out that
upper left edge of pattern follows :
print * if i<=2 and j<=2 and i+j=2
upper right edge of pattern follows :
print * if i<=2 and j>=2 and j-i=2
lower left edge of pattern follows :
print * if i>=2 and j<=2 and i-j=2
upper left edge of pattern follows :
print * if i>=2 and j>=2 and i+j=6
Now following code-snippets can be written to generate above pattern:
for(j=0;j<n;j++)
{
for(i=0;i<n;i++)
{
if((i<=n/2 && j<=n/2 && i+j==n/2)||(i<=n/2 && j>=n/2 && j-i==n/2)||(i>=n/2 && j<=n/2 && i-j==n/2)||(i>=n/2&& j>=n/2 && i+j==((n-1)/2)*3))
{
printf("*");
}
else
printf(" ");
}
printf("\n");
}
Hope you have understood essence of pattern generation. As a assignment, you can generate following pattern :
Write an algorithm to generate following pattern:
*
* *
* *
* *
*
for n=any odd number say 5.
To understand the behavior of pattern put them inside grid a follows:
| 0 | 1 | 2 | 3 | 4 |
| 0 | * | ||||
| 1 | * | * | |||
| 2 | * | * | |||
| 3 | * | * | |||
| 4 | * |
Now we will check what trend above pattern is following. On close observation we find out that
upper left edge of pattern follows :
print * if i<=2 and j<=2 and i+j=2
upper right edge of pattern follows :
print * if i<=2 and j>=2 and j-i=2
lower left edge of pattern follows :
print * if i>=2 and j<=2 and i-j=2
upper left edge of pattern follows :
print * if i>=2 and j>=2 and i+j=6
Now following code-snippets can be written to generate above pattern:
for(j=0;j<n;j++)
{
for(i=0;i<n;i++)
{
if((i<=n/2 && j<=n/2 && i+j==n/2)||(i<=n/2 && j>=n/2 && j-i==n/2)||(i>=n/2 && j<=n/2 && i-j==n/2)||(i>=n/2&& j>=n/2 && i+j==((n-1)/2)*3))
{
printf("*");
}
else
printf(" ");
}
printf("\n");
}
Hope you have understood essence of pattern generation. As a assignment, you can generate following pattern :
| 0 | * | ||||
| 1 | * | * | * | ||
| 2 | * | * | * | * | * |





0 comments