Thursday, January 9, 2014

Printing Pattern-1( Right Angle Triangle 1)

Printing pattern involve using several number of loop. Very basic pattern require two nested for loops.
The outer loop iterates to the number of lines in the pattern.
The inner loop controls the printing of pattern occurring in single line.

Patterns become simple if we relate them to loop number
*
**
***
****
In above pattern,
Line 1 has 1 *
Line 2 has two *
And similarly the pattern remains the same.

Looking at above pattern i can also say
  • It prints 4 lines, so outer loop should count to value of 4.
  • Inner loop is responsible for printing *.
  • Inner loop is dependent on outer loop in a way. 
  • If Line no. is 1 (line no. depends on outer loop) then inner loop should loop once and print * once
  • If Line no. is 2 then inner loop should run twice print ** and so on.


Setting up two loops

need i to print 4 lines and line number 1 to 4
for(i=1;i<=4;i++)

need j to be less than or equal to i's current value i.e if i=2 then j should be 1 and 2 , first printing * (for j=1) and * (for j=2) (total two times) for line no 2
for(j=1; j<=i;j++)
print("*");

after everything is done for that line i.e go to the next line - use \n newline
printf("\n");

 #include<stdio.h>
int main()
{
int i,j;

for(i=1;i<=4;i++)
   {
             for(j=1;j<=i;j++)
            {
                    printf("*");
             }
     printf("\n");
   }
return 0;
}

Try Printing
1
12
123
1234

This is very much similar the * pattern that was discussed
Only print value of j instead of printing *.

No comments:

Post a Comment