the following code prints a square of '*'
characters:
int m = 5; int n=5;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
std::cout << "*" << " \n"[j==5];
Output:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
My question is regarding to the " \n"[j==5]
part.
Does anyone know how exactly does this syntax work?
You are inserting std::endl which prints next string on the next line. The following newline \n and std::flush is equivalent to std::endl . std::cout << printFunction() << std::endl; Now removing std::endl will print the string in the same line.
The symbol \n is a special formatting character. It tells cout to print a newline character to the screen; it is pronounced “slash-n” or “new line.”
cout is a object for which << operator is overloaded, which send output to standard output device. The main difference is that printf() is used to send formated string to the standard output, while cout doesn't let you do the same, if you are doing some program serious, you should be using printf().
The cout operator does not insert a line break at the end of the output. One way to print two lines is to use the endl manipulator, which will put in a line break. The new line character \n can be used as an alternative to endl. The backslash (\) is called an escape character and indicates a special character.
" \n"
is array of 3 char
s. You can index is as normal array. Boolean values implicitly convert to integers: false
to 0
, true
to 1
. So it will use '\n'
for j == 5
and ' '
if not,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With