Pure Function in C++

C++ProgrammingServer Side Programming

Pure functions always return the same result for the same argument values. They only return the result and there are no extra side effects like argument modification, I/O stream, output generation etc.

Some pure functions are sin(), strlen(), sqrt(), max(), pow(), floor() etc. Some impure functions are rand(), time() etc.

Some programs to demonstrate some of the pure functions are as follows −

strlen()

The strlen() function is used to find the length of a string. This is demonstrated in the following program −

Example

Live Demo

#include<iostream>
#include<string.h>
using namespace std;

int main() {
char str[] = "Rainbows are beautiful";
int count = 0;

cout<<"The string is "<< str <<endl;
cout <<"The length of the string is "<<strlen(str);

return 0;
}

Output

The output of the above program is as follows −

The string is Rainbows are beautiful
The length of the string is 22

sqrt()

The sqrt() function is used to find the square root of a number.This is demonstrated in the following program −

Example

Live Demo

#include<iostream>
#include<cmath>

using namespace std;
int main() {
int num = 9;

cout<<"Square root of "<< num <<" is "<<sqrt(num);

return 0;
}

Output

The output of the above program is as follows −

Square root of 9 is 3
Published on 23-Oct-2018 15:28:24