Answer to Question #308351 in C++ for ankur

Question #308351

Identify the logical and syntax errors in the given code snippet (with the explanation), to print the sum of diagonal elements in the square matrix:

void main() { int i, j, matri[10][10], row, col; int sum = 0; cin>>row; cin>>col; for (i = 1; i < col; i++) { for (j = 1; j < row; j++) { cin>matrix[i][j]; } } for (i = 1; i > row; i++) { for (j = 1; j > col; i++) { if (i > j) sum = sum - matrix[i][j]; } } cout<<sum; }


1
Expert's answer
2022-03-09T06:38:35-0500
using namespace std;


/*
	Identify the logical and syntax errors in the given code snippet (with the explanation), to print the sum of diagonal elements in the square matrix:


*/
/*
void main() 
{ 
	int i, j, matri[10][10], row, col; 
	int sum = 0; 
	cin>>row; cin>>col; 
	for (i = 1; i < col; i++) 	//Error --> i and j should be iitialized  with i=0 and j=0
	{
		for (j = 1; j < row; j++)
		{
			cin>matrix[i][j]; 	//Error --> cin>	should be cin>>
								//Error --> matrix ws not declared
		} 
	} 
	for (i = 1; i > row; i++)	//Error --> i and j should be iitialized  with i=0 and j=0
	{							//Error --> i < row and j < col
		for (j = 1; j > col; i++)
		{ 
			if (i > j) sum = sum - matrix[i][j]; 
		} 
	} 
	cout<<sum; 
}
*/

//Corrected Code
int main() 
{ 
	int i, j, matrix[10][10], row, col; 
	int sum = 0; 
	cin>>row; cin>>col; 
	for (i = 0; i < col; i++) 	//Error
	{
		for (j = 0; j < row; j++)
		{
			cin>>matrix[i][j]; 	//Error --> cin>	should be cin>>
								//Error --> matrix ws not declared
		} 
	} 
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; i++)
		{ 
			if (i > j) sum = sum + matrix[i][j]; 	//Error --> sum = sum + matrix[i][j]
		} 
	} 
	cout<<sum; 
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog