Friday, September 9, 2016

Pattern Program Concept

Let us suppose we have to draw a pattern like this-

***1***
**121**
*12321*
1234321


Whatever be the pattern the method remains same.
Let us take an even complex pattern -
1
  121
 12321
1234321
 12321
  121
   1




All patterns can be grouped into number of triangles as shown above.


For

***1***
**121**
*12321*
1234321    pattern we have 4 sub triangles

1.

***
**
*

2.

      1
    12
  123
1234


3.


1
21
321

4.

***
**
*


We will write a master for loop for 4 times i.e equal to the number of rows we have to print and insite that we will run for loops 4 times for each triangle.

If the pyramid becomes inverted after half then we will have to have 2 mater for loops.



#include<stdio.h>

int main()
{

for (int i = 1; i <= 4; i++)  //for 4 horizontal lines
{

        for (int j = 4; j-i > 0; j--)   //as we go down we have to print one star lesser
printf("*");

       for (int k = 1; k <= i; k++)  //as we go down we have to print one more digit in increasing order
printf("%d", k);

for (int m = i; m > 1; m--) /*except for first line we have to print one digit less than the line number */'
printf("%d", m-1);

for (int l = 4; l - i >= 1; l--)
printf("*");

printf("\n");

}

return 0;

}



Fibonacci Series

It is a series of numbers such that the first number is 0, second is 1 and from thereon every number is a sum of previous two numbers.
0 1 1 2 3 5.....

The concept can be extended for negative numbers also  -8, 5, -3, 2, -1, 1, 0, 1, 1, 2, 3, 5, 8,
For the sake of simplicity we re considering non negative sequence only.



#include<stdio.h>

int main()
{
int n;

printf("enter the number of fibonacci numbers you want to enter \n \n");
scanf_s("%d", &n);

if (n <= 0)
printf("not valid or negative sequence \n");

else if (n == 1)
printf("0 \n");
else if(n==2)
printf("0 1\n");

else
{
int a2 = 0;
   int a1 = 1;
int newnum;
printf("0 \n1\n");
for (int i = 2; i < n; i++)
{
newnum = a2 + a1;
printf("%d \n", newnum);
a2 = a1;
a1 = newnum;
}


}

return 0;

}


O/P-