Csharp/C Sharp/Language Basics/Function Definition

Материал из .Net Framework эксперт
Версия от 11:39, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Catch StackOverflowException for recursive function

using System;
   
class MainClass
{
    public static void Main()
    {
        try
        {
            Recursive();
        }
        catch(StackOverflowException)
        {
            Console.WriteLine("The CLR is out of stack space.");
        }
    }
   
    public static void Recursive()
    {
        Recursive();
    }
}


Define function

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
public class Functions
 {
     static void Main()
     {
         Console.WriteLine("In Main! Calling SomeMethod()...");
         SomeMethod();
         Console.WriteLine("Back in Main().");
     }
     static void SomeMethod()
     {
         Console.WriteLine("Greetings from SomeMethod!");
     }
 }


Recursive Factorial method.

 

using System;
public class FactorialTest
{
   public static void Main( string[] args )
   {
      for ( long counter = 0; counter <= 10; counter++ )
         Console.WriteLine( "{0}! = {1}", counter, Factorial( counter ) );
   } 
   public static long Factorial( long number )
   {
      if ( number <= 1 )
         return 1;
      else
         return number * Factorial( number - 1 );
   } 
}


Recursive function in action

using System;
public class FactorialTest
{
   public static void Main( string[] args )
   {
      for ( long counter = 0; counter <= 10; counter++ )
         Console.WriteLine( "{0}! = {1}",
            counter, Factorial( counter ) );
   }
   public static long Factorial( long number )
   {
      if ( number <= 1 )
         return 1;
      else
         return number * Factorial( number - 1 );
   }
}


Recursive sum method

public class SumPrices {
  public static double Sum(double[] p, int start, int end) {
    if (start < end)
       return p[start] + Sum(p,start+1,end);
    else return 0;
  }
  public static void Main() {
    double[] prices = {1.3, 13.68, 314.919, 82.827, 363.949};
    System.Console.WriteLine("The sum is {0:C}", Sum(prices,0,prices.Length));
  }
}


Use a recursive method, travel, to journey from start to finish

using System;
public class Journey {
  private static String indent = "";
  
  public static void TakeOneStep(int step) {
    Console.WriteLine("{0}Taking step {1}", indent, step);
  }
  
  public static void Move(int start, int finish) {
    string oldIndent = indent;
    Console.WriteLine("{0}Starting move from {1} to {2}", indent, start, finish);
    if (start < finish) {
      TakeOneStep(start);
      indent += "   "; 
      Move(start+1, finish);
      indent = oldIndent;
    }
    Console.WriteLine("{0}Finishing move from {1} to {2}",indent, start, finish);
  }
  public static void Main(String [] args) {
    Move(1, 10);
  }
}