C Sharp/Recursion

From Meshplex

Jump to: navigation, search
Image:Csharp_programming.gif

Main Home

Basics
C# Tutorial Home
C# - Introduction to Visual Studio IDE
Introduction to C#
C# - Overview
C# - Statements
C# - Data Types
C# - Variables
C# - Operators
C# - Flow Control
C# - Variables II
C# - Functions and Methods

C# - Classes and Objects I
C# - Enumerations
C# - Dates and Times
C# - Random Numbers

Advanced
C# - Inheritance
C# - Polymorphism
C# - Garbage Collection
C# - Operator Overloading
C# - Encapsulation
C# - Properties
C# - Indexers
C# - Exceptions
C# - GUI
C# - Delegates
C# - Events
C# - Components
C# - Multithreading
C# - Regular Expressions
C# - Graphics and Multimedia
C# - Files and Streams
C# - XML
C# - Database, SQL and ADO.NET
C# - ASP.NET Web Forms and Web Controls
C# - Web Services
C# - Network Programming
C# - Datastructures and Collections
C# - Enumerations and Iterators
C# - .NET Assemblies
C# - CLR
C# - Visual Studio Debugger
C# - Namespaces
C# - Generics
C# - MS Intermediate Language
C# - Deploying Windows Application

Contents

[edit] C# Recursion


C# recursion is the idea of a function calling itself. This may seem weird but this is a good feature to produce some elegant results. Recursion is common in advanced math and science where complicated calculations require recursion. We will provide a simple and easy example of C# recursion.



The programmer must have a condition in the recursive funtion to tell it to stop, otherwise it will go forever and the program will run out of memory.

[edit] Advantages of C# Recursion

  • Directory list programming
  • Mathmatics and science programming
  • Node programming
  • Some AI programming techniques
  • Forum programming


[edit] Disadvantages of C# Recursion

  • Memory hog
  • Can be unstable if not programmed correctly
  • If recursion reaches deep levels it can have a severe performance issue when unwinding

[edit] C# Recursion Tips

  • Specify a condition to end the recursion
  • Do not overuse recursion


Example: This code will count from 1 to 10 using recursion

using System;
class Program
{
    static void RecuriveFunction(int x)
    {
 
        if (x > 10)  //Condition to stop recursion
            return;  //Exit out of function
        else
        {
            Console.WriteLine(x);
            RecuriveFunction(x + 1);  //Call myself
        }
    }
 
    static void Main()
    {
        RecuriveFunction(1);
        Console.Read();
    }
}

Output:

1
2
3
4
5
6
7
8
9
10