Thursday, December 6, 2018

C code review implement Transpose of Matrix in Sparse Form

This C code shows how to implement Transpose of Matrix in Sparse Form. And code is helpful while user is in between any algorithm-like manipulation task.

code:

//Tested OK on Code::Block IDE 17.12 & Cygwin+GCC tools.
//Transpose of Matrix in Sparse Form.

#include <stdio.h>
//#include <conio.h>

int a[100][100],b[100][100];

void main()
{
    int i,m,n,p,q,col,t;
//    clrscr();
    printf("\nEnter the no. of rows");
    scanf("%d", &a[0][0]);
    printf("\nEnter the no. of cols");
    scanf("%d", &a[0][1]);
    printf("\nEnter the number of non zero terms");
    scanf("%d", &a[0][2]);

    for(i=1; i<=a[0][2]; i++)
    {
        printf("\nEnter the value (that is non zero)");
        scanf("%d",&a[i][2]);
        printf("\nEnter the row  for %d  : ",a[i][2]);
        scanf("%d",&a[i][0]);
        printf("\nEnter the col for %d  : ",a[i][2]);
        scanf("%d",&a[i][1]);
    }

    /* Printing for testing the sparse input */
    printf("\n *****************************"
           "\nThe martix you entered is"
           "\n************************ "
           " \nRow       Col      Value \n");
    for ( i = 0; i <= a[0][2]; i++)
    {
        printf(" %d      %d      %d      \n", a[i][0],a[i][1],a[i][2]);
    }

    /* Calling function for evaluation of transpose */

    m = a[0][0];
    n = a[0][1];
    t = a[0][2];

    b[0][0] = n;
    b[0][1] = m;
    b[0][2] = t;

    q=1;

    for( col = 1; col <=n; col++)
    {
        for(p = 1; p<=t; p++)
        {
            if(a[p][1] == col)
            {
                b[q][0] = a[p][1];
                b[q][1] =a[p][0];
                b[q][2] = a[p][2];
                q++;
            }
        }
    }                  //end of outer for loop

    /* Printing the transposed matrix */

    getchar();
    printf("\nThe Transpose of the above matrix is \n");
    for ( i = 0; i <= a[0][2]; i++)
    {
        printf(" %d      %d      %d     \n ", b[i][0],b[i][1],b[i][2]);
    }
    getchar();
}

//end of program

To see such C code reviews refer blog archieve at right side or click CCode lable for till posted posts list.

...till next post, bye-bye and take care.

No comments:

Post a Comment