Search code examples
c++matrixvisual-c++user-inputsparse-matrix

Why the program runs with endless Input when taking values of a 2D matrix from user


I was trying to make a program to make a linked list implementation of Sparse Matrix and Multiply two Sparse matrix.

Lets say user choose dimensions 2*2 ,thus there would be 4 input from the user for matrix values. but When I run the program it takes endless input from the user. I don't know why.(this is the error)

whereas when i tried to directly initialize value of matrix while declaring instead of taking input, code works, but I want values of matrix to be entered by user. I tried to Run this code on Code Block and VS Code. program works same on both.

Is there a logical error?

            int m=0,n=0;
            int i,j;
            int sparseMatric[10][10];

            cout<<"Enter the Dimentions of the Matrix A"<<endl;
            cin>>m>>n;

            cout<<endl<<"Enter The Values of Sparse Matrix A"<<endl;
            for(i=0; i<m; i++)
                for(j=0; i<n; j++)
                    cin>>sparseMatric[i][j];        //whats wrong with input?

            Sparse_Matrix* start = NULL; 

            for (i = 0; i < m; i++) 
                for (j = 0; j < n; j++) 
                    if (sparseMatric[i][j] != 0) 
                        create_new_node(&start, sparseMatric[i][j], i, j); 
            .
            .
            .
             //code continues

Solution

  • for(j=0; i<n; j++)
    

    should be:

    for(j=0; j<n; j++)
    

    Otherwise, the loop will never exit since i is never modified inside the inner loop.


    NOTE: I also highly recommend adding a check to make sure that m and n are both under 10, or else the program will crash.