Select Page

Merge two triangle patterns in C

merge two triangle patterns in C- in this tutorial we will cover techniques to merging the right triangle and mirror right triangle side by side. Triangle Pattern is made using Star Symbol(*).

The following Pattern program is written in three unique manners:

  • For Loop
  •  While Loop
  •  Do-While Loop

 

Merge two triangle patterns in C- we have to specify the certain number of rows and columns. According to above program number of rows specified 5 and the number of Columns specified  7.

The Star Symbol (any other symbol can take) is picked here for demonstration.

This issue can also be solved by observing that the two triangle is printed side by side.

1.  using For Loop

 Algorithm of merging two triangle pattern

Input: Let, three variables say r,c,n,m. The value of n and m will be given by the user.

step 1: Input values for n and m where n is Row size and m is column size

step 2: r=1 and outer loop will be performed as long as r<=n

step 3: c=1

step 4: inner loop will be performed as long as  c<=m

step 4.1: check if (c<=r||c>=m+1-r) is true then 

                               print symbol star ( “*”)

else

print  “blank space”

step 5: j=j+1

step 6: End inner loop

step 7: next line start

step 8: i= i+1

step 9:  End outer loop

Source Code

int main()
{
    int r,c,n,m;
    printf("\n\tEnter row no:");
    scanf("%d",&n);
    printf("\n\tEnter column no:");
    scanf("%d",&m);
    printf("\n\t");
    for(r=1; r<=n; r++)
    {
      for(c=1; c<=m; c++)
        {
           if(c<=r||c>=m+1-r)
           {
               printf("*");
           }
           else
               printf(" ");
        }
        printf("\n");
        printf("\t");
      }
 return 0;
}

2. Source code using while Loop

 

int main()
{
    int r,c,n,m;
    printf("\n\tEnter no:");
    scanf("%d",&n);
    printf("\n\tEnter no:");
    scanf("%d",&m);
    printf("\t");
    r=1;
    while(r<=n)
    {
       c=1;
       while(c<=m)
        {
           if(c<=r||c>=m+1-r)
           {
              printf("*");
           }
       else
          {
           printf(" ");
          }
         c++;
        }
        r++;
        printf("\n");
        printf("\t");
    }
}

3. Source code using do..while Loop

 

int main()
{
    int r,c,n,m;
    printf("\n\tEnter no:");
    scanf("%d",&n);
     printf("\n\tEnter no:");
    scanf("%d",&m);
    printf("\t");
    r=1;
    do
    {
      c=1;
      do
      {
         if(c<=r||c>=m+1-r)
           {
              printf("*");
           }
       else
          {
              printf(" ");
          }
            c++;
      }while(c<=m);

        r++;
       printf("\n");
       printf("\t");
    } while(r<=n);
}

Follow me on Facebook