Creation of sparse matrix

PHOTO EMBED

Wed Apr 19 2023 07:30:36 GMT+0000 (Coordinated Universal Time)

Saved by @saakshi #c++

#include <iostream>
using namespace std;

struct element
{
  int i;
  int j;
  int x;
 };
 
 struct sparse
 {
     int m;
     int n;
     int num;
     struct element *ele;
 };
 
 void create(sparse *s)
 {
     cout << "Enter dimensions : ";
     cin >> s->m >> s->n;
     cout << "Enter number of non zero elements : \n";
     cin >> s->num;
     
     s->ele = new element[s->num];
     
     cout << "Enter all non zero elements : ";
     for(int i=0; i<s->num; i++)
     {
         cout << "Enter row no: ";
         cin >> s->ele[i].i;
         cout << "Enter column no: ";
         cin >> s->ele[i].j;
         cout << "Enter element: ";
         cin >> s->ele[i].x;
     }
 }
 
 void display(struct sparse s)
{
    int k;
    for (int i=0; i< s.m; i++)
    {
        for(int j=0; j< s.n; j++)
        {
            if(i==s.ele[k].i && j==s.ele[k].j)
                cout << s.ele[k++].x << " ";
            else 
                cout << " ";
        }
        cout << endl;
    }
}

int main() {
    
    struct sparse s;
    create(&s);
    display(s);
    

    return 0;
}
content_copyCOPY