program to print upper half of matrix.

This is a program to print upper half of the matrix.
#include <iostream>
using namespace std;

int upperhalf(int n, int apu[n][n])
{
cout<<"The upper half of the matrix is :\n";
for(int r=0; r<n; r++)
{
for(int s=r; s<n; s++)
{
cout<<apu[r][s];
}
}
}

int main()
{
int k, j, arr[k][j];
cout<<"Enter no. of rows and columns.[They should be same] \n"; cin>>k;
cout<<"Enter the elements.\n";
for(int p=0; p<k; p++)
{
for(int q=0; q<k; q++)
{
cin>>arr[q][k];
}
}
upperhalf(k, arr);
return 0;
}

the compiler is giving these errors:-
sh-4.2# g++ -o main *.cpp
main.cpp:4:31: error: use of parameter outside fun
ction body before ']' token
int upperhalf(int n, int apu[n][n])
^
main.cpp:4:34: error: use of parameter outside fun
ction body before ']' token
int upperhalf(int n, int apu[n][n])
^
main.cpp: In function 'int upperhalf(...)':
main.cpp:7:20: error: 'n' was not declared in this
scope
for(int r=0; r<n; r++)
^
main.cpp:11:19: error: 'apu' was not declared in t
his scope
cout<<apu[r][s];

i dont know where i am wrong.
please help asap.
Please put your code between the [code] blocks for better readability. You can do it using the <> button when editing.
Last edited on
Ok so here's the working code which prints the upper half of the matrix (2D array):

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>

using namespace std;

void upperhalf(int n, int **apu)
{
	cout << "The upper half of the matrix is :\n";
	for (int r = 0; r<n/2; r++)
	{
		cout << "Row " << r + 1 << ": ";
		for (int s = 0; s<n; s++)
		{
			cout << apu[r][s] << ", ";
		}

		cout << endl << endl;
	}
}

int main()
{
	//const int k, j;
	//int arr[k][j];
	int k;
	cout << "Enter no. of rows and columns.[They should be same] \n"; cin >> k;

	// Declare the rows of the 2D array
	int **arr = new int*[k];
	
	for (int i = 0; i < k; i++) {
		// For each row, declare 'k' columns
		arr[i] = new int[k];
	}

	cout << "Enter the elements.\n";
	for (int p = 0; p<k; p++)
	{
		cout << "Row " << p + 1 << ": " << endl;
		for (int q = 0; q<k; q++)
		{
			cout << "Column " << q+1 << ": ";
			cin >> arr[p][q];
		}

		cout << endl;
	}

	upperhalf(k, arr);

	system("PAUSE");
	return 0;
}



You have to create your arrays dynamically if you want the rows and columns from the user. So this is why I have used double pointers (int **arr). I have commented the lines where the rows and columns of the array is getting allocated.

You also have to pass the double pointers to the function you created for displaying.

Another problem in your code was that the looping was not right, both in main and function, so I've fixed it. Check it with your code to find out where the problem was.
Last edited on
Thanks man :)
Topic archived. No new replies allowed.