0

I'm trying to build a program that asks a user for a number "k" and print a series of numbers lower than the number k. For example if the user writes 20 the output has to be:

0, 1, 1, 2, 3, 5, 8, 13

Instead I got:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181

This means that are printing 20 Fibonacci numbers.

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

unsigned int fib(unsigned int num)
{
    if (num == 0 || num == 1)
    {
        return num;
    }
    else
    {
        return (fib(num - 1) + fib(num - 2));
    }
}

int main()
{
    int k = 0;

    cout << "White a number k ";
    cin >> k;

    for (int i = 0; i < k; i++)
        cout << fib(i) << endl;

    return 0;
}

I tried using "break;" but is does not work. How can I break the loop?

anastaciu
  • 23,467
  • 7
  • 28
  • 53

2 Answers2

1

You are comparing the inputed k limit with the iterator i, so the input is read as the quantity of numbers in the fibonacci sequence you want to output, not the upper limit.

To do what you want you need to compare the limit k with the fib function returned result so that you can stop the loop as soon as the limit is exceeded.

Live demo

Keeping the for loop:

int main()
{
    int k = 0;
    int res = 0; // store the result of fib(i) to avoid duplicate calls

    cout << "White a number k: ";
    cin >> k;

    for (int i = 0; (res = fib(i)) < k; i++){ //assign fib(i) to res
        cout << res << endl;                  //when res is larger than k exits the loop
    }
    return 0;
}

Or using a while loop:

int main()
{
    int k = 0;
    cout << "White a number k: ";
    cin >> k;
    int res;
    int i = 0; //iterator

    while((res = fib(i++)) < k) { //assign result to res and compare it with the limit k
        cout << res << endl; //output the result while it's smaller than k
    }
    return 0;
}

Sample run:

White a number k: 20
0
1
1
2
3
5
8
13
anastaciu
  • 23,467
  • 7
  • 28
  • 53
0
  for (int i=0; i<k; i++){
      if(fib(i)<k)    //while fib(i) is less than k,it prints fib(i)            
       cout << fib(i) << endl;      
      else            //if number becomes greater than k,then it will break out from the loop.
       break;
    }    

Hope it helps!!

Amit Nandal
  • 118
  • 1
  • 6