Fibonacci Number at a Given Position
This program calculates the Fibonacci number at a specified position in the sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. This program takes a position as input and outputs the Fibonacci number at that position.
Code Breakdown
Algorithm
- Start
- Input Position: Read the value of
n
(position) from the user. - Check Position:
- If
n < 1
, print "Invalid position" and exit.
- If
- Initialize Variables:
- Set
a = 1
,b = 0
, andi = 0
.
- Set
- Compute Fibonacci Number:
- Loop until
i
is less thann
:- Calculate
c = a + b
. - Update
a
tob
. - Update
b
toc
. - Increment
i
.
- Calculate
- Loop until
- Display Result:
- Print the Fibonacci number at position
n
.
- Print the Fibonacci number at position
- End
Code Explanation
Example Flowchart
Start
|
V
Input position n
|
V
Is n less than 1?
/ \
/ \
Yes No
/ |
V V
Print "Invalid position" Initialize
| a = 1, b = 0, i = 0
V |
End |
V
Loop while i < n
/ \
/ \
V V
Compute c = a + b Update a = b, b = c
| |
V V
Increment i Print Fibonacci number at position n
| |
V V
End End