0

I have written the following code to print the first 10 numbers in a Fibonacci sequence. I am expecting an output of 0,1,1,2,3,5,8,13,21,34. Instead I get 0,1,2,3,5,8,13,21,34,55. Here is the code -

var a = 0
var b = 0
var i = 0

while(i < 10) {
  val c = a +b
 a = b
 b = c
 i = i + 1
 if (a < 1) a = 1

println(b)
 }
J. Chavez
  • 1
  • 1
  • 1
    Possible duplicate of [Generate a sequence of Fibonacci number in Scala](https://stackoverflow.com/questions/9864497/generate-a-sequence-of-fibonacci-number-in-scala) – jwvh Jun 15 '17 at 19:23

2 Answers2

0

This should work:

var a = 0 
var b = 1 
var i = 0 

while(i < 10) {
  println(a)
  val c = a + b 
  a = b 
  b = c 
  i = i + 1 
}

but this is not functional and so not really scala

perreal
  • 94,503
  • 21
  • 155
  • 181
0

Here is a recursive solution that shows off some basic Scala features:

// Function definitions can have types with default values
def fib(a: Int = 0, b: Int = 1, count: Int = 2): List[Int] = {

  // Calculate the next value
  // In functional programming we prefer immutability so always try to use val instead of var
  val c = a + b

  // Stopping criteria, send back a list containing the latest value
  if (count >= 10) {
    List(c)
  }

  // If this is the first iteration create the first few fibonacci numbers, and make a recursive call
  // Adding one list to another is done using the ++ function
  else if (a == 0 && b == 1) {
    List(a, b, c) ++ fib(b, c, count + 1)
  }

  // If this wasn't the first iteration, just add the latest element and make the recursive call
  else {
    c +: fib(b, c, count + 1)
  }
}

// Since we gave default values the function parameters, you don't need to pass any when you call the function here
println(fib())
Tyler
  • 17,669
  • 10
  • 51
  • 89