Friday 21 July 2017

Write program for Lower Triangula Matrix

Lower triangle matrix
Write a program to print the following pattern for a given integer.

Sample Input 1:
3
Sample Output 1:

1
6 2
5 4 3 
                                          C-Solution
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
 int n,i,c=1,j=0,ans;
 scanf("%d",&n);
 int a[n][n];
    if(n%2==0){ans=(pow(n,2)/2)+n/2;}
    else 
    ans=(n-(n/2))*n;
    
    int m=n-1,p=0,l=0,k;
    while(c-1<ans)
    {
        for(i=l+p;i<=m&&c-1<ans;i++)
        a[i][i-l]=c++;
        ++l;
        for(j=m-l;j>=p&&c-1<ans;j--)
        a[m][j]=c++;
        for(k=m-1;k>l+p-1&&c-1<ans;k--)
        a[k][p]=c++;
        m--;p++;
    }
    for(i=0;i<n;i++)
    {    for(j=0;j<=i;j++)
        {    printf("%d ",a[i][j]);}
        printf("\n");
    }
 return 0;
}

No comments:

Post a Comment