Search code examples
clogic

How to print this pattern? can anyone explain logic?


Star pattern

Anyone can make logic for this pattern? I tried using 2 for loops also. I just had an interview where I was asked to create star pattern as shown in picture.

#include <stdio.h>
int main()
{
   char f;
    int n;
    printf("Enter the number:");
    scanf("%d", &n);
    int i, j, s, k, l, m;
    for (s = 1; s <= n; s++) //printing
    {
        for (k = 1; k <= n; k++)
        {
            for (i = 1; i <= n; i++) //pattern
            {
                for (j = 1; j <= n; j++)
                {
                    if ((i + j == n + 1)) //star positions
                    {
                        printf("* ");
                    }
                    else
                    {
                        printf(" ");
                    }                
                }
                printf("\n");   //next line
            }            
        }        
    }
    return 0;
}

Solution

  • This problem can solve using 2 for loop.

    #include<stdio.h>
        int main()
        {
            int num;
            printf("Enter pattern length :");
            scanf("%d",&num);
            
            int matrix=num*num;
            for(int i=0;i<matrix;i++)
            {
        
                for(int j=0;j<matrix;j++)
                {
                   if((i+j+1)%num==0)
                   {
                       printf("*");
                   }
                   else
                   {
                      printf(" ");
                   }
                }
                printf("\n");
            }
        }