Lesson 34 of 60 – Functions in C++
57%

Functions in C++

A function is a reusable block of code designed to perform a specific task. Functions help divide a large program into smaller, organized, and reusable parts.

Note: A function can be called whenever you need to perform its task. This helps reduce code repetition and makes programs easier to understand and maintain.

1. What is a Function?

A function is a named block of code that performs a particular task.

void greet() {

    std::cout << "Hello";

}

Here, greet() is a function that displays a message.

2. Why Use Functions?

Functions provide several advantages:

  • They reduce code repetition.
  • They make programs easier to understand.
  • They make code easier to maintain.
  • They allow code reuse.
  • They divide a large program into smaller tasks.
  • They make testing and debugging easier.

3. Basic Function Syntax

returnType functionName() {

    // statements

}

For example:

void display() {

    std::cout << "Welcome";

}

Here, void is the return type and display is the function name.

4. Function Declaration

A function declaration tells the compiler about a function before it is used.

void greet();

This is also called a function prototype.

5. Function Definition

The function definition contains the actual statements that the function executes.

void greet() {

    std::cout << "Hello World";

}

The code between the braces is the function body.

6. Calling a Function

A function does not execute just because it is defined. It must be called.

#include <iostream>

void greet() {

    std::cout << "Hello World";

}

int main() {

    greet();

    return 0;
}

The statement greet(); calls the function.

7. Function Execution Flow

void greet() {

    std::cout << "Hello";

}

int main() {

    greet();

    std::cout << " World";

    return 0;
}

The execution is:

  1. Program starts from main().
  2. greet() is called.
  3. The statements inside greet() execute.
  4. Control returns to main().
  5. The next statement in main() executes.

8. Function with void Return Type

The void return type means that the function does not return a value.

void message() {

    std::cout << "Welcome to C++";

}

This function performs an action but does not return a result.

9. Function Returning int

A function can return an integer using the int return type.

int getNumber() {

    return 100;

}

Calling the function:

int number = getNumber();

std::cout << number;

Output:

100

10. Function Returning double

double getPrice() {

    return 99.50;

}

int main() {

    double price = getPrice();

    std::cout << price;

    return 0;
}

A function can return values of different data types.

11. Function to Add Two Numbers

int add() {

    int a = 10;
    int b = 20;

    return a + b;
}

int main() {

    int result = add();

    std::cout << result;

    return 0;
}

The function calculates and returns the sum of two numbers.

12. Function with Parameters

Parameters allow us to pass data into a function.

void greet(std::string name) {

    std::cout << "Hello " << name;

}

The function can be called as:

greet("Rahul");

Output:

Hello Rahul

13. Function with Two Parameters

int add(int a, int b) {

    return a + b;

}

int main() {

    std::cout << add(10, 20);

    return 0;
}

The values 10 and 20 are passed to the parameters a and b.

14. Function with Multiple Calls

void greet() {

    std::cout << "Hello" << std::endl;

}

int main() {

    greet();
    greet();
    greet();

    return 0;
}

The same function can be called multiple times.

15. Function for Multiplication

int multiply(int a, int b) {

    return a * b;

}

int main() {

    int result = multiply(5, 4);

    std::cout << "Result = "
              << result;

    return 0;
}

Output:

Result = 20

16. Function for Checking Even Number

bool isEven(int number) {

    return number % 2 == 0;

}

int main() {

    if (isEven(10)) {

        std::cout << "Even number";

    }

    return 0;
}

The function returns either true or false.

17. Function for Finding Maximum

int maximum(int a, int b) {

    if (a > b) {
        return a;
    }

    return b;
}

int main() {

    std::cout << maximum(25, 40);

    return 0;
}

The function returns the larger of the two numbers.

18. Function Declaration Before main()

#include <iostream>

void greet();

int main() {

    greet();

    return 0;
}

void greet() {

    std::cout << "Hello World";

}

The declaration allows the function to be called before its definition.

19. Function Definition Before main()

#include <iostream>

void greet() {

    std::cout << "Hello World";

}

int main() {

    greet();

    return 0;
}

If the function definition appears before main(), a separate declaration is not necessary for this simple example.

20. Function with No Parameters and Return Value

int getAge() {

    return 20;

}

int main() {

    int age = getAge();

    std::cout << "Age = "
              << age;

    return 0;
}

A function can have no parameters and still return a value.

21. Function with Parameters and Return Value

int square(int number) {

    return number * number;

}

int main() {

    int result = square(6);

    std::cout << "Square = "
              << result;

    return 0;
}

This function accepts a number and returns its square.

22. Function for Factorial

int factorial(int number) {

    int result = 1;

    for (int i = 1; i <= number; i++) {

        result *= i;
    }

    return result;
}

int main() {

    std::cout << factorial(5);

    return 0;
}

The function uses a loop to calculate the factorial and returns the result.

23. Function for Multiplication Table

void table(int number) {

    for (int i = 1; i <= 10; i++) {

        std::cout << number
                  << " x "
                  << i
                  << " = "
                  << number * i
                  << std::endl;
    }
}

int main() {

    table(7);

    return 0;
}

A function can contain loops and other programming statements.

24. Function Calling Another Function

void message() {

    std::cout << "Welcome";

}

void display() {

    message();

    std::cout << " to C++";

}

int main() {

    display();

    return 0;
}

One function can call another function.

25. Function with User Input

int add(int a, int b) {

    return a + b;

}

int main() {

    int x, y;

    std::cout << "Enter first number: ";
    std::cin >> x;

    std::cout << "Enter second number: ";
    std::cin >> y;

    std::cout << "Sum = "
              << add(x, y);

    return 0;
}

The user provides values, which are passed to the function.

26. Common Mistakes with Functions

  • Calling a function with the wrong number of arguments.
  • Using an incorrect return type.
  • Forgetting the return statement when a value is required.
  • Using a function before declaring it when its definition appears later.
  • Using incompatible argument types.
  • Giving confusing names to functions.
  • Repeating code instead of creating a reusable function.
int add(int a, int b) {

    return a + b;

}

The arguments passed to the function should match the expected parameters appropriately.

27. Practical Calculator Functions

#include <iostream>

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;
}

int main() {

    int a = 20;
    int b = 5;

    std::cout << "Addition = "
              << add(a, b)
              << std::endl;

    std::cout << "Subtraction = "
              << subtract(a, b)
              << std::endl;

    std::cout << "Multiplication = "
              << multiply(a, b)
              << std::endl;

    return 0;
}

Different functions perform different calculator operations.

28. Practical Student Result Function

#include <iostream>

char getGrade(int marks) {

    if (marks >= 90) {
        return 'A';
    }
    else if (marks >= 75) {
        return 'B';
    }
    else if (marks >= 60) {
        return 'C';
    }
    else if (marks >= 40) {
        return 'D';
    }

    return 'F';
}

int main() {

    int marks;

    std::cout << "Enter marks: ";
    std::cin >> marks;

    std::cout << "Grade = "
              << getGrade(marks);

    return 0;
}

The function accepts marks and returns a grade character.

29. Best Practices for Functions

  • Give functions meaningful names.
  • Keep each function focused on a specific task.
  • Use parameters to make functions reusable.
  • Use an appropriate return type.
  • Avoid unnecessarily large functions.
  • Declare functions before using them when required.
  • Use functions to reduce repeated code.
  • Keep function logic simple and readable.
int calculateTotal(int price, int quantity) {

    return price * quantity;

}

30. Functions – Final Summary

Concept Meaning
Function A reusable block of code that performs a specific task.
Declaration Tells the compiler about a function.
Definition Contains the actual function code.
Call Executes the function.
Parameter A variable that receives data passed to a function.
Argument A value passed when calling a function.
Return Type Specifies the type of value returned by a function.
void Indicates that the function does not return a value.
returnType functionName(parameters) {

    // statements

}

📌 Key Points

  • A function is a reusable block of code.
  • Functions help reduce code repetition.
  • A function can have parameters.
  • A function can return a value.
  • void means the function does not return a value.
  • A function can be declared before its definition.
  • A function is executed when it is called.
  • Functions can call other functions.
  • Functions can contain loops and conditional statements.
  • Good functions should perform a clear and specific task.

🧠 Quick Quiz

Question: What is the main purpose of a function in C++?