In-Built Functions
In addition to user-defined functions, C++ provides a rich set of in-built functions that can be used to perform various operations. These functions are already implemented in the C++ standard library, and you can directly use them in your code.
In this lesson, we will explore some commonly used in-built functions in C++.
Commonly Used In-Built Functions
sqrt
The sqrt
function is used to calculate the square root of a number. It takes a single argument of type double
or float
and returns the square root as a double
or float
value.
1#include <cmath>
2
3int main() {
4 int num = 16;
5
6 // Using in-built function
7 double squareRoot = sqrt(num);
8
9 return 0;
10}
abs
The abs
function is used to calculate the absolute value of a number. It takes a single argument of any integral type (int
, long
, char
, etc.) and returns the absolute value as the same type.
1#include <cmath>
2
3int main() {
4 int num = -10;
5
6 // Using in-built function
7 int absoluteValue = abs(num);
8
9 return 0;
10}
max and min
The max
and min
functions are used to find the maximum and minimum values between two numbers, respectively. They take two arguments of the same type and return the maximum or minimum value as the same type.
1#include <algorithm>
2
3int main() {
4 int a = 5;
5 int b = 10;
6
7 // Using in-built functions
8 int maximumValue = max(a, b);
9 int minimumValue = min(a, b);
10
11 return 0;
12}
xxxxxxxxxx
int main() {
int num = 16;
// Using in-built functions
int squareRoot = sqrt(num);
int absoluteValue = abs(-10);
int maximumValue = max(5, 10);
int minimumValue = min(5, 10);
std::cout << "Square root of " << num << " is " << squareRoot << std::endl;
std::cout << "Absolute value of -10 is " << absoluteValue << std::endl;
std::cout << "Maximum value between 5 and 10 is " << maximumValue << std::endl;
std::cout << "Minimum value between 5 and 10 is " << minimumValue << std::endl;
return 0;
}