Using Recursive Method In C# Language

Introduction

Recursive method is a trick, which use to self calling. It means a method, which call itself, that is recursive method. How to use it? See in given below example.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace recursive_method_in_c_sarp

{

    class fact

    {

        public int result( int val)

        {

            int answre;

            if (val == 1)

            {

                return 1;

            }

            else

            {

                answre = result(val - 1) * val;   /* method result is call to it self*/

                return answre;

            }

        }

 

    }

    class Program

    {

        static void Main(string[] args)

        {

            fact f = new fact();

            Console.WriteLine(" Factorial of 4 is :{0}",f.result(4));

            Console.WriteLine(" Factorial of 5 is :{0}", f.result(5));

        }

    }

}


Output:


output.jpg


Ebook Download
View all
Learn
View all