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

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

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
  • Проголосовать: не нравится

»
3 года назад, скрыть # |
 
Проголосовать: нравится +1 Проголосовать: не нравится

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

»
3 года назад, скрыть # |
← 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++)

»
3 года назад, скрыть # |
← Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

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.

»
3 года назад, скрыть # |
← 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]);
} 

?

»
3 года назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

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