Naaz's blog

By Naaz, history, 3 years 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?
»
3 years ago, hide # |
 
Vote: I like it +1 Vote: I do not like it

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

»
3 years ago, hide # |
← 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++)

»
3 years ago, hide # |
← Rev. 2  
Vote: I like it 0 Vote: I do not like it

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 years ago, hide # |
← 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]);
} 

?

»
3 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

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