// Calculate grade for multiple students
int marks1 = 85;
if (marks1 >= 90) grade1 = 'A';
else if (marks1 >= 80) grade1 = 'B';
// ... repeat for every student!
Problems: Repetitive code, hard to maintain, can't reuse logic.
char calculateGrade(int marks) {
if (marks >= 90) return 'A';
if (marks >= 80) return 'B';
if (marks >= 70) return 'C';
return 'F';
}
// Use it anywhere
cout << calculateGrade(85); // B
cout << calculateGrade(92); // A
Definition: A function is a reusable block of code with a name that performs a specific task.
int add(int a, int b) {
return a + b;
}
Parts:
int) - What type of data it returnsadd) - How to call itint a, int b) - Inputs it needs{}) - Code that executesreturn a + b) - Value sent back