0

The following code uses a user define function to print fibonacci numbers up to the user's choosing. The only problem is that the output includes the first n fibonacci numbers, followed by a zero. (e.g. 1,1,2,3,5,8,0) How can I get rid of the zero?

#include <stdio.h>
int fibonacci(int a);
int main()
{
    int j, number;
    printf("Enter the number of terms: ");
    scanf("%d", &number);
    printf("Fibonacci Series: ");
    j = fibonacci(number);
    printf("%d", j);
}

int fibonacci (int a)
{
    int num1 = 1, num2 = 1, k, i;
    for (i = 1; i <= a; ++i)
    {
        printf("%d, ", num1);
        k = num1 + num2;
        num1 = num2;
        num2 = k;
    }
    return 0;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 1
    You return a zero to j from the fibonnaci call and then print the 0. Remove the printf call and you get rid of it. Or better, do not return anything, because it doesn't matter – RoQuOTriX Nov 05 '19 at 15:12
  • I returned num1 and this produced the correct result. Oh well. – Caleb Barnett Nov 05 '19 at 15:14
  • Do you really understand what you are doing? – RoQuOTriX Nov 05 '19 at 15:15
  • Why your `fibonacci` function returns a value ? It seems like you don't need to return anything but you don't know about "return types". – patoglu Nov 05 '19 at 15:15
  • @RoQuOTriX No, I don't. But I really want to. – Caleb Barnett Nov 05 '19 at 15:16
  • Your j variable its unnused and you are printing at the end, thats it's your 0 – Horacio Nov 05 '19 at 15:18
  • @sushibossftw I learned that we are supposed to return something when using functions other than main. The last value was the only problem, so it likely had to do with me returning 0. When I didn't return anything, the last number was the number given by the user. – Caleb Barnett Nov 05 '19 at 15:19
  • @Horacio But j has been initialized and declared. Then it is printed. It had to do with the *fibonacci* function. – Caleb Barnett Nov 05 '19 at 15:20
  • Do you realize when you print what number and why? Try to understand what each of your printf statements does. You are using printf's in your for loop AND after the function itself – RoQuOTriX Nov 05 '19 at 15:22
  • 1
    Please don't edit your question to include a fix, rather answer your own question. That's how this site works. – Jabberwocky Nov 05 '19 at 15:40

1 Answers1

0

I learned that we are supposed to return something when using functions other than main.

If you learned that, you should look for a better learning source. You could well have written:

void fibonacci(int a)
{
    int num1 = 1, num2 = 1, k, i;
    for (i = 1; i <= a; ++i)
    {
        printf("%d, ", num1);
        k = num1 + num2;
        num1 = num2;
        num2 = k;
    }
}

Armali
  • 18,255
  • 14
  • 57
  • 171