Thakur Karthik
Thakur Karthik

Reputation: 3528

Whats the cout << i << " \n"[ i == n ] term doing?

In this statement

for (i = 1; i <= n; i++) {
    cout << i << " \n"[ i == n ];
}

what is the last term in cout statement [i==n] doing? This loop prints space separate numbers I guess.

Upvotes: 9

Views: 242

Answers (2)

asimes
asimes

Reputation: 5894

It is a silly way to index either the character ' ' or the character '\n'. This does the same idea and prints "Hello World":

#include <iostream>

int main() {
        for (int i = 0; i < 11; i++)
                std::cout << "Hello World"[i];
        return 0;
}

i == n is either going to be true or false. When cast to an integer for indexing using [i == n] you get either the first or second element

Upvotes: 7

Mankarse
Mankarse

Reputation: 40623

It is an obtuse way of writing:

(i == n ? '\n' : ' ')

That is, when i == n, a newline is printed, otherwise a space is printed.

The idea is to separate the numbers by spaces, and to put a newline after all the numbers have been printed.

Upvotes: 15

Related Questions