Please read the new rule regarding the restriction on the use of AI tools. ×

Naaz's blog

By Naaz, history, 15 months ago, In English

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.

  • Vote: I like it
  • -9
  • Vote: I do not like it

| Write comment?
»
15 months ago, # |
  Vote: I like it +1 Vote: I do not like it

And can anyone please explain how the above code even works?

  • »
    »
    15 months ago, # ^ |
      Vote: I like it -15 Vote: I do not like it

    its simple the new line is printed only when i==n-1 condition becomes true otherwise its ignored

    • »
      »
      »
      15 months ago, # ^ |
      Rev. 3   Vote: I like it +18 Vote: I do not like it

      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

»
15 months ago, # |
Rev. 2   Vote: I like it +2 Vote: I do not like it

is it slower than the code below?

for (int i = 0; i < n; ++i)
    cout << i << ' ';
cout << '\n';

I think yes, as your code checks the condition i == n-1 every iteration (and, ++i might run faster than i++)

»
15 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

How about simple (if you really want to do it in print way- don't know why)

for (int i = 0; i < n; ++i) {
    printf("%d%c", i, " \n"[i == n - 1]);
} 

?

»
15 months ago, # |
  Vote: I like it 0 Vote: I do not like it

add a "\n" after the for loop block ends