C program to print a 2D matrix row wise without using curly braces

  • Write a program in C to print a 2D matrix row wise without curly braces.
  • How to print a two dimentional array(one row in one line) without using curly braces.

Required knowledge: For loop

Here, basically we have to do two things. First iterate through each row of matrix and print space separated elements and second at the end of each row we have to print a newline character(\n). This is how the code would look like, If we can use curly braces:

for (row = 0; row < rows; row++) {
   for (col = 0; col < cols; col++) {
      printf("%d ",matrix[row][col]);
   }
   printf("\n");
}
  • We will use two for loops. One iteration of outer for loop will print one row at a time whereas one iteration of inner for loop print’s all elements of a row.
  • Opening and Closing braces are not required for single statement inside for loop code block.
    For Example:
    for(i = 0; i < 100; i++)
    sum+= i;
  • The main problem is how can we remove curly braces form outer for loop as it contains multiple statements inside it’s code block. We will use a character string of length 2 (” \n”) and print either first character of string(” “) or second character of string(“\n”) depending upon whether we are printing non-last character or last character of a row. Just check the code below to get more clarity on this approach.

C program to print a 2D matrix row wise without using curly braces

C program to print a 2D matrix row wise without using curly braces

#include<stdio.h>
  
int main() {
    int rows = 3, cols = 3, row, col; 
    int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
     
    /* Print matrix using two for loops */
    for (row = 0; row < rows; row++)
       for (col = 0; col < cols; col++)          
          printf("%d%c", matrix[row][col], " \n"[col == cols-1]);
  
    return 0;
}

Output

1 2 3
4 5 6
7 8 9