Chapter 6
HomeFunctions 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.
Without functions, your `main()` grows without bound. Every time you need to sum an array, you write the loop again. Functions give you:
// 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;
}
// 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.
Write a function that computes the factorial of a number.
Sample input: 5 Expected output: 120
#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;
}
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));
}
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.
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.
int name(params) { ... return x; }
fn name(params) -> T { expr } — last expression is the return value.
const & (C++) or as &[T] (Rust) to avoid copying.