Twitter Facebook Delicious Digg Stumbleupon Favorites More

Thursday, 22 December 2016

BCA/MCA Semester 2 : Data Structure Using C - Check Sparse Matrix

CHECK FOR SPARSE MATRIX

Data Structure Using C


Question: Write a program in 'C' to check whether a matrix is a sparse matrix or not.

Answer:
A sparse matrix is a matrix in which the most of the elements are zero (0). Here follows a program which inputs matrix elements and checks if more than half of its elements are zero, it is a sparse matrix.


/*
* C Program to check whether a matrix is Sparse Matrix
*/
  
#include <stdio.h>
  
int main(){
    int rows, cols, row, col, count=0;
    int matrix[50][50];
     
    printf("Enter Rows and Columns of Matrix\n");
    scanf("%d %d", &rows, &cols);
      
    printf("Enter Matrix of size %dX%d\n", rows, cols);
      
    for(row = 0; row < rows; row++){
        for(col = 0; col < cols; col++){
            scanf("%d", &matrix[row][col]);
        }
    }

    /* Print the matrix */
    printf("Matrix is:\n");
    printf("⎡");
    for(col = 0; col < cols; col++)
        printf("\t");
    printf("⎤\n");

    for(row = 0; row < rows; row++){
        printf("⎢ ");
        for(col = 0; col < cols; col++){
            printf("%3d\t", matrix[row][col]);
        }
        printf("⎥");
        printf("\n");
    }
    printf("⎣");
    for(col = 0; col < cols; col++)
        printf("\t");
    printf("⎦\n");
    
      
    /* Count the number of Zero's(0) in Matrix */
    for(row = 0; row < rows; row++){
        for(col = 0; col < cols; col++){
            if(matrix[row][col] == 0){
             count++;
            }
        }
    }
     
    if(count > (rows*cols)/2){
        printf("Input Matrix is a Sparse Matrix\n");
    } else {
        printf("Input Matrix is Not a Sparse Matrix\n");
    }
 
    return 0;
}

Compile the program in bash shell.  and run its compiled out.
$ gcc sparsecheck.c -o sparsecheck.out
$ ./sparsecheck.out

Here is the output:

BCA Semester 2 : Data Structure Using C - Check Sparse Matrix

Share:

0 comments:

Post a Comment

BCE-Hacks Notes

BCE-Hacks Notes
Chemical Engineering Notes

Maths Resources

Maths Resources
Maths Resources

Buy Books

Buy Books
Buy Books

Geography Quiz

Geography Quiz
Geography Quiz

NodeJS Tutorial

NodeJS Tutorial
Developer-Bytes

History MCQs

History MCQs
History Quiz For Competitive exams

Categories

Popular Posts

GooglePlus

Recent Posts

Unordered List

Express Print Zone

Eduvictors Quizzes

Online Quizzes, Study notes for CBSE Class 6 - 12

Text Widget

Compete4Exams

Study notes for Competitive Exams

Developer Bytes

Developer Bytes
Developer Bytes
Powered by Blogger.

Blogger Tutorials

Blogger Templates

Sample Text

Copyright © IP University Musings BCA, MCA, BBA, MBA, BTech Question Papers and Study Notes | Powered by Blogger
Design by SimpleWpThemes | Blogger Theme by NewBloggerThemes.com