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

Here, we will see how to print a 2D matrix in C programming language without using curly braces. This technique uses a clever approach to eliminate the need for braces in nested loops.

Curly braces are separators in C that define separate code blocks in the program. Without curly braces, defining scopes is difficult, but we can use a shorthand technique to achieve the same result for simple operations.

Syntax

for (int i = 0; i < rows; i++)
    for (int j = 0; j < cols; j++)
        printf("%d%c", matrix[i][j], " \n"[j == cols-1]);

Method 1: Traditional Approach with Curly Braces

Let's first see the basic approach to print a 2D matrix using curly braces −

#include <stdio.h>

int main() {
    int arr[2][2] = {{12, 67},
                     {99, 5}};
    int rows = 2, cols = 2;
    
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
    return 0;
}
12 67 
99 5 

Method 2: Without Curly Braces Using Shorthand

To print the same matrix without using curly braces, we use the technique " \n"[j == cols-1]. This expression prints a space after each element except the last element in a row, which gets a newline character −

#include <stdio.h>

int main() {
    int mat[][3] = {
        {31, 7, 57},
        {42, 1, 99},
        {12, 9, 56}
    };
    int rows = 3, cols = 3;
    
    printf("The matrix is:\n");
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            printf("%d%c", mat[i][j], " \n"[j == cols-1]);
    
    return 0;
}
The matrix is:
31 7 57
42 1 99
12 9 56

How It Works

The key trick is in the expression " \n"[j == cols-1]:

  • When j != cols-1 (not the last column), the expression evaluates to " \n"[0], which is a space character
  • When j == cols-1 (last column), the expression evaluates to " \n"[1], which is a newline character
  • This eliminates the need for separate logic and curly braces to handle row endings

Conclusion

The shorthand technique " \n"[condition] allows printing 2D matrices without curly braces by using array indexing to select between space and newline characters. While clever, this approach may reduce code readability compared to the traditional method.

Updated on: 2026-03-15T12:43:50+05:30

348 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements