Calculate Fibonacci Series using C# programming

Hello mates,
This is one of the most asked question in interviews, calculating and printing Fibonacci series.
Let’s first try the iterative approach that is simple and prints all the Fibonacci series by passing the length.
Please note that we are starting the series from 0 (instead of 1).
  • public static voidFibonacci_Iterative(int len)
  • {
  •     int a = 0, b = 1, c = 0;
  •     Console.Write(“{0} {1}”, a,b);
  •     for (int i = 2; i < len; i++)
  •     {
  •         c= a + b;
  •         Console.Write(” {0}”, c);
  •         a= b;
  •         b= c;
  •     }
  • }

Test Results:

Input: Fibonacci_Iterative(9);
Output:
We can also use the recursive way to print the series against the length as below.
  • public static voidFibonacci_Recursive(int len)
  • {
  •    Fibonacci_Rec_Temp(0, 1, 1, len);
  • }
  • private static voidFibonacci_Rec_Temp(int a, int b, int counter, int len)
  • {
  •     if (counter <= len)
  •     {
  •         Console.Write(“{0} “, a);
  •         Fibonacci_Rec_Temp(b, a + b, counter+1, len);
  •     }
  • }
Here we have used two functions just to only the length as an input parameter. In the second method 4 parameters are required since we need to continue changing the variable’s position (in other words a -> b and b -> a + b).
We also need to increment the counter in each recursion call and to compare it with the length and continue the loop until it exceeds the length parameter.
Test Results:
Input: Fibonacci_Recursive(11);
Output:

Calculate nth Fibonacci number

Calculating the nth Fibonacci number is not difficult, we just need to the value with the right index.
We will first have a look at an iterative approach.
Here we are using an integer array to keep the Fibonacci numbers until n and returning the nthFibonacci number.
  • public static int GetNthFibonacci_Ite(int n)
  • {
  •     int number = n – 1; //Need to decrement by 1 since we are starting from 0
  •     int[] Fib = new int[number + 1];
  •     Fib[0]= 0;
  •     Fib[1]= 1;
  •     for (int i = 2; i <= number;i++)
  •     {
  •        Fib[i] = Fib[i – 2] + Fib[i – 1];
  •     }
  •     return Fib[number];
  • }
Test Results:
Input: GetNthFibonacci_Ite(4);
Output:
We can also look for a recursive version of that. The only thing to consider is, here we need to a number less than 1 to get the nth Fibonacci number.
For example if we want the 8th Fibonacci number then we need to 8-1 (in other words 7) as an input (we can also create a -through method alternatively).
  • public static int GetNthFibonacci_Rec(int n)
  • {
  •     if ((n == 0) || (n == 1))
  •     {
  •         return n;
  •     }
  •     else
  •         returnGetNthFibonacci_Rec(n – 1) + GetNthFibonacci_Rec(n – 2);
  • }
Test Results:
Input: GetNthFibonacci_Rec(8-1);
Output:
Please inform me of your comments/suggestions or if you have any better way to do it.

Working With Async Main In C# 7.1

Hello folks!

I am here to present the series related to C# 7.1’s new features. In the first part, we will be going through one of the important features called async main.

async main

Starting with C# 7.1, the main function that is the entry point of the application can have async. Before C# 7.1, the main function could have a return type as either void or int; however now, it also supports Task and Task<int>.

Main overrides (Before C# 7.1) Main overrides (In C# 7.1)
  • static void Main();
  • static int Main();
  • static void Main(string[] args);
  • static int Main(string[] args);
  • static void Main();
  • static int Main();
  • static void Main(string[] args);
  • static int Main(string[] args);
  • static Task Main();
  • static Task < int > Main();
  • static Task Main(string[] args);
  • static Task < int > Main(string[] args);

Let’s take a few examples to understand more.

Before C# 7.1, when you wanted to call async method from Main, you needed to add some boilerplate code but now, C# compiler does it for you and, in turn, enforces crisp coding by adding the required code automatically.

Let’s try to understand this by a simple example as following.

Before C# 7.1

  • using System.Threading.Tasks;
  • using static System.Console;
  • namespace CSharp7PlusDemo
  • {
  •     class Program
  •     {
  •         static void Main(string[] args)
  •         {
  •             Title = “C# 7.1 demo”;
  •             WriteLine($“Hello Prakash!!, I am from < C# 7.1 at {System.DateTime.Now}”);
  •             Task.Delay(2000).GetAwaiter().GetResult();
  •             WriteLine($“Hello Prakash!!, I am from < C# 7.1 at {System.DateTime.Now}”);
  •         }
  •     }
  • }

Output

Output

In C# 7.1

  • using System.Threading.Tasks;
  • using static System.Console;
  • namespace CSharp7PlusDemo
  • {
  •     class Program
  •     {
  •         static async Task Main(string[] args)
  •         {
  •            WriteLine($“Hello Prakash!!, I am from C# 7.1 at {System.DateTime.Now}”);
  •            await Task.Delay(2000);
  •            WriteLine($“Hello Prakash!!, I am from C# 7.1 at {System.DateTime.Now}”);
  •         }
  •     }
  • }

Output

Output

As you can see that Task.Delay is adding 2 seconds. Now, C# 7.1 syntax is crispier and easy to use.

So we just looked at how we could use the Task with Main. Now, let’s take another example where we will demonstrate the use of Task<int>.

Here, we will call another async method (FactorialAsync) from Main.

  • using System.Threading.Tasks;
  • using static System.Console;
  • namespace CSharp7PlusDemo
  • {
  •     class Program
  •     {
  •         static async Task<int> Main(string[] args)
  •         {
  •             Title = “C# 7.1 demo”;
  •             var number = 5;
  •             WriteLine($“Factorial of {number}: {await FactorialAsync(number)}”);
  •             return 0;
  •         }
  •         private static Task<int> FactorialAsync(int n)
  •         {
  •             return Task.Run(() => Cal(n));
  •             int Cal(int i)  //Local function
  •             {
  •                 if (i == 1)
  •                 {
  •                     return 1;
  •                 }
  •                 else
  •                 {
  •                     return i * Cal(i – 1);
  •                 }
  •             }
  •          }
  •      }
  • }

Output

Output

You can also see that in the above example, we have used a Local function that is the feature of C# 7.0. Moreover, we can also use expression-bodied method (introduced as part of C# 6.0) to call the async method directly from Main, as following.

static async Task Main(string[] args) => WriteLine($“Factorial: {await FactorialAsync(5)}”);

Output

Output

Conclusion

In this article, we have looked at one of the quite useful features “async main”, introduced as part of C# 7.1. We have seen how to use Task and Task<int> with Main. On the sideline, we have also seen the use of Local function and expression bodied method.

Hope you liked the article. I look forward to your comments/suggestions.

References

  • https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-1
  • https://blogs.msdn.microsoft.com/dotnet/2017/10/31/welcome-to-c-7-1/

Threads Inception in .NET

Hello guys,

Threading in .Net is an important topic. I have seen people unable to understand the nuances of processes, threads and how they are related in .Net and also in general.

In the series of articles around threading, I will try to present the concepts in the simplest way possible so that it can knock to your head directly and help you understand easily.

Threading is a broad topic that goes with operating systems. So before beginning the threading in .Net let’s understand a few core or underlying concepts as in the following.

How applications and processes are related

When we start an application, system resources and memory are assigned to it. The separation of these boundaries are based on memory and the resources are called a process.

An application can be allocated one or more processes, where each process is differentiated based on allocated resources, data and execution code.


Processes

A process can be defined as an instance of the application. While running it uses assigned program code, system resources and data. A process further can be broken into more than one thread based on application design and the operating system of the machine.

Threads

A thread can be defined as the smallest possible part of the process that can be handled or controlled independently by a scheduler. If I make an analogy to it then you can relate it to atom in the world of matters/particles.

How processes and threads are related

Every thread is a part of a process. Multiple threads within a process share the memory, execution instruction, context data and other system resources.

The following picture explains the relationship among applications, processes and threads.

How threading works internally

As said above, each process has its own execution instruction/sequence, context, memory and other system resources. The part or constituents that makes threads to work can be defined as in the following.

  • Registers (in the CPU)
  • Memory Stack
  • Container to store threads state/context (in other words TLS)

TLS

I assume you understand what context switching is in threading. In simple words, it’s switching the focus to various threads involved in the system based on certain algorithms (you might have heard of Round Robin and so on). In this scenario, the outgoing thread needs to store its state information to be able to start form the same place (again when it gets the slot). Basically this is done by TLS that uses a program counter that tells the thread which instruction to execute next.

Multithreading

Well, that’s enough for the first tutorial. 🙂 I will explain multithreading in the next article.

Please share your comments.