الدوال والعودية في C++17: دليل شامل
Functions and Recursion in C++
Introduction: why do we need functions?
Imagine you are writing a program for a weather station. You need to compare two temperatures 10 times and find the larger one. If you write the comparison code from scratch each time, the program will become huge and confusing. Functions are like small "bricks" or "tools". You create a tool once, and then use it as many times as you want.
Recursion is a special technique where a function calls itself. It's like a Russian nesting doll: inside a large doll, there is a smaller identical one hidden. Recursion helps solve problems that break down into identical small steps.
Basic function syntax
A function is a block of code that has a name. To create a function, write:
return_type function_name(parameters) {
// function code
return result;
}
Example: a function that adds two numbers (like in the "Family Budget" problem):
#include <iostream>
using namespace std;
int summa(int a, int b) { // function takes two numbers, returns their sum
return a + b;
}
int main() {
int x, y;
cout << "Enter two incomes: ";
cin >> x >> y;
int result = summa(x, y); // call the function
cout << "Total sum: " << result << endl;
return 0;
}
Program output:
Enter two incomes: 500 300
Total sum: 800
Functions with conditions (temperature comparison)
Inside a function, you can use if to return one of two values:
#include <iostream>
using namespace std;
double maxTemperature(double t1, double t2) {
if (t1 > t2) {
return t1;
} else {
return t2;
}
}
int main() {
double temp1, temp2;
cout << "Enter two temperatures: ";
cin >> temp1 >> temp2;
double result = maxTemperature(temp1, temp2);
cout << "Higher temperature: " << result << endl;
return 0;
}
Program output:
Enter two temperatures: 36.6 38.2
Higher temperature: 38.2
Functions returning true/false (even number check)
Such functions are called boolean functions. They return true or false:
#include <iostream>
using namespace std;
bool isEven(int number) {
if (number % 2 == 0) {
return true;
} else {
return false;
}
}
int main() {
int boxes;
cout << "How many boxes were produced? ";
cin >> boxes;
if (isEven(boxes)) {
cout << "The number is even, can be packed in pairs." << endl;
} else {
cout << "The number is odd, one box is extra." << endl;
}
return 0;
}
Program output:
How many boxes were produced? 101
The number is odd, one box is extra.
Recursion: a function calls itself
Recursion is when a function calls itself from within itself. Important: there must be a base case (stopping condition), otherwise the program will loop infinitely.
Example: recursive string reversal (like in the "String Reverse" problem):
#include <iostream>
#include <string>
using namespace std;
void reverseString(string s) {
// Base case: if the string is empty, exit
if (s.length() == 0) {
return;
}
// Recursive step: print the last character, then call for the string without the last character
cout << s[s.length() - 1];
reverseString(s.substr(0, s.length() - 1));
}
int main() {
string text;
cout << "Enter a string: ";
getline(cin, text);
cout << "Reversed: ";
reverseString(text);
cout << endl;
return 0;
}
Program output:
Enter a string: Hello
Reversed: olleH
Finding the minimum in a list (using recursion)
Imagine you have an array of temperatures for the day. Recursion will help find the lowest temperature:
#include <iostream>
using namespace std;
int findMin(int arr[], int size) {
// Base case: if the array has one element, it is the minimum
if (size == 1) {
return arr[0];
}
// Find the minimum in the remaining part
int minOfRest = findMin(arr, size - 1);
// Compare the last element with the minimum of the rest
if (arr[size - 1] < minOfRest) {
return arr[size - 1];
} else {
return minOfRest;
}
}
int main() {
int temps[5] = {22, 18, 25, 15, 20};
int minTemp = findMin(temps, 5);
cout << "Minimum temperature for the day: " << minTemp << " degrees" << endl;
return 0;
}
Program output:
Minimum temperature for the day: 15 degrees
Common beginner mistakes
- Forgot return — a function must return something if it does not have a void type. Otherwise, the program will output garbage or an error.
- Infinite recursion — if you don't write a base case (stopping condition), the function will call itself forever, and the program will "freeze".
- Mixed up arguments — when calling a function, the order of numbers matters. If the function expects (a, b), but you pass (b, a), the result may be incorrect.
- Modifying global variables inside a function — it's better to pass everything through parameters to avoid confusion.
Final example: family budget with a check
Let's write a program that takes incomes, checks if the sum is even, and outputs the result. We'll use two functions:
#include <iostream>
using namespace std;
// Function for addition
int add(int a, int b) {
return a + b;
}
// Function for even number check
bool isEven(int num) {
return num % 2 == 0;
}
int main() {
int income1, income2;