Think of functions like recipes in a cookbook. Instead of writing out how to make chocolate chip cookies every time you want them, you just refer to the recipe. Functions let you write code once and use it many times!
A function has four main parts, like a machine with input, processing, and output!
// 1. Simple function with no parameters
void printWelcome() {
cout << "Welcome to the program!" << endl;
cout << "Let's learn functions!" << endl;
}
// 2. Function with parameters
void greetUser(string name, int age) {
cout << "Hello, " << name << "!" << endl;
cout << "You are " << age << " years old." << endl;
}
// 3. Function that returns a value
int square(int number) {
return number * number;
}
// 4. Function with multiple parameters and return
double calculateBMI(double weight, double height) {
return weight / (height * height);
}
// 5. Using the functions
int main() {
printWelcome(); // Call function with no parameters
greetUser("Alice", 25); // Call with parameters
int result = square(5); // Store return value
cout << "5 squared is: " << result << endl;
double bmi = calculateBMI(70, 1.75);
cout << "BMI: " << bmi << endl;
return 0;
}
When you call a function, it's like taking a detour - you pause the main road, take the function path, then return where you left off!
Pass by value is like giving someone a photocopy - they can mark it up without affecting your original. Pass by reference is like giving them your actual document!
// Pass by value - original unchanged
void tryToDouble(int num) {
num = num * 2;
cout << "Inside function: " << num << endl;
}
// Pass by reference - original changed
void actuallyDouble(int &num) {
num = num * 2;
cout << "Inside function: " << num << endl;
}
// Swap function - classic reference example
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
// Using const reference for large objects (efficient, read-only)
void printArray(const int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int x = 10;
tryToDouble(x);
cout << "After tryToDouble: " << x << endl; // Still 10
actuallyDouble(x);
cout << "After actuallyDouble: " << x << endl; // Now 20
int a = 5, b = 8;
swap(a, b);
cout << "a=" << a << ", b=" << b << endl; // a=8, b=5
return 0;
}
Function overloading is like having multiple tools with the same name but different uses - a "cut" function might cut paper, fabric, or video!
// Different parameter types
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
// Different number of parameters
int add(int a, int b, int c) {
return a + b + c;
}
// Different parameter order
void display(int num, string text) {
cout << "Number: " << num << ", Text: " << text << endl;
}
void display(string text, int num) {
cout << "Text: " << text << ", Number: " << num << endl;
}
int main() {
cout << add(5, 3) << endl; // Calls int version: 8
cout << add(5.5, 3.2) << endl; // Calls double version: 8.7
cout << add(1, 2, 3) << endl; // Calls three-parameter version: 6
display(42, "Answer"); // Number: 42, Text: Answer
display("Answer", 42); // Text: Answer, Number: 42
return 0;
}
Default parameters are like restaurant orders - "I'll have the usual" means you get your default choice!
// Function with default parameters
void greet(string name, string greeting = "Hello") {
cout << greeting << ", " << name << "!" << endl;
}
// Multiple defaults (must be rightmost)
void createWindow(int width = 800, int height = 600, string title = "My Window") {
cout << "Creating " << width << "x" << height << " window: " << title << endl;
}
int main() {
greet("Alice"); // Uses default: "Hello, Alice!"
greet("Bob", "Hi"); // Uses provided: "Hi, Bob!"
createWindow(); // All defaults: 800x600 "My Window"
createWindow(1024, 768); // Custom size, default title
createWindow(1920, 1080, "Game"); // All custom values
return 0;
}
Function prototypes are like movie trailers - they tell you what's coming without showing the whole thing!
Recursion is like Russian nesting dolls - each doll contains a smaller version of itself until you reach the smallest one!
// Factorial: n! = n × (n-1) × ... × 1
int factorial(int n) {
if (n <= 1) { // Base case
return 1;
}
return n * factorial(n - 1); // Recursive case
}
// Fibonacci sequence
int fibonacci(int n) {
if (n <= 1) { // Base cases
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Sum of array elements recursively
int sumArray(int arr[], int size) {
if (size == 0) { // Base case: empty array
return 0;
}
return arr[size - 1] + sumArray(arr, size - 1);
}
// Palindrome checker
bool isPalindrome(string str, int start, int end) {
if (start >= end) { // Base case: middle reached
return true;
}
if (str[start] != str[end]) {
return false;
}
return isPalindrome(str, start + 1, end - 1);
}
Create a calculator using functions for each operation:
#include <iostream>
using namespace std;
// TODO: Create function prototypes here
int main() {
int choice;
double num1, num2, result;
do {
displayMenu();
cin >> choice;
if (choice >= 1 && choice <= 4) {
cout << "Enter two numbers: ";
cin >> num1 >> num2;
// TODO: Call appropriate function based on choice
cout << "Result: " << result << endl;
}
} while (choice != 5);
return 0;
}
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
void displayMenu();
bool isValidChoice(int choice);
Create a text adventure game using functions for: