Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Блог пользователя Naaz

Автор Naaz, история, 15 месяцев назад, По-английски

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.

  • Проголосовать: нравится
  • -9
  • Проголосовать: не нравится

»
15 месяцев назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

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

  • »
    »
    15 месяцев назад, # ^ |
      Проголосовать: нравится -15 Проголосовать: не нравится

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

    • »
      »
      »
      15 месяцев назад, # ^ |
      Rev. 3   Проголосовать: нравится +18 Проголосовать: не нравится

      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 месяцев назад, # |
Rev. 2   Проголосовать: нравится +2 Проголосовать: не нравится

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 месяцев назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

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 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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