Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 11

C Exercise 11

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Classical problem (rabbit breeding): A pair of rabbits produces a new pair every month starting from the 3rd month after birth. Each young rabbit, once it reaches the third month, also produces a pair every month. Assuming no rabbits die, how many rabbits are there in total each month? (Output the first 40 months.)

**Analysis:** The rabbit population follows the sequence 1, 1, 2, 3, 5, 8, 13, 21..., i.e., each month's total is the sum of the previous two months (starting from the third month).

Program source code:

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. All rights reserved.

//

// This program prints the first 20 terms of the Fibonacci sequence

#include

<

stdio.h

int

main

(

)

{

int

a

=

1

,

b

=

1

,

temp

,

i

;

printf

(

"

%12d%12d

"

,

a

,

b

)

;

// Output the first two terms

for

(

i

=

3

;

i

<=

20

;

i

+=

2

)

{

temp

=

a

b

;

// Compute the next term

printf

(

"

%12d

"

,

temp

)

;

// Output the next term

a

=

b

;

// Update a

b

=

temp

;

// Update b

temp

=

a

b

;

// Compute the next term again

printf

(

"

%12d

\

n

"

,

temp

)

;

// Output and start a new line

a

=

b

;

// Update a

b

=

temp

;

// Update b

}

return

0

;

}

The output of the above example is:



           1           1           2           3

           5           8          13          21

          34          55          89         144

         233         377         610         987

        1597        2584        4181        6765

       10946       17711       28657       46368

       75025      121393      196418      317811

      514229      832040     1346269     2178309

     3524578     5702887     9227465    14930352

    24157817    39088169    63245986   102334155

100 Classic C Language Examples 100 Classic C Language Examples