0% found this document useful (0 votes)
2 views15 pages

Chapter4 Functions Notes

Chapter 4 of EthioFreshman covers functions in C++, explaining their definition, purpose, and rules for declaration, definition, and calling. It discusses key concepts such as local vs global variables, pass by value vs reference, inline functions, default arguments, function overloading, and recursion. The chapter provides examples and practical applications to illustrate these concepts.

Uploaded by

abrarawmolla87
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

Chapter4 Functions Notes

Chapter 4 of EthioFreshman covers functions in C++, explaining their definition, purpose, and rules for declaration, definition, and calling. It discusses key concepts such as local vs global variables, pass by value vs reference, inline functions, default arguments, function overloading, and recursion. The chapter provides examples and practical applications to illustrate these concepts.

Uploaded by

abrarawmolla87
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

EthioFreshman | Freshman Educational Resources

Chapter 4: Functions in C++ | Computer Programming

ETHIOFRESHMAN
Freshman Educational Resources

Chapter Four
FUNCTIONS IN C++
Complete Study Notes with Examples

Computer Programming • First Year Freshman

EthioFreshman — Chapter 4: C++ Functions Page 1 of 15


EthioFreshman | Freshman Educational Resources
Chapter 4: Functions in C++ | Computer Programming

4. What is a Function?

Key Definition
A function is a named block of code designed to perform a specific, well-defined task.
It packages a computational recipe so it can be reused as many times as needed.
Think of it like a recipe card: write once, cook many times!

Real-World Analogy:
Imagine a TV remote. Each button (Power, Volume, Channel) is like a function — each does ONE
specific task. You press the button (call the function) and it does the job without you needing to know
the electronics inside.

4.1 Why Use Functions?


• Break large problems into smaller, manageable tasks
• Avoid repeating the same code — write once, use many times
• Make programs easier to read, debug, and maintain
• Each function should do only ONE primary task

4.2 Function Rules (Summary)

Rule Details Example


Must have a name Assigned by programmer calculateArea, printMessage
following variable naming
rules
Name length Up to 32 characters, starts myFunction123
with a letter
Parentheses required Always () immediately after greet(), add()
the name
Body in braces All code inside { } braces void greet() { ... }
after the parentheses

4.3 Declaring, Defining & Calling Functions

EthioFreshman — Chapter 4: C++ Functions Page 2 of 15


EthioFreshman | Freshman Educational Resources
Chapter 4: Functions in C++ | Computer Programming

4.3.1 Declaring a Function (Prototype)


A function prototype tells the compiler about the function before it is fully defined. It has three parts:

Part What it means Example


Return Type What type of value the int, float, void
function gives back
Function Name A unique identifier you addition, display
choose
Parameters Typed variables the function int a, int b
receives

Syntax:
returnType functionName(paramType param1, paramType param2);

// Examples:
int addition(int a, int b); // returns an int
void printLine(); // returns nothing (void)
float getArea(float w, float h); // returns a float

4.3.2 Defining a Function


A function definition has two parts: the header (prototype without semicolon) and the body (the actual
code in { }).

int addition(int a, int b) // Header (no semicolon here!)


{ // Opening brace
int r; // Local variable
r = a + b; // Body: the actual work
return r; // Send result back
} // Closing brace

Important Note
If the function is defined BEFORE main(), no prototype is needed.
If defined AFTER main(), you MUST write the prototype before main() starts.
Tip: It's good practice to always use prototypes for clarity.

4.3.3 Calling a Function


Calling a function means making it execute. You write the function name followed by parentheses and
pass any required arguments.

EthioFreshman — Chapter 4: C++ Functions Page 3 of 15


EthioFreshman | Freshman Educational Resources
Chapter 4: Functions in C++ | Computer Programming

Full Example — Understanding Function Flow:


#include <iostream.h>

int addition(int a, int b) // Function DEFINITION


{
int r;
r = a + b;
return r; // Returns 8 when a=5, b=3
}

int main()
{
int z;
z = addition(5, 3); // Function CALL — sends 5 and 3
cout << "The result is " << z; // Prints: The result is 8
return 0;
}

Step-by-Step Execution Trace


Step 1: main() starts. Variable z is declared.
Step 2: addition(5, 3) is called. Control jumps to addition().
Step 3: Inside addition(), a=5 and b=3. r = 5+3 = 8.
Step 4: return(r) sends 8 back to main().
Step 5: z = 8. cout prints 'The result is 8'.

Think of it like a highway detour: you leave main(), complete the detour (function), then
return to main().

EthioFreshman — Chapter 4: C++ Functions Page 4 of 15


EthioFreshman | Freshman Educational Resources
Chapter 4: Functions in C++ | Computer Programming

4.4 Global vs Local Variables

Feature Global Variable Local Variable


Where defined Outside all functions Inside a function or block
Who can see it Entire program Only its own scope/block
Lifetime Entire program run Only while function executes
Example int year = 1994; int x = 5; (inside main)

int count = 0; // GLOBAL — visible everywhere

void increment() {
count++; // can access global count
}

int main() {
int score = 100; // LOCAL — only visible in main()
increment();
cout << count; // OK: 1
// cout << score; // OK here but NOT inside increment()
return 0;
}

4.5 The Scope Operator ::


When a local variable has the same name as a global variable, the local one hides the global. Use the
scope operator :: to access the global version explicitly.

int num = 2; // Global num

void fun1(int num) { // Local num (hides global)


num = 33;
cout << num; // Prints: 33 (local)
cout << ::num; // Prints: 2 (global, using ::)
if (::num != 0) // Refers to global num
cout << "Global is non-zero";
}

4.6 Automatic vs Static Variables

EthioFreshman — Chapter 4: C++ Functions Page 5 of 15


EthioFreshman | Freshman Educational Resources
Chapter 4: Functions in C++ | Computer Programming

Feature Automatic (default) Static


Keyword auto (optional) static
Memory Erased when function ends Retained between calls
Default value Undefined/garbage 0 (if not initialized)
Scope Local to function Local to function
Initialization Every call Only on FIRST call

void my_fun() {
static int count = 2; // Initialized ONCE, then remembered
static int num; // Auto-initialized to 0
count = count * 5;
num = num + 4;
cout << "count=" << count << ", num=" << num << endl;
}

// Call 1: count=2*5=10, num=0+4=4


// Call 2: count=10*5=50, num=4+4=8
// Call 3: count=50*5=250, num=8+4=12

Memory Tip
Static = Sticky. The value sticks around between calls.
Automatic = Amnesia. The variable forgets its value each time the function ends.
Use static when you need a counter or accumulator across multiple function calls.

EthioFreshman — Chapter 4: C++ Functions Page 6 of 15


EthioFreshman | Freshman Educational Resources
Chapter 4: Functions in C++ | Computer Programming

4.7 Function Parameters and Arguments

C++ supports two ways to pass data to functions: Pass by Value and Pass by Reference.

4.7.1 Pass by Value


The function receives a COPY of the argument. Changes inside the function do NOT affect the original
variable.

void Foo(int num) { // num is a COPY of x


num = 0; // Changes copy, not original
cout << "num = " << num; // Prints: num = 0
}

int main() {
int x = 10;
Foo(x); // Pass copy of x
cout << "x = " << x; // Prints: x = 10 (unchanged!)
return 0;
}

4.7.2 Pass by Reference


The function receives a REFERENCE to the original variable. Changes inside the function DO affect
the original. Use & in the parameter type.

void Foo(int & num) { // & means reference to original


num = 0; // Changes the ORIGINAL variable!
cout << "num = " << num; // Prints: num = 0
}

int main() {
int x = 10;
Foo(x); // Pass reference to x
cout << "x = " << x; // Prints: x = 0 (CHANGED!)
return 0;
}

Practical Example — Swapping Two Numbers:


void order(int &num1, int &num2) {
if (num1 > num2) { // If out of order, swap them
int temp = num1;
num1 = num2;

EthioFreshman — Chapter 4: C++ Functions Page 7 of 15


EthioFreshman | Freshman Educational Resources
Chapter 4: Functions in C++ | Computer Programming

num2 = temp;
}
}

int main() {
int n1=99, n2=11; // Unsorted pair
int n3=22, n4=88; // Already sorted pair
order(n1, n2); // n1 and n2 get swapped
order(n3, n4); // n3 and n4 stay the same
// Output: n1=11, n2=99, n3=22, n4=88
}

Pass by Value Pass by Reference


Syntax void f(int n) void f(int &n)
Original changed? NO — copy only YES — direct access
Use when You don't want changes to You need to modify original,
propagate or return multiple values
Analogy Photocopy of a document The actual document

EthioFreshman — Chapter 4: C++ Functions Page 8 of 15


EthioFreshman | Freshman Educational Resources
Chapter 4: Functions in C++ | Computer Programming

4.8 Inline Functions

For small, frequently-called functions, function call overhead (saving registers, setting up stack frames)
can slow your program. The inline keyword asks the compiler to copy the function body directly at the
call site — eliminating the call overhead.

Type Regular Function Inline Function


Keyword None inline before return type
How it works Jumps to function code Copies code at call site
Speed Slight overhead per call Faster for tiny functions
Code size Compact executable Larger if called many times
Best for Large or rarely called Tiny functions called often
functions

// Regular function — has call overhead


int Abs(int n) {
return n > 0 ? n : -n;
}

// Inline function — compiler inserts body at each call


inline int Abs(int n) {
return n > 0 ? n : -n;
}

// Usage is identical:
int x = Abs(-7); // x = 7

When Inlining May NOT Work


1. Recursive functions (they call themselves — can't expand infinitely)
2. Functions with loops (for, while)
3. Functions that are too large (compiler decides)
Rule of thumb: inline is best for 1-3 line functions called hundreds of times.
The 'inline' keyword is a hint — the compiler has the final say.

4.9 Default Arguments & Function Overloading

EthioFreshman — Chapter 4: C++ Functions Page 9 of 15


EthioFreshman | Freshman Educational Resources
Chapter 4: Functions in C++ | Computer Programming

4.9.1 Default Arguments


Default arguments let you call a function without providing all arguments. Missing arguments use their
preset default values. Defaults must be placed on the RIGHT side of the parameter list.

void Add_Display(int x=10, int y=20, int z=30) {


cout << (x + y + z);
}

int main() {
Add_Display(40, 50, 60); // Uses all provided: 40+50+60 = 150
Add_Display(40, 50); // z defaults to 30: 40+50+30 = 120
Add_Display(40); // y,z default: 40+20+30 = 90
Add_Display(); // All default: 10+20+30 = 60
}

Common Mistake
WRONG: void f(int x, int y=5, int z) // z has no default but comes after y!
RIGHT: void f(int x, int z, int y=5) // default always on the far RIGHT

Think of it like a queue: defaults fill from the back first.

4.9.2 Function Overloading


C++ allows multiple functions with the SAME name as long as they have DIFFERENT parameter lists.
The compiler picks the right version based on the argument types provided.

// Two functions, same name, different parameters


int abs(int i) {
return (i < 0) ? i * -1 : i;
}

float abs(float x) {
return (x < 0.0) ? x * -1.0 : x;
}

int main() {
int a = abs(-5); // Calls int version => 5
float b = abs(-3.7f); // Calls float version => 3.7
cout << a << " " << b;
}

Overloading Rules

EthioFreshman — Chapter 4: C++ Functions Page 10 of 15


EthioFreshman | Freshman Educational Resources
Chapter 4: Functions in C++ | Computer Programming

REQUIRED: Overloaded functions MUST differ in parameter types or number.


NOT ALLOWED: Functions that differ ONLY in return type cannot be overloaded.
Example valid: int f(int), float f(float) — different parameter types
Example invalid: int f(int), float f(int) — only return type differs

EthioFreshman — Chapter 4: C++ Functions Page 11 of 15


EthioFreshman | Freshman Educational Resources
Chapter 4: Functions in C++ | Computer Programming

4.10 Recursion

A recursive function is one that calls ITSELF. Recursion works on problems that can be broken into
smaller versions of the same problem.

Three Essential Components of Recursion


1. A BASE CASE — the condition that stops the recursion (no more self-calls)
2. A RECURSIVE CALL — the function calling itself with a simpler input
3. PROGRESS — each call must move closer to the base case

Example 1: Factorial
Factorial definition: 0! = 1 and n! = n x (n-1)!
int factorial(unsigned int n) {
return (n == 0) ? 1 : n * factorial(n - 1);
}

// Trace for factorial(4):


// factorial(4) = 4 * factorial(3)
// = 4 * 3 * factorial(2)
// = 4 * 3 * 2 * factorial(1)
// = 4 * 3 * 2 * 1 * factorial(0)
// = 4 * 3 * 2 * 1 * 1 = 24

Example 2: Sum of First N Integers


int sum(int N) {
if (N == 1) // Base case: sum of 1 = 1
return 1;
else
return N + sum(N - 1); // Recursive case
}

// sum(4) = 4 + sum(3)
// = 4 + 3 + sum(2)
// = 4 + 3 + 2 + sum(1)
// = 4 + 3 + 2 + 1 = 10

Example 3: Fibonacci Series


Series: 0, 1, 1, 2, 3, 5, 8, 13, 21 ... (each number = sum of previous two)
int fibonacci(int n) {
if (n == 0) return 0; // Base case 1

EthioFreshman — Chapter 4: C++ Functions Page 12 of 15


EthioFreshman | Freshman Educational Resources
Chapter 4: Functions in C++ | Computer Programming

if (n == 1) return 1; // Base case 2


return fibonacci(n-1) + fibonacci(n-2); // Recursive
}

// fibonacci(5) = fib(4) + fib(3)


// = (fib(3)+fib(2)) + (fib(2)+fib(1))
// = 3 + 2 = 5

Example 4: Exponentiation A^N


float expo(float A, int N) {
if (N == 1) return A; // Base case: A^1 = A
return A * expo(A, N - 1); // A^N = A * A^(N-1)
}

// expo(2.0, 4) = 2 * expo(2,3)
// = 2 * 2 * expo(2,2)
// = 2 * 2 * 2 * expo(2,1)
// = 2 * 2 * 2 * 2 = 16

4.11 Recursion vs Iteration

Feature Recursion Iteration


Control structure Selection (if/else/switch) Repetition (for/while/do-
while)
Memory use Higher (stack frame per call) Lower (single loop variable)
Speed Slower (function call Generally faster
overhead)
Code clarity Often more elegant for More straightforward for
tree/math problems loops
Risk Stack overflow if no base Infinite loop if condition never
case false
Best used when Problem is naturally recursive Efficiency is critical

When to Choose Recursion


1. The recursive solution is natural and easy to understand
2. It doesn't result in excessive repeated computation
3. The equivalent iterative solution is very complex
4. You are asked to use it in an exam!

For most real-world problems, iteration is preferred for performance.

EthioFreshman — Chapter 4: C++ Functions Page 13 of 15


EthioFreshman | Freshman Educational Resources
Chapter 4: Functions in C++ | Computer Programming

EthioFreshman — Chapter 4: C++ Functions Page 14 of 15


EthioFreshman | Freshman Educational Resources
Chapter 4: Functions in C++ | Computer Programming

Quick Reference Summary

Topic Key Point Syntax


Prototype Declare before use int add(int a, int b);
Definition Header + body int add(int a,int b){ return
a+b; }
Call Execute the function z = add(5, 3);
Pass by Value Copy — original safe void f(int x)
Pass by Reference Direct — original changes void f(int &x)
Default Args Defaults from right void f(int x, int y=10)
Overloading Same name, diff params int abs(int), float abs(float)
Inline No call overhead inline int f(int x){...}
Static local Keeps value between calls static int count = 0;
Recursion Function calls itself return n==0 ? 1 : n*fact(n-1);

EthioFreshman
Good luck with your studies! — Chapter 4 Complete

EthioFreshman — Chapter 4: C++ Functions Page 15 of 15

You might also like