Function in c++ language
Suppose you must write a C++ program that computes the square root of a number supplied by the user.
#include <iostream>
int main()
{
double input;
// Get value from the user
std::cout << "Enter number: ";
std::cin >> input;
double diff;
// Compute a provisional square root
double root = 1.0;
do {
// Loop until the provisional root
// is close enough to the actual root
root = (root + input/root) / 2.0;
std::cout << "root is " << root << '\n';
// How bad is the approximation?
diff = root * root - input;
}
while (diff > 0.0001 || diff < -0.0001);
// Report approximate square root
std::cout << "Square root of " << input << " = " << root << '\n';
}
Enter number: 100
root is 50.5
root is 26.2401
root is 15.0255
root is 10.8404
root is 10.0326
root is 10.0001
root is 10
Square root of 100 = 10
While this code may be acceptable for many applications, better algorithms exist that work faster and produce more precise answers. Another problem with the code is this: What if you are working on a significant scientific or engineering application and must use different formulas in various parts of the source code, and each of these formulas involve square roots in some way?
Introduction to Using Functions
In mathematics, a function computes a result from a given value; for example, from the function definition f(x) = 2x + 3, we can compute f(5) = 13 and f(0) = 3. A function in C++ works like a mathematical function. To introduce the function concept, we will look at the standard C++ function that implements mathematical square root
#include <iostream>
#include <cmath>
int main()
{
double input;
// Get value from the user
std::cout << "Enter number: ";
std::cin >> input;
// Compute the square root
double root = sqrt(input);
// Report result
std::cout << "Square root of " << input << " = " << root << '\n';
}
The diagram on the right visualizes the execution of the program on the left. Time flows from left to right. A rectangular bar represents the time that a function is active. A C++ program’s execution begins with its main function. Here, main calls the sqrt function twice. The shaded parts of main’s bar shows the times main has to wait for sqrt to complete.
#include <iostream>
#include <cmath>
int main()
{
double x = 16.0;
// Pass a literal value and display the result
std::cout << sqrt(16.0) << '\n';
// Pass a variable and display the result
std::cout << sqrt(x) << '\n';
// Pass an expression
std::cout << sqrt(2 * x - 5) << '\n';
// Assign result to variable
double y = sqrt(x);
// Use result in an expression
y = 2 * sqrt(x + 16) - 4;
// Use result as argument to a function call
y = sqrt(sqrt(256.0));
std::cout << y << '\n';
}
Standard Math Functions
The cmath library provides much of the functionality of a scientific calculator. Table 8.1 lists only a few of the available functions.
double sqrt(double x)
Computes the square root of a number: sqrt(x) =√x
double exp(double x)
Computes e raised a power: exp(x) = ex
double log(double x)
Computes the natural logarithm of a number: log(x) = log(e)x = lnx
double pow(double x, double y)
Raises one number to a power of another: pow(x, y) = xy
double fabs(double x)
Computes the absolute value of a number: fabs(x) = |x|
Code Example
#include <iostream>
#include <cmath>
int main()
{
int max_value;
std::cout << "Display primes up to what value? ";
std::cin >> max_value;
for (int value = 2; value <= max_value; value++)
{
// See if value is prime
bool is_prime = true; // Provisionally, value is prime
double r = value, root = sqrt(r);
// Try all possible factors from 2 to the square
// root of value
for (int trial_factor = 2;is_prime && trial_factor <= root; trial_factor++)
is_prime = (value % trial_factor != 0);
if (is_prime)
std::cout << value << " "; // Display the prime number
}
std::cout << '\n'; // Move cursor down to next line
}
The function names are the same, but the parameter types differ. We say that the sqrt function is overloaded. (Overloaded functions are covered in more detail in Section 10.3.) When a caller invokes the sqrt function, the compiler matches the call to the closest matching prototype. If the caller passes a double parameter, the compiler generates code to call the double version. If the caller instead passes a float variable, the compiler selects the float version of sqrt.
Maximum and Minimum
#include <iostream>
#include <algorithm>
int main()
{
int value1, value2;
std::cout << "Please enter two integer values: ";
std::cin >> value1 >> value2;
std::cout << "max = " << std::max(value1, value2)
<< ", min = " << std::min(value1, value2) << '\n';
}
clock Function
The clock function from the library requests from the operating system the amount of time an executing program has been running. The units returned by the call clock() is system dependent, but it can be converted into seconds with the constant CLOCKS_PER_SEC, also defined in the ctime library. Under Visual C++, the CLOCKS_PER_SEC constant is 1,000, which means the call clock() returns the number of milliseconds that the program has been running.
#include <iostream>
#include <ctime>
int main()
{
char letter;
std::cout << "Enter a character: ";
clock_t seconds = clock(); // Record starting time
std::cin >> letter;
clock_t other = clock(); // Record ending time
std::cout << static_cast<double>(other - seconds)/CLOCKS_PER_SEC
<< " seconds\n";
}
Character Functions
The C library provides a number of character functions that are useful to C++ programmers.
#include <iostream>
#include <cctype>
int main()
{
for (char lower = 'a'; lower <= 'z'; lower++)
{
char upper = toupper(lower);
std::cout << lower << " => " << upper << '\n';
}
}
//Output
a => A
b => B
c => C
d => D
int toupper(int ch)
Returns the uppercase version of the given character;
returns the original character if no uppercase version exists (such as for punctuation or digits)
int tolower(int ch)
Returns the lowercase version of the given character; returns the original character if no
lowercase version exists (such as for punctuation or digits)
int isupper(int ch)
Returns a nonzero value (true) if ch is an uppercase letter (’A’–’Z’); otherwise, it returns
0 (false)
int islower(int ch)
Returns a nonzero value (true) if ch is an lowercase letter (’a’–’z’); otherwise, it returns
0 (false)
Random Numbers
Some applications require behavior that appears random. Random numbers are useful particularly in games and simulations. For example, many board games use a die (one of a pair of dice) to determine how many places a player is to advance.
#include <iostream>
#include <cstdlib>
int main()
{
srand(23);
for (int i = 0; i < 100; i++)
{
int r = rand();
std::cout << r << " ";
}
std::cout << '\n';
}