Learn with Yasir

Share Your Feedback

Lecture 5: Practical Applications of C++ Functions


Lecture 5: Practical Applications of C++ Functions

Course: CS-303 Programming Fundamentals
Topics: Combining Functions, Modular Programming, Practical Problem-Solving and Function-Based Programs

1. Learning Outcomes

After completing this lecture, students will be able to:

  1. Divide a large problem into smaller functions.
  2. Create and call multiple functions in one program.
  3. Pass data between functions using parameters.
  4. Return results from functions.
  5. Use function overloading and default arguments in practical programs.
  6. Develop a complete C++ program using functions.

2. Recap of Previous Lectures

We have learned the following concepts:

Lecture Topics
Lecture 1 Introduction to Functions
Lecture 2 Function Parameters and Return Values
Lecture 3 Function Prototypes, Variable Scope and Parameter Passing
Lecture 4 Default Arguments, Function Overloading and Recursion

Now we will apply these concepts to solve practical programming problems.

3. Modular Programming

3.1 What is Modular Programming?

Modular programming means dividing a large program into smaller, manageable parts called modules or functions.

Each function performs a specific task.

Real-life example: University Student Management System

A university system may perform several operations:

  • Add student information
  • Calculate student marks
  • Calculate percentage
  • Assign grades
  • Display student results

Instead of writing all instructions inside main(), we can create separate functions for each operation.

Student Management System

main()

Controls the program

inputMarks()

Input marks

calculateTotal()

Calculate total

calculatePercentage()

Calculate percentage

displayResult()

Display result

3.2 Advantages of Modular Programming

  1. Makes programs easier to understand.
  2. Reduces code repetition.
  3. Makes testing and debugging easier.
  4. Allows code reuse.
  5. Makes large programs easier to maintain.

4. Practical Example 1: Student Result System

Problem Statement: Write a C++ program that accepts marks of three subjects, calculates total marks and percentage, and displays the result using functions.

Step 1: Understand the Problem

The program needs to perform four tasks:

  1. Input marks.
  2. Calculate total marks.
  3. Calculate percentage.
  4. Display the result.

Step 2: Identify Functions

Function Purpose
inputMarks() Accept three subject marks
calculateTotal() Calculate total marks
calculatePercentage() Calculate percentage
displayResult() Display final result

Step 3: C++ Program

#include <iostream>
using namespace std;

// Function prototypes
void inputMarks(int &m1, int &m2, int &m3);
int calculateTotal(int m1, int m2, int m3);
double calculatePercentage(int total);
void displayResult(int total, double percentage);

int main()
{
    int m1, m2, m3;

    inputMarks(m1, m2, m3);

    int total = calculateTotal(m1, m2, m3);

    double percentage = calculatePercentage(total);

    displayResult(total, percentage);

    return 0;
}

// Input marks
void inputMarks(int &m1, int &m2, int &m3)
{
    cout << "Enter marks of three subjects: ";
    cin >> m1 >> m2 >> m3;
}

// Calculate total
int calculateTotal(int m1, int m2, int m3)
{
    return m1 + m2 + m3;
}

// Calculate percentage
double calculatePercentage(int total)
{
    return (total / 300.0) * 100;
}

// Display result
void displayResult(int total, double percentage)
{
    cout << "Total Marks: " << total << endl;
    cout << "Percentage: " << percentage << "%" << endl;
}

Step 4: Sample Output

Enter marks of three subjects: 75 80 85

Total Marks: 240
Percentage: 80%

Step 5: Understand the Program Flow

  1. Program starts from main().
  2. inputMarks() accepts marks from the user.
  3. calculateTotal() calculates the total marks.
  4. calculatePercentage() calculates the percentage.
  5. displayResult() displays the final result.

Important concept: The & symbol in inputMarks() allows the function to modify the original variables in main() through reference parameters.

5. Practical Example 2: Simple Calculator

Problem Statement: Write a C++ program that performs addition, subtraction, multiplication and division using separate functions.

Step 1: Identify Functions

Function Operation
add() Addition
subtract() Subtraction
multiply() Multiplication
divide() Division

Step 2: C++ Program

#include <iostream>
using namespace std;

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

int subtract(int a, int b)
{
    return a - b;
}

int multiply(int a, int b)
{
    return a * b;
}

double divide(double a, double b)
{
    return a / b;
}

int main()
{
    int num1, num2;

    cout << "Enter two numbers: ";
    cin >> num1 >> num2;

    cout << "Addition: " << add(num1, num2) << endl;

    cout << "Subtraction: " << subtract(num1, num2) << endl;

    cout << "Multiplication: " << multiply(num1, num2) << endl;

    if (num2 != 0)
    {
        cout << "Division: " << divide(num1, num2) << endl;
    }
    else
    {
        cout << "Division by zero is not allowed." << endl;
    }

    return 0;
}

Sample Output

Enter two numbers: 20 10

Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2

Classroom Discussion

Ask students:

  1. Why did we create separate functions for each operation?
  2. Why does the divide() function use double?
  3. Why do we check whether the second number is zero?
  4. What is the advantage of returning a result instead of displaying it directly?

6. Practical Example 3: Function Overloading in a Calculator

We can use function overloading to calculate the area of different shapes.

Problem Statement: Write a C++ program using overloaded functions to calculate the area of a square, rectangle and circle.

#include <iostream>
using namespace std;

double area(double side)
{
    return side * side;
}

double area(double length, double width)
{
    return length * width;
}

double area(int radius, double pi)
{
    return pi * radius * radius;
}

int main()
{
    cout << "Square Area: " << area(5.0) << endl;

    cout << "Rectangle Area: " << area(5.0, 4.0) << endl;

    cout << "Circle Area: " << area(3, 3.14159) << endl;

    return 0;
}

Output:

Square Area: 25
Rectangle Area: 20
Circle Area: 28.2743

Observation: All three functions have the same name, area(), but their parameter lists are different.

7. Practical Example 4: Recursion to Calculate Sum

Problem Statement: Write a recursive function to calculate the sum of integers from 1 to n.

C++ Program

#include <iostream>
using namespace std;

int calculateSum(int n)
{
    if (n == 0)
        return 0;

    return n + calculateSum(n - 1);
}

int main()
{
    int number;

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

    if (number < 0)
    {
        cout << "Please enter a non-negative number.";
    }
    else
    {
        cout << "Sum = " << calculateSum(number);
    }

    return 0;
}

Output:

Enter a number: 5
Sum = 15

Dry Run

For calculateSum(4):

Function Call Calculation Return Value
calculateSum(4) 4 + calculateSum(3) 10
calculateSum(3) 3 + calculateSum(2) 6
calculateSum(2) 2 + calculateSum(1) 3
calculateSum(1) 1 + calculateSum(0) 1
calculateSum(0) Base case 0

Final result:

\[ 4+3+2+1+0=10 \]

8. Practical Lab Assignment

Students should complete the following problems in the computer lab.

Problem Statement 1: Employee Salary Calculator

Write a C++ program using functions to calculate an employee’s salary.

Tasks:

  1. Input employee name and basic salary.
  2. Create a function calculateAllowance() to calculate 20% allowance.
  3. Create a function calculateTax() to calculate 5% tax on basic salary.
  4. Create a function calculateNetSalary() to calculate net salary.
  5. Display employee name and final salary.

Requirements:

  • Use separate functions for each calculation.
  • Use parameters and return values.
  • Use appropriate data types.

Problem Statement 2: Number Checking System

Write a C++ program using functions to check different properties of a number.

Tasks:

  1. Create a function isEven() to check whether a number is even.
  2. Create a function isPositive() to check whether a number is positive.
  3. Create a function isPrime() to check whether a number is prime.
  4. Display the results in main().

Requirements:

  • Use bool return types where appropriate.
  • Pass the number as a parameter.
  • Do not repeat the same calculation in multiple places.

Problem Statement 3: Student Grade Calculator

Write a C++ program to calculate a student’s grade using functions.

Tasks:

  1. Input marks of five subjects.
  2. Create a function to calculate total marks.
  3. Create a function to calculate percentage.
  4. Create a function to determine the grade.
  5. Display total, percentage and grade.

Requirements:

  • Use separate functions.
  • Use parameters and return values.
  • Use if-else statements for grade calculation.

9. Independent Practice

Ask students to modify the programs.

No. Modification Task
1 Add a function to calculate the average of three numbers.
2 Modify the calculator to use a menu.
3 Add a function to check whether a year is a leap year.
4 Modify the student result program to accept five subjects.
5 Calculate factorial using both recursion and iteration.

10. Assessment Questions

  1. What is modular programming?
  2. Why do we divide a program into functions?
  3. What is the difference between a function parameter and an argument?
  4. Why do we use function prototypes?
  5. What is the purpose of a return value?
  6. How can multiple functions work together?
  7. What is the advantage of function overloading?
  8. Why should we avoid repeating code?
  9. What is the difference between pass by value and pass by reference?
  10. What is the difference between recursion and iteration?

11. Quick Knowledge Check

Test your understanding

0 / 5 answered

1. What is modular programming?

A. Writing all code in main()

B. Dividing a program into smaller functions

C. Using only global variables

D. Avoiding functions

2. Which function usually controls the execution of a C++ program?

A. add()

B. display()

C. main()

D. calculate()

3. Which return type is suitable for a function that checks whether a number is even?

A. void

B. bool

C. string

D. char

4. What is the main advantage of separate functions?

A. More repetition

B. Code becomes harder to test

C. Better organization and reuse

D. No need for variables

5. What happens when a function returns a value?

A. It sends a result back to the calling code

B. It always ends the entire program

C. It creates a global variable

D. It starts main() again

Submit Answers

12. Lecture Summary

In this lecture, we applied C++ functions to practical programming problems.

Concept Practical Application
Multiple functions Student result system
Parameters and return values Calculator
Function overloading Area calculation
Recursion Sum of numbers
Modular programming Employee and student management

Key Message for Students:

A good programmer does not write the entire program in one place. A good programmer divides a problem into smaller tasks and creates separate functions to solve those tasks.