Search Here

C program for 2D Array



/* C program to perform simple operations on 2D Array */

void main()
{
    int arr[10][10],r,c,i,j,sum,trace;
    
    printf("____ 2D Array ____\n\n");
    printf("Enter the value of ROW and COLUMN: ");
    scanf("%d%d",&r,&c);
    for(i=0;i<r;i=i+1)
    {
        for(j=0;j<c;j=j+1)
        {
            printf("\nEnter the value for row no %d and column no %d: ",i+1,j+1);
            scanf("%d",&arr[i][j]);
        }
    }

    // Displaying the matrix
    printf("\nThe entered matrix is \n");
    for(i=0;i<r;i=i+1)
    {
        for(j=0;j<c;j=j+1)
            printf("%d ",arr[i][j]);
        printf("\n");
    }

    // Displaying transpose of the matrix
    printf("\nThe transpose of the given matrix is \n");
    for(i=0;i<r;i=i+1)
    {
        for(j=0;j<c;j=j+1)
            printf("%d ",arr[j][i]);
        printf("\n");
    }
    
    // Displaying sum of elements
    sum=0;
    for(i=0;i<r;i=i+1)
        for(j=0;j<c;j=j+1)
            sum=sum+arr[i][j];
    printf("\nThe Sum of the elements is: %d",sum);
    
    // Displaying trace of the matrix
    if(r==c)
    {
        trace=0;
        for(i=0;i<r;i=i+1)
            for(j=0;j<c;j=j+1)
                if(i==j)
                    trace=trace+arr[i][j];
        printf("\nTrace is: %d",trace);
    }
    else
        printf("\nTrace can not be calculated");
}


Output

No comments:

Post a Comment