Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fibonacci Sequence in VB.net using loop

Please could you help me with displaying the first 10 Fibonacci numbers. My code displays the following result: 1, 2, 3, 5, 8, 13, 21, 34, 55 and I need it to also display the first two Fibonacci numbers (0 and 1). How would I do that?

Public Class Form1
  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim a As Integer = 0
    Dim b As Integer = 1
    Dim fib As Integer = 0

    Do
      fib = a + b
      a = b
      b = fib
      Label1.Text = Label1.Text + fib.ToString & ControlChars.NewLine
    Loop While fib < 55
  End Sub
End Class

Where in professional programming would you need to use Fibonacci sequences?

like image 370
Wannabe Avatar asked Apr 03 '11 18:04

Wannabe


People also ask

What is fibonacci series in VB net?

Fibonacci series means, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 etc. The first two numbers of Fibonacci series are 0 and 1. Like. 0+1=1, 1+1=2, 1+2=3.


2 Answers

Just add

Label1.Text = Label1.Text + a.ToString & ControlChars.NewLine
Label1.Text = Label1.Text + b.ToString & ControlChars.NewLine

before the Do ... while.

For applications linked to Fibonacci numbers see : Fibonacci: Applications

like image 64
log0 Avatar answered Oct 23 '22 04:10

log0


Instead of calculating the next in sequence number and then adding the results to the output, do it in reverse order:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim a As Integer = 0
    Dim b As Integer = 1
    Dim fib As Integer 

    Do
        Label1.Text += a.ToString & ControlChars.NewLine
        fib = a + b
        a = b
        b = fib
    Loop While a <= 55

End Sub
like image 42
Anax Avatar answered Oct 23 '22 05:10

Anax