Chapter 6

Home

Functions to Organize Code

Functions let you name a block of code, give it parameters, and call it from anywhere. Instead of copy-pasting the same logic, you write it once and reuse it.

Why Functions?

Without functions, your `main()` grows without bound. Every time you need to sum an array, you write the loop again. Functions give you:

main() read() compute() main calls read, then compute, then prints Each function has one job.

Function Syntax

C++

// return_type function_name(parameters)
int add(int a, int b) {
    return a + b;
}

int main() {
    int result = add(3, 7);
    cout << result << "\n"; // 10
    return 0;
}

Rust

// fn function_name(parameters) -> return_type
fn add(a: i32, b: i32) -> i32 {
    a + b  // no semicolon = return value
}

fn main() {
    let result = add(3, 7);
    println!("{}", result); // 10
}

Rust: the last expression in a function is returned. No return keyword needed.

Problem: Factorial

Write a function that computes the factorial of a number.

Sample input:
5

Expected output:
120

C++

#include <bits/stdc++.h>
using namespace std;

int factorial(int n) {
    int result = 1;
    for (int i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}

int main() {
    int n; cin >> n;
    cout << factorial(n) << "\n";
    return 0;
}

Rust

use std::io::{self, Read};

fn factorial(n: i32) -> i64 {
    let mut result = 1;
    for i in 2..=n {
        result *= i as i64;
    }
    result
}

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let n: i32 = input.trim().parse().unwrap();
    println!("{}", factorial(n));
}

Passing Arrays (Vectors) to Functions

C++ — pass by reference

int sum(const vector<int>& arr) {
    int total = 0;
    for (int x : arr) total += x;
    return total;
}

int main() {
    vector<int> v = {1, 2, 3, 4};
    cout << sum(v) << "\n"; // 10
}

Use const & to avoid copying the whole vector.

Rust — pass as slice

fn sum(arr: &[i64]) -> i64 {
    arr.iter().sum()
}

fn main() {
    let v = vec![1, 2, 3, 4];
    println!("{}", sum(&v)); // 10
}

Use &[T] (a slice reference) to borrow without copying.

Key Takeaways

Practice