Types of function in C++

Functions in C++ can be categorized into two main types: library functions and user-defined functions. Here’s an explanation with easy examples for both:

1. Library Functions

Library functions are pre-defined functions provided by C++ standard libraries. They are included in header files and can be used directly in your programs without needing to define them yourself.

Example: Using the sqrt Function from the <cmath> Library

<#include <iostream>>
<#include <cmath> // Include the cmath library for the sqrt Function

using namespace std;

int main() {
double number, result;

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

// Using the library function sqrt
result = sqrt(number);

cout << "The square root of " << number << " is " << result << endl;

return 0;
}

Output:

Enter a number: 4
The square root of 4 is 2

Explanation:

Library Function: sqrt is a library function defined in the <cmath> header file.

Usage: Simply include the header and call sqrt with a number to get its square root.

2. User-Defined Functions

User-defined functions are created by the programmer to perform specific tasks. These functions are defined within your program and can be reused wherever needed.

Example: User-Defined Function to Calculate the Area of a Rectangle

<#include <iostream>>
using namespace std;

// Function declaration
double calculateArea(double width, double height);

int main() {
double width, height, area;

cout << "Enter height of the rectangle: " << endl;
cin >> height;

cout << "Enter width of the rectangle: " << endl;
cin >> width;

// Function call
area = calculateArea(width, height);

cout << "The area of the rectangle is " << area << endl;

return 0;
}

// Function definition
double calculateArea(double width, double height) {
return width * height;
}

Output:

Enter height of the rectangle: 20
Enter width of the rectangle: 30
The area of the rectangle is 600