How to print the first ten Fibonacci numbers using C#?

CsharpProgrammingServer Side Programming

For displaying the first ten numbers, firstly set the first two numbers.

int val1 = 0, val2 = 1;

Now, use a for loop from 2 to 10, to display first ten Fibonacci numbers −

for(i=2;i<10;++i) {
   val3 = val1 + val2;
   Console.Write(val3+" ");
   val1 = val2;
   val2 = val3;
}

The following is the complete code to display first ten Fibonacci numbers −

Example

 Live Demo

using System;
public class Demo {
   public static void Main(string[] args) {
      int val1 = 0, val2 = 1, val3, i, n;

      n = 10;

      Console.WriteLine("1st ten Fibonacci numbers:");
      Console.Write(val1+" "+val2+" ");

      for(i=2;i<n;++i) {
         val3 = val1 + val2;
         Console.Write(val3+" ");
         val1 = val2;
         val2 = val3;
      }
   }
}

Output

1st ten Fibonacci numbers:
0 1 1 2 3 5 8 13 21 34
raja
Published on 20-Aug-2018 12:38:10
Advertisements