Mark As Completed Discussion

User-Defined Functions

In C++, you can create your own user-defined functions to perform specific tasks. User-defined functions allow you to break down your code into smaller, more manageable pieces that can be reused throughout your program.

When creating a user-defined function, you need to provide the following information:

  • The name of the function
  • The parameters (inputs) the function requires, if any
  • The return type of the function, if any

Here is an example of a user-defined function that calculates the factorial of a number:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int factorial(int n) {
5  if (n == 0)
6    return 1;
7  else
8    return n * factorial(n - 1);
9}
10
11int main() {
12  int num = 5;
13  int result = factorial(num);
14
15  cout << "The factorial of " << num << " is: " << result << endl;
16
17  return 0;
18}

In this example, we have defined a function called factorial that takes an integer n as a parameter and returns an integer. The function uses recursion to calculate the factorial of the given number.

When you run the code, the output will be:

SNIPPET
1The factorial of 5 is: 120

User-defined functions can be used to perform a wide range of tasks, from simple calculations to complex algorithms. They allow you to write modular and reusable code, improving the overall structure and maintainability of your programs.

Next, we will explore more advanced concepts related to user-defined functions, such as function overloading and function templates.