C language: Use recursive method to find the first 40 numbers of Fibonacci sequence: 1, 1, 2, 3, 5, 8,...

analyze:

    First, at the beginning of the code, include the <stdio.h> header file. This header file provides input and output functions.
    Then, four variables are defined: f, f1, f2 and i. f1 and f2 are the first two numbers of the Fibonacci sequence, initialized to 1. f is the number currently being calculated.
    Next, use the printf function to print out the values ​​of f1 and f2, and use the %10d format control character to ensure that the output width is 10 characters.
    Then, use a for loop to iterate through each number in the sequence from 3 to 40. In the loop body, calculate the new number through f=f1+f2, update f1 to f2, and update f2 to f.
    If i is divisible by 4, use printf("\n") to break the line so that the output results are aligned on the line.

Code:

#include<stdio.h>
int main()
{
	long f,f1,f2;int i;
	f1=1;f2=1;
	printf("%10d%10d",f1,f2);
	for(i=3;i<=40;i++) 
	{
		f=f1+f2;
		printf("%10d",f);
		f1=f2;
		f2=f;
		if(i%4==0)
		printf("\n");
	}
}

operation result:

Guess you like

Origin blog.csdn.net/m0_63002183/article/details/134706463