Reputation: 303
I print out each element of the array through the gap
// n - array length
for(x=0; x<n; x++){
printf("%d ", a[x]);
}
It returns me:
1 2 3 4 5 [space here]
How to remove latest space (character)?
Upvotes: 1
Views: 2730
Reputation: 462
Not sure I would recommend this method, but something like this will work too:
for ( x = 0; x < n; x++ )
{
printf("%c%d", " "[!x], a[x]);
}
It's a bit cheaty, but neat in my opinion.
Upvotes: 0
Reputation: 606
Everyone is posting their own answers, so here's my own.
int n, i;
for (i = 1, n = 5; i <= n; i++)
printf("%d%s", i, i < n ? " " : "");
Upvotes: 0
Reputation: 37914
A "branch-less" variant of Paul Roub's solution. It requires that n > 0
holds (i.e. consequently there exist at least one element in a
array).
#include <stdio.h>
int main(void)
{
int x, n, a[] = {1, 2, 3, 4, 5};
n = 5;
printf("%d", a[0]);
for (x = 1; x < n; x++)
printf(" %d", a[x]);
putchar('\n');
return 0;
}
Upvotes: 0
Reputation: 11070
The way is simple:
for(x=0; x<n; x++){
printf("%d", a[x]);
if(x<(n-1)){
printf(" ");
}
}
Upvotes: 2
Reputation: 36438
An alternative, IMHO more readable approach:
for ( x = 0; x < n; x++ )
{
if (x > 0)
putchar(' ');
printf("%d", a[x]);
}
Upvotes: 3
Reputation: 4852
for(x=0; x<n-1; x++){
printf("%d ", a[x]);
}
if(n > 0)
printf("%d", a[x]);
Upvotes: 1
Reputation: 19864
for(x=0; x<n; x++){
if(x == n-1)
printf("%d", a[x]); /* Print without space when printing last element */
else
printf("%d ", a[x]);
}
Upvotes: 3