Chapter 10: Functions

Functions let you organize your code, reuse it, and make your program clean and easy to understand.

Think of a function as a small machine:

  • You give it some input (parameters)
  • It does some work
  • It gives you back a result (return value)

1. What is a Function?

A function is a block of code that performs a specific task and has a name. Instead of writing the same code many times, you write it once in a function and call it whenever needed.

2. Defining and Calling Functions

Defining a function (writing the function):

C

Calling a function (using it):

C

Simple Example – Function without parameters and without return

C

Output:

text

3. Function Parameters and Return Values

Parameters = Inputs the function receives Return value = Output the function gives back

Example – Function with parameters and return value

C

Output:

text

4. Types of Functions

There are 4 main combinations:

A. No arguments, no return value (like sayHello above)

B. Arguments but no return value

C

C. No arguments but returns a value

C

D. Arguments and return value (most common and useful)

C

Output:

text

5. Recursion

A function that calls itself is called recursive.

Example – Factorial using recursion

C

How it works (n=5):

  • 5 * factorial(4)
  • 5 * 4 * factorial(3)
  • 5 * 4 * 3 * factorial(2)
  • 5 * 4 * 3 * 2 * factorial(1)
  • 5 * 4 * 3 * 2 * 1 = 120

Output:

text

Note: Always have a base case (stopping condition), otherwise infinite recursion → crash!

6. Scope and Storage Classes

Scope = Where a variable can be used.

A. Local variables (declared inside function) – only visible inside that function B. Global variables (declared outside all functions) – visible everywhere

Storage Classes – Control how long and where variables exist:

Storage Class Keyword Lifetime Default Value Scope
auto (default) Until function ends Garbage Inside function
static static Whole program (but only one copy) 0 Inside function (local) or global
extern extern Whole program 0 Global (declared elsewhere)
register register Until function ends Garbage Inside function (try to store in CPU register)

Example – static variable (keeps value between calls)

C

Output:

text

7. Function Prototypes (Declaration)

If you call a function before defining it, compiler needs to know about it.

Prototype = Tells compiler the function’s name, parameters, and return type.

C

Best Practice: Always put prototypes at the top of the file (after includes).

Today’s Homework

  1. Write a function greet() that prints “Good Morning!” and call it from main.
  2. Write a function maxOfTwo(int a, int b) that returns the larger of two numbers.
  3. Create a function isEven(int n) that returns 1 if even, 0 if odd.
  4. Write a recursive function to calculate the sum of first N natural numbers.
  5. Create a program with a static variable inside a function that counts how many times the function is called.

You may also like...