Caro
Caro

Reputation: 11

How do I get rid of a space at the end of output?

Here is my code so far for producing Fibonacci numbers. I keep getting a zero because it it adding a space bar at the very end, but I need a space between numbers.

#include<stdio.h>
void fib(int);

int main()
{
    int n = 0;
    while (n <= 0 || n > 70)
    {
        printf("enter the value(between 0 and 70)");
        scanf("%d", &n);
        if (n <= 0 || n >= 70)
            printf("wrong input\n");
    }
    fib(n);
    return 0;
}

void fib(int n)
{
    /* Declare an array to store Fibonacci numbers. */
    int f[n]; // 1 extra to handle case, n = 0
    int i;

    /* 0th and 1st number of the series are 0 and 1*/
    f[0] = 0;
    f[1] = 1;
    printf("%d %d ", f[0], f[1]);
    for (i = 2; i < n; i++)
    {
        f[i] = f[i - 1] + f[i - 2];
        printf("%d ", f[i]);
    }
}

Upvotes: 1

Views: 36

Answers (1)

Unmitigated
Unmitigated

Reputation: 89204

Remove the trailing space in the first printf and print the space before instead of after the number in the loop.

printf("%d %d", f[0], f[1]);
for (i = 2; i < n; i++) {
    f[i] = f[i - 1] + f[i - 2];
    printf(" %d", f[i]);
}

Upvotes: 2

Related Questions