What does cout << (1 + (a[i] == mx)) << " \n"[i + 1 == n]; do?

Revision en2, by ahnaf09, 2025-06-19 12:44:50

Hi everyone,

While solving Problem 2107A - LRC и VIP, I got stuck and decided to read the editorial. In the editorial solution, I came across the following line:

for (int i = 0; i < n; ++i)
    cout << (1 + (a[i] == mx)) << " \n"[i + 1 == n];

I have a basic understanding that the expression (a[i] == mx) returns a boolean value, and when it's true, it becomes 1, so the full expression would be 1 + 1 = 2; otherwise, 1 + 0 = 1.

However, I'm not fully sure about the use of " \n"[i + 1 == n]; — I assume it’s a trick to conditionally print either a space or a newline depending on whether it’s the last element in the loop.

Can someone please explain this line step-by-step? I'd really appreciate any clarification.

Thanks in advance.

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English ahnaf09 2025-06-19 12:44:50 6
en1 English ahnaf09 2025-06-19 12:42:47 832 Initial revision (published)