Writing user define function

Writing user define function

As programs become more complex, programmers must structure their programs in such a way as to effectively manage their complexity. Most humans have a difficult time keeping track of too many pieces of information at one time.

It is difficult to debug. If the sequence of code does not work correctly, it is often difficult to find the source of the error.

It is difficult to extend. If the code is complex, this may be a formidable task.

Function Basics

Recall the “handwritten” square root code we saw in. We know that the better option is the standard library function sqrt; we will illustrate custom function development by writing our own square root function based on the code

#include <iostream>
#include <iomanip>
#include <cmath>
// Compute an approximation of
// the square root of x
double square_root(double x) 
{
    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 + x/root) / 2.0;
        //std::cout << "root is " << root << '\n';
        // How bad is the approximation?
        diff = root * root - x;
       } while (diff > 0.0001 || diff < -0.0001);
    return root;
}

int main() 
{
    // Compare the two ways of computing the square root
    for (double d = 1.0; d <= 10.0; d += 0.5)
    std::cout << std::setw(7) << square_root(d) << " : " << sqrt(d) << '\n';
}

1. Function definition. The definition of a function specifies the function’s return type and parameter types, and it provides the code that determines the function’s behavior. the definition of the square_root function appears above the main function.

2. Function invocation. A programmer uses a function via a function invocation. The main function invokes both our function and the function. function has exactly one definition but may have many invocations.

A function definition consists of four parts:

Name—every function in C++ has a name. The name is an identifier (see Section 3.3). As with variable names, the name chosen for a function should accurately portray its intended purpose or describe its functionality.

Type—every function has a return type. If the function returns a value to its caller, its type corresponds to the type of the value it returns. The special type void signifies that the function does not return a value.

Parameters—every function must specify the types of parameters that it accepts from callers. The parameters appear in a parenthesized comma-separated list like in a function prototype (see Section 8.1).

Body—every function definition has a body enclosed by curly braces. The body contains the code to be executed when the function is invoked.

#include <iostream>
// Definition of the prompt function
void prompt() {
std::cout << "Please enter an integer value: ";
}
int main() {
int value1, value2, sum;
std::cout << "This program adds together two integers.\n";
prompt(); // Call the function
std::cin >> value1;
prompt(); // Call the function again
std::cin >> value2;
sum = value1 + value2;
std::cout << value1 << " + " << value2 << " = " << sum << '\n';
}

write without function

#include <iostream>
int main() {
for (int i = 1; i <= 10; i++)
std::cout << i << '\n';
}
1
2
3
4
5
6
7
8
9
10

Write with function

#include <iostream>
// Count to n and print each number on its own line
void count_to_n(int n) 
{
    for (int i = 1; i <= n; i++)
    std::cout << i << '\n';
}
int main() 
{
    std::cout << "Going to count to ten . . .";
    count_to_n(10);
    std::cout << "Going to count to five . . .";
    count_to_n(5);
}

Code Example

#include <iostream>
// Definition of the prompt function
int prompt() 
{
    int result;
    std::cout << "Please enter an integer value: ";
    std::cin >> result;
    return result;
}
int main() 
{
    int value1, value2, sum;
    std::cout << "This program adds together two integers.\n";
    value1 = prompt(); // Call the function
    value2 = prompt(); // Call the function again
    sum = value1 + value2;
    std::cout << value1 << " + " << value2 << " = " << sum << '\n';
}

Syntex of Functions

//The general form of a function definition is
type name( parameterlist ) {
      body
}

Pass by Value

The default parameter passing mechanism in C++ is classified as pass by value, also known as call by value.

#include <iostream>
/*
* increment(x)
* Illustrates pass by value protocol.
*/
void increment(int x) 
{
    std::cout << "Beginning execution of increment, x = " << x << '\n';
    x++; // Increment x
    std::cout << "Ending execution of increment, x = " << x << '\n';
}

int main() 
{
    int x = 5;
    std::cout << "Before increment, x = " << x << '\n';
    increment(x);
    std::cout << "After increment, x = " << x << '\n';
}
//Output
Before increment, x = 5
Beginning execution of increment, x = 5
Ending execution of increment, x = 6
After increment, x = 5

Custom Functions vs. Standard Functions

#include <iostream>
double square_root(double x) 
{
    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 + x/root) / 2.0;
         std::cout << "root is " << root << '\n';
         // How bad is the approximation?
         diff = root * root - x;
       }
    while (diff > 0.0001 || diff < -0.0001);
         return root;
}

int main() 
{
     double input;
     // Get value from the user
     std::cout << "Enter number: ";
     std::cin >> input;
     // Report square root
     std::cout << "Square root of " << input << " = " << square_root(input) 
     << '\n';
}

• Your effort to produce the custom code is eliminated entirely; you can devote more effort to other parts of the application’s development.

• If you write your own custom code, you must thoroughly test it to ensure its correctness; your code is exercised only by the programs you write, and errors may not become apparent immediately. If your programs are not used by a wide audience, bugs may lie dormant for a long time. Standard library routines are well known and trusted;

• Standard routines are typically tuned to be very efficient; it takes a great deal of effort to make custom code efficient.