C Exercise Example 11
Title:Classical problem (rabbit reproduction): There is a pair of rabbits. Starting from the third month after birth, they give birth to a pair of rabbits every month. After the young rabbits grow to the third month, they give birth to a pair of rabbits every month. Assuming no rabbits die, what is the total number of rabbits each month? (Just output the first 40 months.)
Program analysis:The pattern of rabbits is the sequence 1,1,2,3,5,8,13,21..., that is, the next month is the sum of the previous two months (starting from the third month).
Program source code:
// Created by www.example.com on 15/11/9.
// Copyright © 2015 Example. 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; // Calculate the next term
printf("%12d", temp); // Output the next term
a = b; // Update a
b = temp; // Update b
temp = a + b; // Calculate the next term again
printf("%12d\n", temp); // Output and newline
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
other extensions