Tuesday, September 5, 2017

How do I print patterns in c using for loop?

Hello Dear Visitor

If you want print patterns in C. There is no problem.
First of all devide the pattern in Graph form. It will help you to understand the Logic.
Please see image below. It is a example pattern of triangle.



From the graph view you can understand that the number of lines are 4. It means the loop should be executed 4 times only.
2nd thing, The main logic displays here that

Number of stars = current Number of line

means if line number is 2, stars are 2.
Wow, we found our logic.

In these types of programs, first or outer most loop is always for total number of lines.
Then, nested loop will have the printing logic.

void main()
{
int i,j;
for (i = 1; i <= 4; i++) /* Outer Loop for total Lines */
    {
      for (j = 1; j <= i; j++) /* inner loop for star printing */
         {
            printf("*"); /* Give space before * for more spaces in the pattern */
         }
        printf("\n"); /* Next line after printing stars */
    }
getch();
}

If you see inner loop, this loop will execute till the number of line (we have used i in comparison condition). Means, if first loop, i=1, inner loop will execute 1 time and print one start. in the same manner, if i=2, inner loop will execute twice and 2 starts will print.


I hope it will help.
Happy Coding.

Rudra Pratap Singh
Software Engineer

No comments:

Post a Comment

How to Get Organic Views on Your Channel/Content

 Hi Friends, This post will be very short and specific in the information.  If you are a content creator and want some help in getting organ...