yeswecode
yeswecode

Reputation: 303

How to remove last space from printf output

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

Answers (7)

p4plus2
p4plus2

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

scottyeatscode
scottyeatscode

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

Grzegorz Szpetkowski
Grzegorz Szpetkowski

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

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

The way is simple:

for(x=0; x<n; x++){
    printf("%d", a[x]);
    if(x<(n-1)){
         printf(" ");
    }
}

Upvotes: 2

Paul Roub
Paul Roub

Reputation: 36438

An alternative, IMHO more readable approach:

for ( x = 0; x < n; x++ )
{
   if (x > 0)
     putchar(' ');
   printf("%d", a[x]);
}

Upvotes: 3

tapananand
tapananand

Reputation: 4852

for(x=0; x<n-1; x++){
    printf("%d ", a[x]);
}
if(n > 0)
    printf("%d", a[x]);

Upvotes: 1

Gopi
Gopi

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

Related Questions