waiting for answer

There is problem in the output where it is just displaying last values just displaying last row values for every output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  # include <iostream>
using namespace std;
int main()
{
    int i;
    int j;
    int a[i][j];
    int nrow;
    int ncol;
    cout << "This program will print matrix." << endl;
    cout << "enter number of rows : ";
    cin >> nrow;
    cout << "enter number of columns : ";
    cin >> ncol;
    for (i=0; i<nrow; i++) {
        for (j=0; j<ncol; j++) {
            cout << "enter elemnt of row : ";
            cin >>a[i][j];
        }
    }
    for (i=0; i<nrow; i++) {
        for (j=0; j<ncol; j++) {
            cout<<a[i][j];
        }
        cout<<endl;
    }
    return 0;
}


Output

This program will print matrix.
enter number of rows : 3
enter number of columns : 2
enter elemnt of row : 1
enter elemnt of row : 2
enter elemnt of row : 3
enter elemnt of row : 4
enter elemnt of row : 5
enter elemnt of row : 6
56
56
56
Last edited on
Lines 5&6: i and j are uninitialized.
Line 7: This isn't valid C++, although many compilers allow it as an extension to the language. But for the ones that allow it, the value of i and j is undefined, so who knows how big that array will be?

You can fix this while using the extension by deleting line 7 and adding the following after line 14:
int a[nrow][ncol];

Using standard C++, you could allocate the array using large enough dimensions to handle the expected input. For example, if the user shouldn't enter more than 1000 for the row or column then you could do:
int a[1000][1000];
but what's to prevent the user from entering a larger number? You'd have to add a bunch of code to check their input, at least in a real-world program.

I more robust way to handle this is the use vectors instead, but you might not have learned about them yet.
This should fix you problem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

using namespace std;

int main()
{
	int i;
	int j;
	int a[50][50];
	int nrow;
	int ncol;
	cout << "This program will print matrix." << endl;
	cout << "enter number of rows : ";
	cin >> nrow;
	cout << "enter number of columns : ";
	cin >> ncol;
	for (i = 0; i<nrow; i++) 
	{
		for (j = 0; j<ncol; j++) 
		{
				cout << "enter elemnt of row : ";
				cin >> a[i][j];
		}
	}
	for (i = 0; i<nrow; i++) 
	{
		for (j = 0; j<ncol; j++) 
		{
			cout << a[i][j];
		}
		cout << endl;
	}
	
	cin.get();
	cin.ignore();

	return 0;
}
Topic archived. No new replies allowed.