Skip to content
ExamplesEspañolWorkspace →

Fibonacci Sequence

Prints the first terms of the Fibonacci sequence.

Level
Beginner
Topic:
Math
Concepts:
Input & output
Para
Math
Open in Codoritmo

Run, change and debug this example in your browser.

What you'll learn

Inside a Para loop, two variables move forward together: each term is the sum of the previous two. At the end, the ratio between terms approaches the golden ratio.

Code

fibonacci.psc · 20 lines
Algoritmo Fibonacci    Definir n, i, a, b, siguiente Como Entero    Escribir "¿Cuántos términos?"    Leer n    a <- 0    b <- 1    Escribir Sin Saltar "Primeros ", n, " términos: "    Para i <- 1 Hasta n Hacer        Escribir Sin Saltar a, " "        siguiente <- a + b        a <- b        b <- siguiente    FinPara    Escribir ""    // a y b son ahora los dos términos que siguen al último mostrado;    // su razón se acerca al número de oro (1.618...)    Si a > 0 Entonces        Escribir "Razón entre los dos términos siguientes: ", b / a    FinSiFinAlgoritmo

Flowchart

Each block in the flowchart matches one instruction in the code.

Algoritmo FibonacciSíNoAlgoritmo FibonacciAlgoritmo FibonacciDefinir n, i, a, b, siguiente Como EnteroDefinir n, i, a, b, siguienteComo EnteroEscribir "¿Cuántos términos?"Escribir "¿Cuántos términos?"Leer nLeer na <- 0a <- 0b <- 1b <- 1Escribir Sin Saltar "Primeros ", n, " términos: "Escribir Sin Saltar "Primeros", n, " términos: "Para i <- 1 Hasta n HacerPara i <- 1 Hasta nEscribir Sin Saltar a, " "Escribir Sin Saltar a, " "siguiente <- a + bsiguiente <- a + ba <- ba <- bb <- siguienteb <- siguienteEscribir ""Escribir ""Si a > 0 Entoncesa > 0Escribir "Razón entre los dos términos siguientes: ", b / aEscribir "Razón entre los dostérminos siguientes: ", b / aFinAlgoritmoFinAlgoritmo

Sample run

This is what the program shows when it runs. The answers typed by the user are highlighted.

¿Cuántos términos?User answer: 15Primeros 15 términos: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 Razón entre los dos términos siguientes: 1.6180327869

Complexity

How much work and memory it needs as the amount of data (n) grows.

Complexity
CaseCost
BestO(n)
AverageO(n)
WorstO(n)
MemoryO(1)

Challenge

Print only the even terms.

Show hint

Before writing a, check with a Si whether a MOD 2 = 0.

Open in Codoritmo