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

C Language Examples - Fibonacci Sequence

C Language Examples - Fibonacci Sequence

C Language Examples C Language Examples

The Fibonacci sequence refers to a sequence like 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368........

Starting from the 3rd term, each term of this sequence equals the sum of the previous two terms.

Example - Outputting a specified number of Fibonacci sequence terms

#include

<

stdio.h

int

main

(

)

{

int

i

,

n

,

t1

=

0

,

t2

=

1

,

nextTerm

;

printf

(

"

How many terms to output:

"

)

;

scanf

(

"

%d

"

, &

n

)

;

printf

(

"

Fibonacci sequence:

"

)

;

for

(

i

=

1

;

i

<=

n

; ++

i

)

{

printf

(

"

%d,

"

,

t1

)

;

nextTerm

=

t1

t2

;

t1

=

t2

;

t2

=

nextTerm

;

}

return

0

;

}

Running result:



输出几项: 10

斐波那契数列: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Example - Outputting the Fibonacci sequence before a specified number

#include

<

stdio.h

int

main

(

)

{

int

t1

=

0

,

t2

=

1

,

nextTerm

=

0

,

n

;

printf

(

"

Enter a positive number:

"

)

;

scanf

(

"

%d

"

, &

n

)

;

// Display the first two terms

printf

(

"

Fibonacci sequence: %d, %d,

"

,

t1

,

t2

)

;

nextTerm

=

t1

t2

;

while

(

nextTerm

<=

n

)

{

printf

(

"

%d,

"

,

nextTerm

)

;

t1

=

t2

;

t2

=

nextTerm

;

nextTerm

=

t1

t2

;

}

return

0

;

}

Running result:



输入一个正数: 100

斐波那契数列: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

C Language Examples C Language Examples