简体   繁体   中英

Print newline at the end of printing array using loop using escape sequence in c

Say I have the following code to print out the array a[n] in C:

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

What I want to do is to print the array giving a " " between two consecutive array element and end it with a newline but I want to avoid writing the printf statement twice. Can I do it somehow using some escape sequence? What is the simplest way?

One of the way would be to use Ternary operator like:

printf("%d%c", a[i], i==n-1? '\n': ' ');

Which means you print your array element and after that you print either a space if i is not equal to (array size - 1)* or a new line character when you get last element of the array to print.

* Since array index starts from 0.

您可以使用条件运算符来实现

printf("%d%c", a[i], (i != n-1) ? ' ' : '\n');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM