Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the last term doing?

Tags:

c++

loops

cout

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.

like image 269
Thakur Karthik Avatar asked Dec 14 '17 03:12

Thakur Karthik


2 Answers

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.

like image 151
Mankarse Avatar answered Oct 04 '22 06:10

Mankarse


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

like image 45
asimes Avatar answered Oct 04 '22 07:10

asimes