The Wayback Machine - https://web.archive.org/web/20240912223142/https://www.geeksforgeeks.org/print-2d-matrix-in-different-lines-and-without-curly-braces-in-cc/
Open In App

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

Last Updated : 09 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Following is a general way of printing 2D matrix such that every row is printed in separate lines. 

C




for (int i = 0; i < m; i++)
{
   for (int j = 0; j < n; j++)
   {
      cout << arr[i][j] << " ";
   }
    
   // Newline for new row
   cout << endl;
}


How to print without using any curly braces in for loops?   We strongly recommend you to minimize your browser and try this yourself first.   We can simply removed inner curly bracket as there is single line inner for loop. How to remove outer curly braces? Below is solution. 

C




// C++ program to print a matrix line by line without
// using curly braces.
#include<iostream>
using namespace std;
 
int main()
{
    int m = 2, n = 3;
    int mat[][3] = { {1, 2, 3},
                    {4, 5, 6},
                  };
    for (int i = 0; i < m; i++)
       for (int j = 0; j < n; j++)
 
          // Prints ' ' if j != n-1 else prints '\n'         
          cout << mat[i][j] << " \n"[j == n-1];
 
    return 0;
}


Output:

1 2 3
4 5 6

The actual trick is in following statement “\n”[j == n-1], explanation is as follows: ” \n” is a 2 character string where 1st character is space and 2nd character is newline, so we want space after each value except last for which we want a newline. In C, string literals are treated character arrays [See this for more details]. j == n-1 statement evaluates to 0 for internal elements (because for them j < n-1) and for last value(of each row) it becomes 1. So for internal elements, statement evaluate to ” \n”[0] i.e. ” ” and for last element of each row ” \n”[1] i.e. “\n”



Similar Reads

How can we use Comma operator in place of curly braces?
In C and C++, comma (, ) can be used in two contexts: Comma as an operator Comma as a separator But in this article, we will discuss how a comma can be used as curly braces. The curly braces are used to define the body of function and scope of control statements. The opening curly brace ({) indicates starting scope and closing curly brace (}) indic
3 min read
Why can't simple initialize (with braces) 2D std::array?
C++ provides a fixed-size sequence container named std::array. It is a useful alternative to C-style arrays, providing additional features such as bounds checking and iterators. We can also create a 2D version of the std::array where each element is an instance of std::array itself. However, when it comes to initializing a 2D std::array, things can
3 min read
Reading Lines by Lines From a File to a Vector in C++ STL
Prerequisites: STL in C++Vector in C++File handling in C++ The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. Vector in C++ STL Vectors are the same as dynamic arrays with
2 min read
Program to print last 10 lines
Given some text lines in one string, each line is separated by ‘\n’ character. Print the last ten lines. If number of lines is less than 10, then print all lines. Source: Microsoft Interview | Set 10 Following are the steps 1) Find the last occurrence of DELIM or '\n' 2) Initialize target position as last occurrence of '\n' and count as 0 , and do
4 min read
Print 1 to 100 in C++ Without Loops and Recursion
We can print 1 to 100 without using loops and recursion using three approaches discussed below: 1) Template Metaprogramming: Templates in C++ allow non-datatypes also as parameters. Non-datatype means a value, not a datatype. Example: C/C++ Code // CPP Program to print 1 to 100 // without loops and recursion #include &lt;iostream&gt; using namespac
3 min read
Print 1 to 100 without loop using Goto and Recursive-main
Our task is to print all numbers from 1 to 100 without using a loop. There are many ways to print numbers from 1 to 100 without using a loop. Two of them are the goto statement and the recursive main. Print numbers from 1 to 100 Using Goto statement Follow the steps mentioned below to implement the goto statement: declare variable i of value 0decla
5 min read
Print substring of a given string without using any string function and loop in C
Write a function mysubstr() in C that doesn't use any string function, doesn't use any loop, and prints substring of a string. The function should not modify contents of string and should not use a temporary char array or string. For example mysubstr("geeksforgeeks", 1, 3) should print "eek" i.e., the substring between indexes 1 and 3. One solution
2 min read
How to print range of basic data types without any library function and constant in C?
How to write C code to print range of basic data types like int, char, short int, unsigned int, unsigned char etc? It is assumed that signed numbers are stored in 2's complement form. We strongly recommend to minimize the browser and try this yourself first. Following are the steps to be followed for unsigned data types. 1) Find number of bytes for
4 min read
Write a C program to print "GfG" repeatedly without using loop, recursion and any control structure?
As we all know the concept of printing the given string repeatedly using various loops(for loop,while loop),recursion and some control structure also. But the question is how we will print the given string repeatedly i.e. infinitely without using any loops,recursion and any control structure? Examples: Input : GFG Output : GFGGFGGFGGFG...(It will p
1 min read
How to print a number 100 times without using loop and recursion in C?
It is possible to solve this problem using loop or a recursion method but what if both are not allowed? A simple solution is to write the number 100 times in cout statement. A better solution is to use #define directive (Macro expansion) C/C++ Code // CPP program to print &amp;quot;1&amp;quot; 100 times. // Prints 1 only once #define a cout&amp;lt;
1 min read
Print a number 100 times without using loop, recursion and macro expansion in C?
It is possible to solve this problem using loop or a recursion method. And we have already seen the solution using #define directive (Macro expansion) but what if all three are not allowed? A simple solution is to write the number 100 times in cout statement. A better solution is to use concept of Concept of setjump and longjump in C. C/C++ Code //
1 min read
Print colored message with different fonts and sizes in C
In C/C++ we can use graphics.h header file for creation of programs which uses graphical functions like creating different objects, setting the color of text, printing messages in different fonts and size, changing the background of our output console and much more. Here we will create a program which will print message ("geeks") in colored form in
2 min read
Print "Even" or "Odd" without using conditional statement
Write a program that accepts a number from the user and prints "Even" if the entered number is even and prints "Odd" if the number is odd. You are not allowed to use any comparison (==, &lt;,&gt;,...etc) or conditional statements (if, else, switch, ternary operator,. Etc). Method 1 Below is a tricky code can be used to print "Even" or "Odd" accordi
4 min read
Print a character n times without using loop, recursion or goto in C++
Given a character c and a number n, print the character c, n times. We are not allowed to use loop, recursion, and goto. Examples : Input : n = 10, c = 'a'Output : aaaaaaaaaa Input : n = 6, character = '@'Output : @@@@@@ In C++, there is a way to initialize a string with a value. It can be used to print a character as many times as we want. While d
2 min read
Write a C program to print "Geeks for Geeks" without using a semicolon
First of all we have to understand how printf() function works. Prototype of printf() function is: int printf( const char *format , ...) Parameter format: This is a string that contains a text to be written to stdout.Additional arguments: ... (Three dots are called ellipses) which indicates the variable number of arguments depending upon the format
2 min read
C Program to print numbers from 1 to N without using semicolon?
How to print numbers from 1 to N without using any semicolon in C. C/C++ Code #include&amp;lt;stdio.h&amp;gt; #define N 100 // Add your code here to print numbers from 1 // to N without using any semicolon What code to add in above snippet such that it doesn't contain semicolon and prints numbers from 1 to N?We strongly recommend you to minimize yo
2 min read
Print individual digits as words without using if or switch
Given a number, print words for individual digits. It is not allowed to use if or switch.Examples: Input: n = 123 Output: One Two Three Input: n = 350 Output: Three Five Zero We strongly recommend you to minimize your browser and try this yourself first. The idea is to use an array of strings to store digit to word mappings. Below are steps.Let the
5 min read
Print "Hello World" in C/C++ without using any header file
Write a C/C++ program that prints Hello World without including any header file. Conceptually it's seems impractical to write a C/C++ program that print Hello World without using a header file of "stdio.h". Since the declaration of printf() function contains in the "stdio.h" header file. But we can easily achieve this by taking the advantage of C p
2 min read
Print Hello World without semicolon in C/C++
Every statement in C++ must end with a semicolon as per basics. However, unlike other languages, almost all statements in C++ can be treated as expressions. However there are few scenarios when we can write a running program without semicolon. If we place the statement inside an if/switch/while/macro statement with a blank pair of parentheses, we d
2 min read
How to print a semicolon(;) without using semicolon in C/C++?
Another interesting question is how can a semicolon be printed without using any semicolon in the program. Here are methods to print ";" : Using printf / putchar in if statement: C/C++ Code // CPP program to print // ; without using ; // using if statement #include &amp;lt;stdio.h&amp;gt; int main() { // ASCII value of semicolon = 59 if (printf(
1 min read
C program to print a string without any quote (single or double) in the program
Print a string without using quotes anywhere in the program using C or C++. Note : should not read input from the console. The idea is to use macro processor in C (Refer point 6 of this article). A token passed to macro can be converted to a string literal by using # before it. C/C++ Code // C program to print a string without // quote in the progr
1 min read
C program to print characters without using format specifiers
As we know that there are various format specifiers in C like %d, %f, %c etc, to help us print characters or other data types. We normally use these specifiers along with the printf() function to print any variables. But there is also a way to print characters specifically without the use of %c format specifier. This can be obtained by using the be
1 min read
How will you print numbers from 1 to 100 without using a loop?
If we take a look at this problem carefully, we can see that the idea of "loop" is to track some counter value, e.g., "i = 0" till "i &lt;= 100". So, if we aren't allowed to use loops, how can we track something in the C language?Well, one possibility is the use of 'recursion', provided we use the terminating condition carefully. Here is a solution
12 min read
Print system time in C++ (3 different ways)
First Method Printing current date and time using time() Second Method // CPP program to print current date and time // using time and ctime. #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; int main() { // declaring argument of time() time_t my_time = time(NULL); // ctime() used to give the present time printf(&quot;%s
2 min read
Lex program to count the number of lines, spaces and tabs
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.Let's the how to count the number of lines, spaces and tabs using Lex. Example: Input: Geeks for Geeks gfg gf
1 min read
Printing Output in Multiple Lines in C++
This article focuses on discussing how to use cout for multi-line printing. This can be easily done using any of these two methods: Using endl.Using \n. Let's discuss each of these methods in detail. Using endl The endl statement can be used to print the multi-line string in a single cout statement. Below is the C++ program to show the same: C/C++
2 min read
C Program to count number of lines in a file
C/C++ Code /* C Program to count the Number of Lines in a Text File */ #include &lt;stdio.h&gt; #define MAX_FILE_NAME 100 int main() { FILE *fp; int count = 0; // Line counter (result) char filename[MAX_FILE_NAME]; char c; // To store a character read from file // Get file name from user. The file should be // either in current folder or complete p
1 min read
How to write long strings in Multi-lines C/C++?
Image a situation where we want to use or print a long long string in C or C++, how to do this? In C/C++, we can break a string at any point in the middle using two double quotes in the middle. Below is a simple example to demonstrate the same. C/C++ Code #include&lt;stdio.h&gt; int main() { // We can put two double quotes anywhere in a string char
2 min read
How to use getline() in C++ when there are blank lines in input?
In C++, if we need to read a few sentences from a stream, the generally preferred way is to use the getline() function as it can read string streams till it encounters a newline or sees a delimiter provided by the user. Also, it uses &lt;string.h&gt; header file to be fully functional. Here is a sample program in c++ that reads four sentences and d
2 min read
Implement your own tail (Read last n lines of a huge file)
Given a huge file having dynamic data, write a program to read last n lines from the file at any point without reading the entire file. The problem is similar to tail command in linux which displays the last few lines of a file. It is mostly used for viewing log file updates as these updates are appended to the log files. Source : Microsoft Intervi
4 min read
Article Tags :
Practice Tags :