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


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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

507 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements