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.

Google for 'cin' and C++.

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

Also, you're now using the C function

I think this belongs in C, I flagged it for a mod.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.