Print 2D matrix in different lines and without curly braces in C/C++


Here, we will see the code that will print a 2D matrix in c/c++ programming language without using curly braces.

Curly braces are separators in a programming language that are used to define separate code blocks in the program. Without curly braces defining scopes is difficult in c/c++.

Let’s see the basic code and sample output to print 2D matrix.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int arr[2][2] = {{12, 67},
   {99, 5}};
   int n = 2, m = 2;
   for (int i = 0; i < m; i++){
      for (int j = 0; j < n; j++){
         cout<<arr[i][j]<<" ";
      }
      cout << endl;
   }
   return 0;
}

Output

1267
995

To print the same without using curly braces. As we have to print black space at each iteration except the last which is a new line. For this, we have a shorthand

“ \n”[j== n-1].

Suppose we have to print a 2X2, matrix using this. After the first element, a blank space occurs and the second has a newline.

The program to show the implementation of this solution

Example

 Live Demo

#include<iostream>
using namespace std;
int main() {
   int mat[][3] = {
      {31, 7, 57},
      {42, 1, 99},
      {12, 9, 56}
   };
   int n=3, m=3;
   cout<<"The matrix is : \n";
   for (int i = 0; i < m; i++)
   for (int j = 0; j < n; j++)
      cout<<mat[i][j]<<" \n"[j==n-1];
   return 0;
}

Output

The matrix is :
31 7 57
42 1 99
12 9 56
raja
Published on 03-Feb-2020 09:56:22
Advertisements