Skip to main content

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
}
PartExampleMeaning
Return typeint, double, voidType of value the function sends back
Function namecalculateAreaWhat you call to run the function
Parametersdouble length, double widthInput values the function receives
Return statementreturn length * width;Sends a result back to the caller

Mini quiz β€” functions​

Quiz

What is a function?

1 / 3

A function is mainly…

Pick an answer to see if you are right.


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

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

Challenge: bigger of two​

Finish bigger so it returns the larger of two integers.

abReturn
499
10310

Parameters vs Arguments​

TermDefinitionExample
ParameterVariable in the function definitionint a, int b in add(int a, int b)
ArgumentActual value passed when callingadd(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;
}
note

Default parameters must come last in the parameter list.

πŸ§ͺ Default parameters

Mini quiz β€” parameters​

Quiz

Parameters and defaults

1 / 3

In this call, 3 and 7 are…

add(3, 7)

Pick an answer to see if you are right.


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;
}
πŸ§ͺ Overloading

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;
}

Mini quiz β€” overloading and scope​

Quiz

Overloading and scope

1 / 3

Function overloading means…

Pick an answer to see if you are right.


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

Challenge: factorial​

Finish factorial so it returns n!. Use recursion. factorial(0) is 1.

nReturn
5120
01

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;
}
πŸ§ͺ Prototypes

Exercises​

Activity: Number Classifier

Write a function classify(int n) that returns "positive", "negative", or "zero" based on the input. Call it from main for several values.

πŸ“’ Solution