Fibonacci max at 100

i will try to explain this as best as i can. let say that the user input 100. i want it to stop when the fibonacci numbers added up to 100. not the 100th time.

how do i make it happen? i can't seem for figure out

(im a beginner at c++ so please take it easy on me)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    #include<iostream>
    using namespace std;
    int main()
    {
       int range, first = 0, second = 1, fibonicci=0;
       cout << "Enter the upper limit for fibonacci number: ";
       cin >> range;
      
       for ( int c = 0 ; c < range ; c++ )
       {
          if ( c <= 1 )
             fibonicci = c;
          else
          {
             fibonicci = first + second;
             first = second;
             second = fibonicci;
          }
          cout << fibonicci;
       }
       return 0;
    }
Do you mean:
1
2
3
4
sum = 0;
while ( sum < range ) {
  sum += ...
}
I'm not entirely sure what you mean. Do you mean to show the fibonacci number just before the limit, or when adding each and every fibonacci number is just less than the limit?

Assuming the former, change the condition of the loop from a for loop to something like while (fibonacci < range), and then subtract first from it to get the value before in the series (i.e. the one just before it went out of range).
sry forgot to include an example

Enter the upper limit for the Fibonacci number: 100
output would be something like this: 0 1 1 2 3 5 8 13 21 34 55 89
Last edited on
for ( int c = 0 ; c < range ; c++ )
will run "range time".
replace with while(fibo <= range) where, fibo is a fibonacci number.
That is still a loop. You want to continue as long as the latest computed Fibonacci number remains below the range. You should consider the do while loop.

Hint: Do not compute a number and then show it. Show the number and then compute next.
replace with while(fibo <= range) where, fibo is a fibonacci number.

I assumed fibo had at least been computed once. Same as do-while. Thought he'll understand.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
using namespace std;

int main()
{
   int range =100, first = 0, second = 1, fibonacci=0, c=0;

   while(true)
    {
     if(c>1)
      {
       fibonacci = first + second;
       first = second;
       second = fibonacci;
      }          
     else fibonacci = c;  
     c++;
     
	 if(fibonacci>=range) break;
	 cout << fibonacci << " ";	       
    }
       
    return 0;
}
Topic archived. No new replies allowed.