COMP2243 - Programming and Problem Solving

Syllabus Software Installation Assignments Tests
Lectures and Labs
**Back to Full Menu**

Repetitions/Loops WhileLoop.java LoopWithCounter.java LoopWithSentinel.java LoopWithFlag.java SimpleInterest.java Factorial.java Fibnonacci.java PrimeNumber.java GCD.java PopulationGrowth.java ForLoop.java DoWhileLoop.java FileIO_Tickets.java FileIO_Salary.java NestedLoop.java



Fibonacci Program


Description

The Fibonacci sequence of numbers start with 0 and 1, then the following number is the addition of two previous numbers.

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,144, 233, 377,...

This program inputs an index (position) and then calculates Fibonacci number at this index.

Associated Concepts:

while loop

Algorithm:

Input an index (position) from the keyboard

If index is 0 or 1

    Set result to index

Set two previous number p1 to 0 and p2 to 1

Set the control variable i to 2

Use a while loop to check the control variable i (as long as i is less than or equal to index)

    Calculate result by adding p1 and p2

    Update p1 and p2 by advancing forward

    Increment i by 1

Print the result after the loop is ended

Source Code



Sample Run



Video