I am new to C and programming. I am trying to print an array separated by comma. But don't wish to print the last comma element. Here is my code so far
void p_array(const int array[], const int s) {
for(int i = 0; i < s; i++) {
printf("%i, ",array[i]);
}
}
I am getting the array printed as
1, 2, 3, 4,
Whereas I dont wish to have the last element of comma printed. I know I am doing something fundamental wrong. Any help is appreciated.
1, 2, 3, 4
for(int i = 0; i < s; i++) {
if(i)
printf(", ");
printf("%i",array[i]);
}
You could do this:
printf("%i%s", array[i], i==s-1 ? "" : ", ");
An alternative is to have the loop go one less iteration, and the print out the last element w/ a printf
after the loop.
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.