الدوال والعودية في C# (.NET 6): دليل تفصيلي
Functions and Recursion in C#
Introduction: Why Do We Need Functions?
Imagine you make a sandwich every day. First, you take bread, then you spread butter, add cheese... If you had to write down all these steps from scratch every time, it would be very tedious. The same thing happens in programming: often we need to perform the same action many times (for example, adding two numbers or checking if a number is even).
A function is like a recipe. You write down what needs to be done once, give this recipe a name, and then you can use it again and again just by calling its name. In C#, we write functions to make code shorter, clearer, and to avoid repeating ourselves.
Basic Syntax of Functions in C#
A function in C# consists of several parts:
- Return type — what the function gives back (a number, text, or nothing if it's
void). - Function name — you make it up yourself.
- Parameters — the data the function takes as input (like ingredients for a sandwich).
- Function body — the actual code inside the curly braces
{ }.
// A simple function that adds two numbers
int Sum(int a, int b)
{
return a + b; // return is the answer the function gives back
}
// Usage
int result = Sum(5, 3);
Console.WriteLine(result); // Output: 8
Example 1: Family Budget (Sum of Incomes)
Let's write a function that takes two numbers (incomes) and returns their sum. This is a basic addition task.
using System;
class Program
{
// Function that calculates total income
static double CalculateTotal(double income1, double income2)
{
return income1 + income2;
}
static void Main()
{
Console.Write("Enter the first income: ");
double first = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the second income: ");
double second = Convert.ToDouble(Console.ReadLine());
double total = CalculateTotal(first, second);
Console.WriteLine($"Total income: {total}");
}
}
Example 2: Comparing Temperatures
The function takes two temperatures and returns the larger one. Here we use the conditional operator if inside the function.
static double MaxTemperature(double t1, double t2)
{
if (t1 > t2)
return t1;
else
return t2;
}
// In Main:
double temp1 = 25.5;
double temp2 = 30.1;
double max = MaxTemperature(temp1, temp2);
Console.WriteLine($"The higher temperature: {max}"); // 30.1
Example 3: Checking if a Number is Even
The function returns true or false. Such functions are called boolean functions.
static bool IsEven(int number)
{
// If the remainder of division by 2 is 0 — the number is even
return number % 2 == 0;
}
// In Main:
Console.Write("Enter the number of boxes: ");
int boxes = Convert.ToInt32(Console.ReadLine());
if (IsEven(boxes))
Console.WriteLine("The number is even, you can pack them in pairs!");
else
Console.WriteLine("The number is odd, you need one more box.");
Example 4: Reversing a String (Using a Function)
Here the function takes a string and returns the reversed string. We use a for loop.
static string ReverseString(string input)
{
string result = ""; // Empty string for the result
for (int i = input.Length - 1; i >= 0; i--) // Go from the end
{
result += input[i]; // Add each character
}
return result;
}
// In Main:
Console.Write("Enter a message: ");
string message = Console.ReadLine();
string reversed = ReverseString(message);
Console.WriteLine($"Reversed message: {reversed}");
What is Recursion?
Recursion is when a function calls itself. It's like a Russian nesting doll: inside a large doll, there is an identical but smaller one. Recursion is needed for tasks that can be broken down into similar but simpler sub-tasks.
Important: recursion must always have a stopping condition (base case), otherwise it will call itself infinitely, and the program will "hang".
Example 5: Finding the Minimum Element in a List (Using Recursion)
Imagine we have a list of temperatures for the day. We want to find the lowest one. Recursively: if the list has one element, that element is the minimum. If it has more, we compare the first element with the minimum of the rest of the list.
using System;
using System.Collections.Generic;
class Program
{
static int FindMin(List<int> numbers, int index)
{
// Base case: if we have reached the last element
if (index == numbers.Count - 1)
return numbers[index];
// Recursion: find the minimum in the remaining part
int minOfRest = FindMin(numbers, index + 1);
// Compare the current element with the minimum of the rest
if (numbers[index] < minOfRest)
return numbers[index];
else
return minOfRest;
}
static void Main()
{
List<int> temperatures = new List<int>() { 15, 12, 18, 10, 20, 8, 14 };
int minTemp = FindMin(temperatures, 0);
Console.WriteLine($"The lowest temperature: {minTemp}"); // 8
}
}
Common Beginner Mistakes
- Forgetting the
statickeyword — in simple console programs, functions in the Program class must bestatic, otherwise they cannot be called fromMain. - Not using
return— if a function is supposed to return a value, but there is noreturn, the compiler will give an error. - Infinite recursion — forgetting to write the exit condition. The function calls itself