Learn with Yasir

Share Your Feedback

Lecture 4: Advanced Functions in C++


Lecture 4: Advanced Functions in C++

Topics: Default Arguments, Function Overloading and Recursion

1. Learning Outcomes

After this lecture, students will be able to:

  1. Explain default arguments in C++ functions.
  2. Use default arguments when calling functions.
  3. Define and use overloaded functions.
  4. Explain recursion and its working.
  5. Write simple recursive programs.
  6. Compare recursion with iteration.

2. Recap of Previous Lecture

In the previous lecture, we learned:

  • Function prototypes
  • Function definition and function call
  • Local and global variables
  • Pass by value
  • Pass by reference

In this lecture, we will learn three more useful features of functions.

3. Default Arguments

3.1 What are Default Arguments?

A default argument is a value provided to a function parameter in advance.

If the programmer does not provide a value for that parameter when calling the function, C++ uses the default value.

Real-life example:

Suppose a university charges Rs. 500 as an application processing fee. If no fee is specified, the system uses Rs. 500 by default.

3.2 Example Without Default Arguments

#include <iostream>
using namespace std;

void displayMessage(string name, int times)
{
    for (int i = 1; i <= times; i++)
    {
        cout << "Welcome " << name << endl;
    }
}

int main()
{
    displayMessage("Ali", 3);

    return 0;
}

Output:

Welcome Ali
Welcome Ali
Welcome Ali

Here, we must provide both arguments when calling the function.

3.3 Example With Default Arguments

#include <iostream>
using namespace std;

void displayMessage(string name, int times = 1)
{
    for (int i = 1; i <= times; i++)
    {
        cout << "Welcome " << name << endl;
    }
}

int main()
{
    displayMessage("Ali");

    displayMessage("Ahmed", 3);

    return 0;
}

Output:

Welcome Ali
Welcome Ahmed
Welcome Ahmed
Welcome Ahmed

Explanation:

  • displayMessage("Ali"): The function uses the default value 1.
  • displayMessage("Ahmed", 3): The function uses the provided value 3.

3.4 Rules of Default Arguments

  1. Default arguments are assigned from right to left.
  2. Parameters with default values must come after parameters without default values.
  3. Once a parameter has a default value, all parameters to its right must also have default values.
  4. If a function prototype is used, specify the default value in the prototype, not again in the function definition.

Correct example:

void calculate(int a, int b = 10, int c = 5);

Incorrect example:

void calculate(int a = 10, int b, int c = 5);

The second example is incorrect because a parameter without a default value follows a parameter with a default value.

3.5 Default Arguments with Function Prototype

#include <iostream>
using namespace std;

int add(int a, int b = 5);

int main()
{
    cout << add(10) << endl;
    cout << add(10, 20) << endl;

    return 0;
}

int add(int a, int b)
{
    return a + b;
}

Output:

15
30

Notice that the default value is written in the prototype only.

4. Function Overloading

4.1 What is Function Overloading?

Function overloading means defining multiple functions with the same name but different parameter lists.

These functions perform similar tasks but can accept different numbers or types of arguments.

Real-life example:

A calculator can add:

  • Two integers
  • Three integers
  • Two decimal numbers

We can use the same function name add() for all these operations.

4.2 Example: Different Number of Parameters

#include <iostream>
using namespace std;

int add(int a, int b)
{
    return a + b;
}

int add(int a, int b, int c)
{
    return a + b + c;
}

int main()
{
    cout << add(10, 20) << endl;

    cout << add(10, 20, 30) << endl;

    return 0;
}

Output:

30
60

Explanation:

  • add(10, 20) calls the function with two parameters.
  • add(10, 20, 30) calls the function with three parameters.

C++ selects the appropriate function based on the arguments.

4.3 Example: Different Data Types

#include <iostream>
using namespace std;

int add(int a, int b)
{
    return a + b;
}

double add(double a, double b)
{
    return a + b;
}

int main()
{
    cout << add(10, 20) << endl;

    cout << add(10.5, 20.5) << endl;

    return 0;
}

Output:

30
31

The first function handles integers, while the second handles decimal values.

4.4 Rules of Function Overloading

  1. Functions must have the same name.
  2. Their parameter lists must be different.
  3. The difference can be in the number, type, or order of parameters.
  4. Changing only the return type is not sufficient.

Invalid example:

int calculate(int a)
{
    return a * 2;
}

double calculate(int a)
{
    return a * 2.5;
}

This is invalid because both functions have the same name and identical parameter lists. Only their return types are different.

4.5 Advantages of Function Overloading

  • Makes programs easier to understand.
  • Allows the same function name for similar operations.
  • Reduces the need to remember different function names.
  • Improves code organization.

5. Recursion

5.1 What is Recursion?

Recursion is a programming technique in which a function calls itself.

A recursive function solves a problem by dividing it into smaller versions of the same problem.

Real-life example:

Imagine a set of nested boxes. Each box contains a smaller box. You continue opening boxes until you reach the smallest box.

Similarly, a recursive function continues calling itself until it reaches a stopping condition.

5.2 Two Important Parts of Recursion

Every recursive function should have two important parts:

1. Base Case

The condition that stops the recursive calls.

2. Recursive Case

The part where the function calls itself with a smaller or simpler problem.

Without a proper base case, recursion may continue indefinitely until the program runs out of available call stack space.

5.3 Example: Counting from 1 to 5

#include <iostream>
using namespace std;

void count(int n)
{
    if (n > 5)
        return;

    cout << n << endl;

    count(n + 1);
}

int main()
{
    count(1);

    return 0;
}

Output:

1
2
3
4
5

Explanation:

  • The function starts with n = 1.
  • It displays the value of n.
  • It calls itself with n + 1.
  • When n becomes 6, the base condition becomes true.
  • The function stops calling itself.

5.4 Understanding Recursive Calls

The following sequence shows how the function works:

Recursive calls

  1. count(1)
  2. count(2)
  3. count(3)
  4. count(4)
  5. count(5)
  6. count(6) — Base case reached; stop.

Output: 1, 2, 3, 4, 5

5.5 Example: Factorial Using Recursion

Problem: Write a C++ program to calculate the factorial of a number using recursion.

Factorial means multiplying a positive integer by all positive integers smaller than it.

For example:

\[ 5! = 5 \times 4 \times 3 \times 2 \times 1 = 120 \]

Important:

\[ 0! = 1 \]

C++ Program:

#include <iostream>
using namespace std;

int factorial(int n)
{
    if (n == 0)
        return 1;

    return n * factorial(n - 1);
}

int main()
{
    int number;

    cout << "Enter a number: ";
    cin >> number;

    if (number < 0 || number > 12)
    {
        cout << "Enter a number between 0 and 12.";
    }
    else
    {
        cout << "Factorial = " << factorial(number);
    }

    return 0;
}

Output:

Enter a number: 5
Factorial = 120

We restrict the input to 12 because larger factorials can exceed the storage capacity of the int data type.

5.6 Dry Run: factorial(4)

The function works as follows:

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

Function call and return process:

Function Call Action
factorial(4) Waits for factorial(3)
factorial(3) Waits for factorial(2)
factorial(2) Waits for factorial(1)
factorial(1) Waits for factorial(0)
factorial(0) Returns 1

After the base case returns 1, the pending calculations are completed:

  • factorial(1) returns 1
  • factorial(2) returns 2
  • factorial(3) returns 6
  • factorial(4) returns 24

This process is called unwinding the recursive calls.

6. Recursion vs Iteration

Iteration means repeating instructions using loops such as for and while.

Recursion Iteration
Function calls itself Uses loops
Requires a base case Requires a loop condition
Uses the call stack for recursive calls Usually uses less memory
Can make some problems easier to express Often more efficient for simple repetition
May be harder to trace Usually easier to trace for beginners

Example: Display numbers from 1 to 5

Using a loop:

for (int i = 1; i <= 5; i++)
{
    cout << i << endl;
}

Using recursion:

void count(int n)
{
    if (n > 5)
        return;

    cout << n << endl;

    count(n + 1);
}

Both approaches produce the same output.

7. Common Mistakes

  1. Forgetting the base case in a recursive function.
  2. Writing a recursive call that does not move toward the base case.
  3. Assigning default arguments to parameters in the wrong order.
  4. Repeating a default argument in both the prototype and definition.
  5. Trying to overload functions by changing only the return type.
  6. Calling a recursive function with an invalid input.
  7. Ignoring possible integer overflow in factorial calculations.

8. Programming Exercises

Beginner Level

Problem Statement 1: Display Student Information

Write a C++ program using a function with default arguments to display a student’s name and semester.

Tasks:

  1. Create a function named displayStudent().
  2. Accept the student’s name as a parameter.
  3. Set the semester’s default value to 1.
  4. Call the function with and without the semester argument.

Problem Statement 2: Overloaded Area Function

Write a C++ program using function overloading to calculate areas.

Tasks:

  1. Create an overloaded function named area().
  2. Calculate the area of a square using one parameter.
  3. Calculate the area of a rectangle using two parameters.
  4. Display both results.

Intermediate Level

Problem Statement 3: Overloaded Maximum Function

Write a C++ program to find the maximum value using overloaded functions.

Tasks:

  1. Create a function to find the maximum of two integers.
  2. Create another function to find the maximum of three integers.
  3. Call both functions from main().

Problem Statement 4: Sum Using Recursion

Write a recursive function to calculate the sum of numbers from 1 to n.

For example:

\[ 1+2+3+4+5=15 \]

Tasks:

  1. Create a function named sum().
  2. Use a base case to stop recursion.
  3. Calculate and display the sum.

Advanced Level

Problem Statement 5: Fibonacci Series Using Recursion

Write a C++ program to generate Fibonacci numbers using recursion.

The Fibonacci sequence starts as:

0 1 1 2 3 5 8 13 21

Tasks:

  1. Create a recursive function named fibonacci().
  2. Return 0 when n is 0.
  3. Return 1 when n is 1.
  4. Calculate other values using the previous two values.
  5. Display the first n terms.

9. Short Questions

  1. What is a default argument?
  2. Why do we use default arguments?
  3. What is function overloading?
  4. Can two functions have the same name and same parameters but different return types?
  5. What is recursion?
  6. What is a base case?
  7. What happens if a recursive function has no base case?
  8. What is the difference between recursion and iteration?
  9. What is the purpose of the return statement in recursion?
  10. What is factorial of zero?

10. Quick Quiz

Test your understanding

0 / 7 answered

1. What is a default argument?

A. A value automatically assigned to a parameter when no argument is supplied

B. A global variable

C. A loop condition

D. A return type

2. Which function calls itself?

A. Overloaded function

B. Recursive function

C. Main function only

D. Void function

3. What is the stopping condition in recursion called?

A. Function prototype

B. Parameter

C. Base case

D. Default argument

4. Can functions be overloaded by changing only their return type?

A. Yes

B. No

C. Only with void

D. Only with int

5. What is the factorial of 0?

A. 0

B. 10

C. 1

D. Undefined

6. Which statement is true about default arguments?

A. They must come before all other parameters

B. They must be assigned from right to left

C. They cannot be used with prototypes

D. Every function must have them

7. Which approach usually uses a function call stack?

A. Recursion

B. A simple for loop

C. A simple while loop

D. An if statement

Submit Answers

11. Lecture Summary

In this lecture, we learned three important concepts:

Topic Main Idea
Default Arguments Provide predefined values to parameters
Function Overloading Use the same function name with different parameter lists
Recursion A function calls itself until the base case is reached

Important points to remember:

  • Default arguments make function calls more flexible.
  • Function overloading allows similar operations to use the same function name.
  • Every recursive function must have a base case.
  • Recursion and loops can solve many of the same problems.