can you please tell me how do you print new line. after a a for loop.
for (int i = 0; i < n; i++) {
cout << i << " \n"[i == n - 1];
}
As you can see in the above code it automatically prints newline when i == n-1. and I don't prefer to use ternery operator for this case. (It takes time to write. haha) But can this be done with printf(); Just asking. If it can be done please tell me how?
Happy Coding.
P.S : I use FastOlympicCoding extension in sublime text so it kind of takes into consideration the extra white at the end and does not give correct answer verdict.But the code snippet above mentioned it does not.









And can anyone please explain how the above code even works?
its simple the new line is printed only when i==n-1 condition becomes true otherwise its ignored
you hardly helped , given string is " \n"
when[i==n-1] it evaluates to true/1 and output is " \n"[1] which is "\n" else evaluation is 0 and output is " \n"[0] which is a simple white space
is it slower than the code below?
I think yes, as your code checks the condition
i == n-1every iteration (and,++imight run faster thani++)To my knowledge, I don't believe that there is a way to use printf and have the same outcome. However, there are other ways such as this code for (int i = 0; i < n; i++) { cout << i << " "; } cout << '\n';
This could also work.
How about simple (if you really want to do it in print way- don't know why)
?
add a "\n" after the for loop block ends