Detailed Explanation of User-Defined Functions in C++

User-Defined Functions

In C++ programming, although the standard library provides over 140 predefined functions, we often need to create our own functions in actual development. User-defined functions are one of the core concepts in C++ programming, especially in object-oriented programming and class design.

Basic Concepts

User-defined functions need to include the following elements:

  • Function prototype (declaration)
  • Function call
  • Function definition

Basic Example

#include <iostream>
using namespace std;

// Function prototype - informs the compiler of the function's existence
void simon(int n);           // accepts an int parameter, no return value
double calculateArea(double length, double width);  // accepts two double parameters, returns double
void printWelcome();         // no parameters, no return value
int getMax(int a, int b);    // accepts two int parameters, returns int

int main() {
    // Call user-defined functions
    printWelcome();
    
    simon(3);  // Call simon function, passing parameter 3
    simon(5);  // Call again, passing parameter 5
    
    double area = calculateArea(4.5, 3.2);
    cout << "Rectangle Area: " << area << endl;
    
    int maxValue = getMax(10, 20);
    cout << "Larger Value: " << maxValue << endl;
    
    return 0;
}

// Function definition - implements the specific functionality of the function
void simon(int n) {
    cout << "Simon says touch your toes " << n << " times." << endl;
}

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

void printWelcome() {
    cout << "=== Welcome to the User-Defined Function Demonstration Program ===" << endl;
    cout << "===================================" << endl;
}

int getMax(int a, int b) {
    if (a > b) {
        return a;
    } else {
        return b;
    }
}

Different Types of Functions

1. Functions with No Parameters and No Return Value

#include <iostream>
using namespace std;

// Function prototype
void displayMenu();
void drawLine();

int main() {
    displayMenu();
    drawLine();
    return 0;
}

// Function definition
void displayMenu() {
    cout << "1. Start Game" << endl;
    cout << "2. Set Options" << endl;
    cout << "3. Exit Program" << endl;
}

void drawLine() {
    cout << "-------------------" << endl;
}

2. Functions with Parameters and No Return Value

#include <iostream>
using namespace std;

// Function prototype
void printStars(int count);
void displayInfo(string name, int age, double score);

int main() {
    printStars(5);
    displayInfo("Zhang San", 20, 88.5);
    printStars(10);
    
    return 0;
}

// Function definition
void printStars(int count) {
    for (int i = 0; i < count; i++) {
        cout << "*";
    }
    cout << endl;
}

void displayInfo(string name, int age, double score) {
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Score: " << score << endl;
}

3. Functions with Parameters and Return Value

#include <iostream>
#include <cmath>
using namespace std;

// Function prototype
double calculateBMI(double weight, double height);
bool isEven(int number);
string getGrade(double score);

int main() {
    // Calculate BMI
    double bmi = calculateBMI(70.5, 1.75);
    cout << "BMI Index: " << bmi << endl;
    
    // Check even or odd
    int num = 15;
    if (isEven(num)) {
        cout << num << " is even" << endl;
    } else {
        cout << num << " is odd" << endl;
    }
    
    // Get grade
    double score = 85.5;
    string grade = getGrade(score);
    cout << "Score " << score << " corresponds to grade: " << grade << endl;
    
    return 0;
}

// Function definition
double calculateBMI(double weight, double height) {
    return weight / (height * height);
}

bool isEven(int number) {
    return (number % 2 == 0);
}

string getGrade(double score) {
    if (score >= 90) return "A";
    else if (score >= 80) return "B";
    else if (score >= 70) return "C";
    else if (score >= 60) return "D";
    else return "F";
}

Practical Example: Calculator Program

#include <iostream>
using namespace std;

// Function prototype
void showCalculatorMenu();
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
int getIntegerInput(string prompt);

int main() {
    int choice;
    double num1, num2, result;
    
    do {
        showCalculatorMenu();
        choice = getIntegerInput("Please select an operation (1-5): ");
        
        if (choice >= 1 && choice <= 4) {
            cout << "Enter the first number: ";
            cin >> num1;
            cout << "Enter the second number: ";
            cin >> num2;
            
            switch(choice) {
                case 1:
                    result = add(num1, num2);
                    cout << "Result: " << num1 << " + " << num2 << " = " << result << endl;
                    break;
                case 2:
                    result = subtract(num1, num2);
                    cout << "Result: " << num1 << " - " << num2 << " = " << result << endl;
                    break;
                case 3:
                    result = multiply(num1, num2);
                    cout << "Result: " << num1 << " * " << num2 << " = " << result << endl;
                    break;
                case 4:
                    if (num2 != 0) {
                        result = divide(num1, num2);
                        cout << "Result: " << num1 << " / " << num2 << " = " << result << endl;
                    } else {
                        cout << "Error: Divisor cannot be zero!" << endl;
                    }
                    break;
            }
        } else if (choice != 5) {
            cout << "Invalid choice, please re-enter!" << endl;
        }
        
        cout << endl;
    } while (choice != 5);
    
    cout << "Thank you for using the calculator program!" << endl;
    return 0;
}

// Function definition
void showCalculatorMenu() {
    cout << "=== Simple Calculator ===" << endl;
    cout << "1. Addition" << endl;
    cout << "2. Subtraction" << endl;
    cout << "3. Multiplication" << endl;
    cout << "4. Division" << endl;
    cout << "5. Exit" << endl;
    cout << "=================" << endl;
}

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

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

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

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

int getIntegerInput(string prompt) {
    int value;
    cout << prompt;
    cin >> value;
    return value;
}

Mathematical Utility Function Example

#include <iostream>
#include <cmath>
using namespace std;

// Function prototype
bool isPrime(int number);
long long factorial(int n);
double circleArea(double radius);
double celsiusToFahrenheit(double celsius);
void printMultiplicationTable(int number);

int main() {
    // Test prime number check
    int testNumber = 17;
    if (isPrime(testNumber)) {
        cout << testNumber << " is prime" << endl;
    } else {
        cout << testNumber << " is not prime" << endl;
    }
    
    // Calculate factorial
    int n = 5;
    cout << n << "! = " << factorial(n) << endl;
    
    // Calculate circle area
    double radius = 3.0;
    cout << "Circle area with radius " << radius << ": " << circleArea(radius) << endl;
    
    // Temperature conversion
    double celsius = 25.0;
    cout << celsius << "°C = " << celsiusToFahrenheit(celsius) << "°F" << endl;
    
    // Print multiplication table
    printMultiplicationTable(7);
    
    return 0;
}

// Function definition
bool isPrime(int number) {
    if (number <= 1) return false;
    if (number == 2) return true;
    if (number % 2 == 0) return false;
    
    for (int i = 3; i * i <= number; i += 2) {
        if (number % i == 0) {
            return false;
        }
    }
    return true;
}

long long factorial(int n) {
    if (n < 0) return -1; // Error case
    if (n == 0 || n == 1) return 1;
    
    long long result = 1;
    for (int i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}

double circleArea(double radius) {
    return M_PI * radius * radius;
}

double celsiusToFahrenheit(double celsius) {
    return (celsius * 9.0 / 5.0) + 32.0;
}

void printMultiplicationTable(int number) {
    cout << number << " multiplication table:" << endl;
    for (int i = 1; i <= 10; i++) {
        cout << number << " × " << i << " = " << number * i << endl;
    }
}

Key Points Summary

  1. Function Prototype: Declare functions before main(), informing the compiler of their existence
  2. Function Call: Call functions where needed, passing necessary parameters
  3. Function Definition: Implement the specific functionality of the function, usually after main()
  4. Return Value: Functions can return a value or not return (void)
  5. Parameter Passing: Functions can accept zero, one, or multiple parameters

Compile and Run

# Compile the program
g++ -o user_functions user_functions.cpp

# Run the program
./user_functions

User-defined functions make code more modular, readable, and maintainable. By breaking down complex tasks into smaller functions, code reusability and testability can be improved. This is one of the most important concepts in C++ programming, laying a solid foundation for further learning in object-oriented programming and class design.

Leave a Comment