error in ma program it shows the last digit twice.

#include<conio.h>
#include<stdio.h>
int main()
{
     int fib(int);
      int n,c,a=0,b=1;
     printf("enter a number: ");
     scanf("%d",&n);
     printf("%d %d ",a,b);
    c=fib(n);
    printf("%d ",c);
    getch();
}
int fib(int n)

{
int a=0,i,b=1,sum;

    for(i=0;i<n-2;i++)
    {
                      sum=a+b;
                      a=b;
                      b=sum;
                      printf("%d ",sum);
                      }

                      return(sum);
                      }

Dani AI

Generated

The duplicated last number comes from printing in two places: main prints the initial values and the returned value, while the helper fib() also prints each sum as it computes. As hinted, either stop printing inside the helper or stop printing the returned value in main. Prefer separating concerns: have computation routines return values and let main handle all output.

A simple, portable iterative example that prints the first N Fibonacci terms without duplication:

#include <stdio.h>

int main(void) {
    unsigned int n;
    unsigned long long a = 0, b = 1;

    if (scanf("%u", &n) != 1) return 1;

    if (n == 0) { printf("\n"); return 0; }

    printf("%llu", a);                 /* F0 */
    for (unsigned int i = 1; i < n; ++i) {
        printf(" %llu", b);            /* F1..F_{n-1} */
        unsigned long long next = a + b;
        a = b;
        b = next;
    }
    printf("\n");
    return 0;
}

If a pure function that returns F_n is required, use an iterative O(n) routine (no printing inside it). Naive recursion (the example from ) is simple but exponential time and can cause deep recursion for large n — memoization or dynamic programming turns that into linear time. The closed-form/Binet formula mentioned by can be handy but relies on floating-point math and will round incorrectly for larger indices; use big-integer libraries or fast-doubling (O(log n)) if truly large Fibonacci numbers are needed.

Practical notes: avoid nonstandard headers like <conio.h> and getch(); check scanf return values; choose types carefully (signed 64-bit is safe up to about F92, unsigned up to F93); and keep printing in one place to prevent duplicate output (either remove the printf after the call in main, or stop printing inside the helper).

Recommended Answers

All 6 Replies

The printf statement in main does the second?

Somewhat related, I found another (iterative) fibonacci function lately that is interesting:

long int fib(unsigned long int n) {
   return lround((pow(0.5 + 0.5 * sqrt(5.0), n) - 
                  pow(0.5 - 0.5 * sqrt(5.0), n)) / 
                 sqrt(5.0));
}

Given how fast Fibonacci numbers hit system limits, don't bother using an iterative approach. Use a recursive one instead. You will never overrun your stack, and it is a LOT easier to code correctly! :-)

for example

Example:

int fib (int n) 
{
   if (n <= 1)
     return n;
   else
     return fib(n - 1) + fib(n - 2);
 }

But the iterative approach is much better in terms of complexity! That is, for large n's the iterative version will be much faster than the recursive one.

Well, you can improve the naive recursive approach^^ with memoization but if you have never heard of Dynamic Programming, may be you can skip this for now.
But keep it at the back of your head and you may find this handy when you learn DP (if you're into a CS program, you will someday!)

Thanks NP! FWIW, I once wrote a Fibonacci program using exceptions, in order to test early standard C++ compiler exception handling. It was interesting how many failed the test! :-) I wish I could dig up the code (it sits on a floppy somewhere in my home office - written in the mid-1990's) as it really was quite neat. All my systems that still have floppy drives have been mothballed - I'm not sure they will even boot up! :-)

My pleasure, rubberman! Add a rep, maybe? :-)

And hey, good luck finding that old floppy! I'm sure people can learn a thing or two about exception handling and how to inmplement them with your code...

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.