"Algorithm Notes" Section 2.4-C/C++ Quick Start -> Loop Structure Example 5-8 Fibonacci Sequence

Example 5-8 Fibonacci sequence

Title description
Enter a positive integer n to find the nth number in the Fibonacci sequence. The characteristics of Fibonacci sequence: the first and second numbers are 1,1. Starting from the third number, the summary is the sum of the previous two numbers. That is: the
Insert picture description here
input of the positive integer n is not more than 50.
Enter
a positive integer not more than 50 to
output
the nth number of the Fibonacci sequence, and output a newline at the end.
Sample input Copy
20
Sample output Copy
6765

#include <stdio.h>

int main(void) {
    
    
    int a;
    int b[50] = {
    
    1, 1};
    scanf("%d", &a);
    if (a == 1 || a == 2) {
    
    
        printf("%d", b[0]);
    } else if (a > 2) {
    
    
        for (int i = 2; i < a; ++i) {
    
    
            b[i] = b[i - 1] + b[i - 2];
        }
    }
    printf("%d", b[a - 1]);
    return 0;
}

Guess you like

Origin blog.csdn.net/DoMoreSpeakLess/article/details/109881140
Recommended