רקורסיות
רקורסיה (באנגלית: Recursion), היא מתודה, אשר קוראת לעצמה.
הנושא קשה, בגלל זה יש הרבה מתכנתים שלא יודעים זאת. אך בגלל שזהו נושא חשוב, מומלץ ללמוד זאת.
רקורסיה פשוטה
בואו נתחיל ממשהו פשוט.
נבנה מתודה בתוך המחלקה הראשית אשר קוראת לעצמה.
לדוגמה:
JAVA
קוד PHP:
public class Recursion {
private static void Method(){
System.out.println("Print line . . .");
Method();
}
public static void main(String args[]){
Method();
}
}
C#
קוד PHP:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
private static void Method()
{
Console.WriteLine("Print line . . .");
Method();
}
static void Main(string[] args)
{
Method();
Console.Read();
}
}
}
C++
קוד PHP:
#include <iostream>
using namespace std;
class Method{
public:
Method(){
cout << "Print line . . ." << endl;
Method();
}
};
int main()
{
Method m;
return 0;
}
והעיקרון ברור.
אם נשים לב, בכל פעם שהרצנו את התוכנה, היא פעלה לכמה שניות ואז קרסה (או הפסיקה לעבוד).
זה בגלל שאנו משתמשים בקריאה חוזרת בכל פעם למתודה בלי הפסקה.
כל פעם שאנו קוראים לפונקציה, המחשב זוכר את הפעולות שהיינו לפני, כל המשתנים וכ'ו.
שאנחנו קוראים לפונקציה כך, בלי סוף, המחשב נכנס כל פעם עוד פעם ועוד פעם לתוך הפונקציה עד שהוא קורס.
ש: אז אם אנחנו רוצים להשתמש ברקורסיה, איך אנחנו עושים בלי שהמחשב יקרוס?
ת: זה פשוט. אנחנו רק צריכים להציב פעולת בדיקה, שהמחשב לא יקרא לאותה פונקציה שוב ושוב.
לדוגמה:
JAVA
קוד PHP:
public class Recursion {
private static void Method(int i){
System.out.println("Print line " + i + " . . .");
if(i < 20)
Method(i+1);
}
public static void main(String args[]){
Method(1);
}
}
C#
קוד PHP:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
private static void Method(int i)
{
Console.WriteLine("Print line " + i + " . . .");
if(i < 20)
Method(i+1);
}
static void Main(string[] args)
{
Method(1);
Console.Read();
}
}
}
C++
קוד PHP:
#include <iostream>
using namespace std;
class Method{
public:
Method(int i){
cout << "Print line " << i << " . . ." << endl;
if(i < 20)
Method(i+1);
}
};
int main()
{
Method m(1);
return 0;
}
אז לא כזה קשה אה? 
בהצלחה!