PART 1: FUNCTIONS (Discuss Card)

Why Functions?

The Problem

// 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.

The Solution

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.


Function Anatomy

int add(int a, int b) {
    return a + b;
}

Parts:

  1. Return Type (int) - What type of data it returns
  2. Name (add) - How to call it
  3. Parameters (int a, int b) - Inputs it needs
  4. Body ({}) - Code that executes
  5. Return (return a + b) - Value sent back

Types of Functions

With Return Value