I've just been trying to put together a small piece of code to display the Fibonacci series up to the nth term, where n is defined by the user.

I have got it working in a way, it is displaying the series up the the nth term where n is defined within the code, however I can't figure out how to get it so the user enters a value and this is used as n.

If anybody could help me along I would be extremely grateful.

Shown below is my code to get it to show the series up to the nth term, with n defined in the For loop.

#include<stdio.h>

int main()
{
    int i,j,k,n;

    i=0;
    j=1;
    printf("%d    %d    ",i,j);
    for(n=0;n<=5;n++)
    {
    k=i+j;
    i=j;
    j=k;
    printf("%d    ",k);
    }
    
}

Have you covered scanf in class? (arguably you should use a fgets/sscanf pair, but I don't know if you've learned those yet)

Read in an integer value using scanf(call it n_user or something) and replace that hard coded 5 that you have there with n_user.

Edited 5 Years Ago by jonsca: n/a

Google for 'cin' and C++.

Also, you're now using the C function for output (printf), in C++ we generally use 'cout'.

Have you covered scanf in class? (arguably you should use a fgets/sscanf pair, but I don't know if you've learned those yet)

Read in an integer value using scanf(call it n_user or something) and replace that hard coded 5 that you have there with n_user.

Ta very much.

I had tried doing that before but I was obviously making some simple error, but you posting this made me try it again and it worked.

I think I was putting:

scanf("%d",n_user);

rather than:

scanf("%d",&n_user);

as it should have been.

This question has already been answered. Start a new discussion instead.