GeeksforGeeks » Interview Questions

A Fibonacci Question

(2 posts)
  • Started 9 months ago by nullpointer
  • Latest reply from kartik
  1. nullpointer
    Member
    Posted 9 months ago #

    #include<stdio.h>
    main()
    {
        int a,b,n,fib=0;
        a=0,b=1;
        scanf("%d",&n);
        if(n==0||n==1)
            printf("%d\n",n);
        while(n--!=0)
        {
    
            fib=a+b;
            a=b;
            b=fib;
            printf("%d+",fib);
    
        }
    }
    

    for n = 3 o/p is 1+2+3+
    how to remve that extra '+' at the end of 3 so that o/p become 1+2+3

  2. kartik
    Moderator
    Posted 9 months ago #

    You can split the last printf statement into two printf statements. See following modified code.

    #include<stdio.h>
    int main()
    {
        int a, b, n, fib=0;
        a = 0, b = 1;
        scanf("%d",&n);
        if (n==0 || n==1)
            printf("%d\n", n);
        while (n-- != 0)
        {
            fib = a + b;
            a = b;
            b = fib;
            printf("%d",fib);
            if(n != 0)
              printf("+");
        }
        return 0;
    }
    

Reply

You must log in to post.

RSS feed for this topic