Using Yield Statement for finding Factorial of a number

Rajnilari2015
Posted by in C# category on for Beginner level | Points: 250 | Views : 783 red flag

Yield is a contextual keyword introduced in C# 2.0, that helps in iterating over a collection with out creating an extra temporary collection object. In this article we will look into how to perform Factorial of a number using the "yield" statement.
Recommendation
Read Create PDF/XPS/Doc/Docx/Html documents with Spire.PDF before this article.

Introduction

Yield is a contextual keyword introduced in C# 2.0, that helps in iterating over a collection with out creating an extra temporary collection object. Under the hood, it creates a state machine which on the other hand remembers what the last value was on each additional cycle of the function and picks up the next value from there. The called function returns an object of type IEnumerable interface. In this article we will look into how to perform Factorial of a number using the "yield" statement.

Using the code

Let us first see how we can implement this in the traditional way by using the foreach loop

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int input = 5; //Factorial of the number to find
            int fact = 1; //a temporary variable to store the intermediate computed values
            
	    List<int> numbers = Enumerable.Range(1, input).ToList(); // intermediate collection that stores the range of numbers            

	    //the computation
            foreach (var number in numbers)

                    fact *= number;

	    //display the result
            Console.WriteLine("Factorial of {0} is {1}", input, fact);
            Console.ReadKey();
        }
    }
}

As can be figure out that, we are generating a list of sequential integers and storing that in an extra temporary collection object which is List<int> numbers. But we can avoid that by using the "Yield" statement. The below program will describe the same.

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int input = 5; //Factorial of the number to find
            int fact = 1; //a temporary variable to store the intermediate computed values            

            foreach (var number in Factorial(input))
            {
                fact *= number;
            }

            //display the result
            Console.WriteLine("Factorial of {0} is {1}", input, fact);
            Console.ReadKey();
        }

	//generate the range of numbers - one at each cycle
        public static IEnumerable<int> Factorial(int number)
        {
            int startIndex = 1;
		
            //loop continues till the condition becomes false
            while (startIndex <= number)
            {                
                yield return startIndex;
                startIndex++;
            }         
        }
    }
}

A careful observation will reveal that the System.Linq namespace is no longer in use. The function Factorial returns an object and it implements the IEnumerable interface. When the calling function started foreach-ing/looping over this object, the Factorial function is called again until it "yields". On each call of yield statement, control is returned to the caller but it ensures that the callee's state is maintained .This is achieved since the yield statement creates a state machine which on the other hand remembers what the last value was on each additional cycle of the function (Factorial) and picks up the next value from there. The cycle continues till the condition becomes false.

The result is as under.

Factorial of 5 is 120

References

yield (C# Reference)

Conclusion

Hope we have all enjoyed the journey with yield and understood how it works. Thanks for reading.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)