Chapter 3a - Functions
What Is a Function?β
A function is a named, reusable block of code. Instead of writing the same logic in multiple places, you write it once inside a function and call it whenever needed.
// Function definition
void greet() {
cout << "Hello from a function!" << endl;
}
int main() {
greet(); // Function call
greet(); // Call it again
return 0;
}
Function Anatomyβ
returnType functionName(parameterType paramName, ...) {
// body
return value; // required if returnType is not void
}
| Part | Example | Meaning |
|---|---|---|
| Return type | int, double, void | Type of value the function sends back |
| Function name | calculateArea | What you call to run the function |
| Parameters | double length, double width | Input values the function receives |
| Return statement | return length * width; | Sends a result back to the caller |
void Functions (No Return Value)β
Use void when the function performs an action but doesn't need to send a value back.
#include <iostream>
using namespace std;
void printSeparator() {
cout << "--------------------" << endl;
}
void greet(string name) {
cout << "Hello, " << name << "!" << endl;
}
int main() {
printSeparator();
greet("Alice");
greet("Bob");
printSeparator();
return 0;
}
π§ͺ Try it
#include <iostream>
#include <string>
using namespace std;
void printBox(string message) {
int len = message.length() + 4;
for (int i = 0; i < len; i++) cout << "*";
cout << endl;
cout << "* " << message << " *" << endl;
for (int i = 0; i < len; i++) cout << "*";
cout << endl;
}
int main() {
printBox("C++ is great");
printBox("Hello");
return 0;
}
Functions That Return Valuesβ
int add(int a, int b) {
return a + b;
}
double circleArea(double radius) {
return 3.14159 * radius * radius;
}
bool isEven(int n) {
return n % 2 == 0;
}
The returned value can be stored in a variable, printed directly, or used in an expression:
int sum = add(3, 7); // store it
cout << add(10, 20) << endl; // print it directly
cout << circleArea(5.0) << endl; // use in expression
π§ͺ Return value examples
#include <iostream>
using namespace std;
int max(int a, int b) {
if (a > b) return a;
return b;
}
double average(double a, double b, double c) {
return (a + b + c) / 3.0;
}
int main() {
cout << "Max of 4 and 9: " << max(4, 9) << endl;
cout << "Average of 80, 90, 95: " << average(80, 90, 95) << endl;
return 0;
}
Parameters vs Argumentsβ
| Term | Definition | Example |
|---|---|---|
| Parameter | Variable in the function definition | int a, int b in add(int a, int b) |
| Argument | Actual value passed when calling | add(3, 7) β here 3 and 7 are arguments |
Default Parameter Valuesβ
You can give parameters a default value so the caller can omit them.
void printGreeting(string name, string greeting = "Hello") {
cout << greeting << ", " << name << "!" << endl;
}
int main() {
printGreeting("Alice"); // Hello, Alice!
printGreeting("Bob", "Hey"); // Hey, Bob!
return 0;
}
Default parameters must come last in the parameter list.
Function Overloadingβ
C++ lets you define multiple functions with the same name but different parameter types or counts. The compiler picks the right one.
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
int main() {
cout << add(1, 2) << endl; // calls int version β 3
cout << add(1.5, 2.5) << endl; // calls double version β 4.0
cout << add(1, 2, 3) << endl; // calls 3-param version β 6
return 0;
}
Scopeβ
A variable declared inside a function only exists inside that function. It cannot be accessed from outside.
void doSomething() {
int localVar = 10; // only visible inside doSomething
cout << localVar << endl;
}
int main() {
doSomething();
// cout << localVar; // ERROR: localVar not in scope here
return 0;
}
Recursion (Intro)β
A function can call itself. This is called recursion. Every recursive function needs a base case that stops the recursion.
int factorial(int n) {
if (n == 0) return 1; // base case
return n * factorial(n - 1); // recursive call
}
int main() {
cout << factorial(5) << endl; // 120
return 0;
}
How it unwinds:
factorial(5)
= 5 * factorial(4)
= 4 * factorial(3)
= 3 * factorial(2)
= 2 * factorial(1)
= 1 * factorial(0)
= 1
π§ͺ Recursion example β Fibonacci
#include <iostream>
using namespace std;
int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
for (int i = 0; i < 10; i++) {
cout << fibonacci(i) << " ";
}
cout << endl;
// Output: 0 1 1 2 3 5 8 13 21 34
return 0;
}
Function Declarations (Prototypes)β
In C++, a function must be declared before it is called. If you define helper functions below main(), you need a prototype at the top.
#include <iostream>
using namespace std;
// Prototype β tells the compiler the function exists
int square(int n);
int main() {
cout << square(5) << endl; // works because prototype is above
return 0;
}
// Actual definition β can be below main
int square(int n) {
return n * n;
}
Exercisesβ
Write a function classify(int n) that returns "positive", "negative", or "zero" based on the input. Call it from main for several values.
π Solution
#include <iostream>
#include <string>
using namespace std;
string classify(int n) {
if (n > 0) return "positive";
if (n < 0) return "negative";
return "zero";
}
int main() {
cout << classify(10) << endl;
cout << classify(-5) << endl;
cout << classify(0) << endl;
return 0;
}
Write a function power(double base, int exp) that returns base raised to exp using a loop (no pow() from <cmath>).
Expected: power(2, 10) β 1024
π‘ Hint
Start with result = 1 and multiply by base exactly exp times in a loop.
π Solution
#include <iostream>
using namespace std;
double power(double base, int exp) {
double result = 1.0;
for (int i = 0; i < exp; i++) {
result *= base;
}
return result;
}
int main() {
cout << power(2, 10) << endl; // 1024
cout << power(3, 4) << endl; // 81
cout << power(1.5, 3) << endl; // 3.375
return 0;
}
Write a function bool isPrime(int n) that returns true if n is a prime number, false otherwise. Use it to print all primes from 2 to 50.
π‘ Hint
A number is prime if it has no divisors other than 1 and itself. Loop from 2 to n-1 and check if any divide evenly.
π Solution
#include <iostream>
using namespace std;
bool isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i < n; i++) {
if (n % i == 0) return false;
}
return true;
}
int main() {
cout << "Primes from 2 to 50: ";
for (int i = 2; i <= 50; i++) {
if (isPrime(i)) {
cout << i << " ";
}
}
cout << endl;
return 0;
}