Unsigned int in while loop

Hello Currently I'm reading a book on c++ algorithms and I stumbled upon the Fibonacci numbers and how to iterate through them
but I don't get 1 thing and that is it has a while loop which is really confusing.
because in it n decremented by 1 with no conditions.

my question is how does the loop stop and why isn't the loop an endless one I mean after 0 it should go to 4294967295 -1 and on on why doesn't this happen?




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>
#include <fstream>

using namespace std;

unsigned long fib(unsigned n)
{
    unsigned fn=1, fn_1=0, fn_2;

    while(n--)//this confuses me
    {
        fn_2=fn_1;
        fn_1=fn;
        fn=fn_1+fn_2;
    }
    return fn_1;
}

int main()
{
   unsigned long n = 4;
   cout<<fib(n);
}


Thank you!
zero is false in c++ (and, everything else is true)

so

int n = 10;

while(n--)

is the same as

while (n-- != 0)

Last edited on
Hello stonedviper,

The condition of a while or even a do/while loop boils down to either being true or false, i.e., true a number greater than zero or false zero.

So as long as "n" is greater than zero the condition is true. And when "n" becomes zero the while condition will fail and the while loop is passed over to the next line of coed.

Hope that helps,

Andy
Okay thank you!

That clarifies alot :)
Topic archived. No new replies allowed.