C++ Function Examples

1️⃣ مثال: جمع دو عدد

#include <iostream> using namespace std; int add(int a, int b) { return a + b; } int main() { int sum = add(10, 20); cout << "Sum = " << sum << endl; // خروجی: Sum = 30 }

2️⃣ مثال: چاپ آرایه

#include <iostream> using namespace std; void printArray(int arr[], int size) { for(int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } int main() { int numbers[] = {1, 2, 3, 4, 5}; int size = sizeof(numbers)/sizeof(numbers[0]); printArray(numbers, size); // خروجی: 1 2 3 4 5 }

3️⃣ مثال: بزرگترین عدد در آرایه

#include <iostream> using namespace std; int maxInArray(int arr[], int size) { int max = arr[0]; for(int i = 1; i < size; i++) { if(arr[i] > max) max = arr[i]; } return max; } int main() { int numbers[] = {10, 50, 20, 40, 30}; int size = sizeof(numbers)/sizeof(numbers[0]); cout << "Maximum: " << maxInArray(numbers, size) << endl; // خروجی: Maximum: 50 }

4️⃣ مثال: تغییر مقدار با Pass By Reference

#include <iostream> using namespace std; void square(int &num) { num *= num; } int main() { int a = 5; square(a); cout << "Squared: " << a << endl; // خروجی: Squared: 25 }

5️⃣ مثال: تابع با struct

#include <iostream> using namespace std; struct Student { string name; int age; }; void birthday(Student &s) { s.age += 1; } int main() { Student s1 = {"Alice", 20}; birthday(s1); cout << s1.name << " is " << s1.age << " years old." << endl; // خروجی: Alice is 21 years old. }

🔹 نکات کاربردی

  1. توابع باعث خوانایی و مدیریت بهتر کد می‌شوند.

  2. می‌توان چندین نوع پارامتر و مقادیر پیش‌فرض استفاده کرد.

  3. Pass By Reference برای تغییر داده‌های اصلی یا آرایه‌های بزرگ مفید است.

  4. Return می‌تواند انواع داده، struct، یا حتی pointer برگرداند.