Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter Four Functions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Chapter Four

Functions in C++

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 easy to become bogged down in the details of a
complex problem. The trick to managing complexity is to break down the problem into more
manageable pieces. Each piece has its own details that must be addressed, but these details are
hidden as much as possible within that piece. The problem is ultimately solved by putting these
pieces together to form the complete solution.
So far all of our programs have been written within one function main. As the number of
statements within a function increases, the function can become unwieldy. The code within such
a function that does all the work by itself is called monolithic code. Monolithic code that is long
and complex is undesirable for several reasons:
 It is difficult to write correctly. All the details in the entire piece of code must be
considered when writing any statement within that code.
 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. The effects of an erroneous statement that appears
earlier in the code may not become apparent until a correct statement later uses the
erroneous statement’s incorrect result.
 It is difficult to extend. All the details in the entire sequence of code must be well
understood before it can be modified. If the code is complex, this may be a formidable
task.

The best way to develop and maintain a large program is to construct it from small, simple
pieces, or components. This technique is called divide and conquer. A small function that
performs one task is easier to test and debug than a larger function that performs many tasks.

C++ programs are typically written by combining new functions and classes the programmer
writes with "prepackaged" functions and classes available in the C++ Standard Library. In this
chapter, we concentrate on functions.
The C++ Standard Library provides a rich collection of functions for performing common
mathematical calculations, string manipulations, character manipulations, input/output, error
checking and many other useful operations. This makes the programmer's job easier, because
these functions provide many of the capabilities programmers need. The C++ Standard Library
functions are provided as part of the C++ programming environment.

Functions allow the programmer to modularize a program by separating its tasks into self-
contained units. The statements in the function bodies are written only once, but are reused from
perhaps several locations in a program and are hidden from other functions.

The compiler refers to the function prototype to check that calls to a method contain the correct
number and types of arguments, that the types of the arguments are in the correct order and that
the value returned by the function can be used correctly in the expression that called the function.

Math Library Functions

Sometimes functions are not members of a class. Such functions are called global functions.
Like a class's member functions, the function prototypes for global functions are placed in header
files, so that the global functions can be reused in any program that includes the header file and
that can link to the function's object code.

The <cmath> header file provides a collection of functions that enable you to perform common
mathematical calculations. To use the following list of math library function we should include
<cmath> header file in the program.

Method Description Example


ceil( x ) rounds x to the smallest integer not less ceil( 9.2 ) is 10.0, ceil( -9.8 ) is -9.0
than x
cos( x ) trigonometric cosine of x (x in radians) cos( 0.0 ) is 1.0
exp( x ) exponential function ex exp( 1.0 ) is 2.71828, exp( 2.0 ) is 7.38906

fabs( x ) absolute value of x fabs( 5.1 ) is 5.1, fabs( 0.0 ) is 0.0


fabs( -8.76 ) is 8.76
floor( x ) rounds x to the largest integer not greater floor( 9.2 ) is 9.0, floor( -9.8 ) is -10.0
than x
fmod( x, y ) remainder of x/y as a floating-point number fmod( 13.657, 2.333 ) is 1.992
log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0, log( 7.389056 ) is
2.0
log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0, log10( 100.0 ) is 2.0
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128, pow( 9, .5 ) is 3
sin( x ) trigonometric sine of x (x in radians) sin( 0.0 ) is 0
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0, sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x (x in radians) tan( 0.0 ) is 0

There are two aspects to every C++ function:


 Function definition
 Function invocation/ Function Call
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. General structure of C++ function
definition is:
Return_Value_Type Function_Name (Parameter_List)
{
Body of function;
}
A function definition consists of four parts:
 Name: - every function in C++ has a name; the name should be valid identifier. As with
variable names, the name chosen for a function should accurately portray its intended
purpose or describe its functionality.
 Type: - every function definition should have 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 voids
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). Unlike function prototypes, however, parameters usually
have names associated with each type.
 Body: - every function definition has a body enclosed by curly braces. The body contains
the code to be executed when the function is invoked.
Function Prototype

A function prototype (also called a function declaration) tells the compiler the name of a
function, the type of data returned by the function, the number of parameters the function expects
to receive, the types of those parameters and the order in which the parameters of those types are
expected. In C++ function prototype can be represented as:

Syntax: - Return-type Function-Name (Parameter-Type);


e.g. double sqrt(double); //standard/ library function
int product(int, int, int);//user defined function

Function invocation/Calling

While creating a C++ function, you give a definition of what the function has to do. To use a
function, you will have to call or invoke that function. When a program calls a function, program
control is transferred to the called function. A called function performs defined task and when
it’s return statement is executed or when its function-ending closing brace is reached, it returns
program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name,
and if function returns a value, then you can store returned value.
Syntax: - Function_Name (Parameter_List);
e.g #include<iostream.h>
#include<cmath>
int quadratic(int a, int b, int c)
{
int x,y; //Function Definition for quadratic
x=((-b)+(sqrt((b*b)-(4*a*c))))/(2*a);
cout<<x<<"\n";
y=((-b)-(sqrt((b*b)-(4*a*c))))/(2*a);
cout<<y<<"\n";
return(x,y);
}
void Information() //Function with void return type
{ cout<<"this is general information about function \n"; }
int main()
{
Information(); Function Invocation/Calling
quadratic(1,-2,-15);
return 0;
}

Global vs. local variables

Local Variable: - A variable declared within a block and not accessible outside of that block.
Local variables are in memory only as long as the function is executing. When the function is
called, memory space is created for its local variables. When the function ends (returns) all of its
local variables are destroyed.
Global Variable: - A variable declared outside of all the functions in a program.
e.g. #include<iostream.h>
int n; // Global variable
int add(int y)
{int i; //Local variable
int sum=0
for (i=0;i<y; i++) //Function Definition for sum
{
sum=sum+i;}
return (sum);
}
int main()
{
cout<<”Enter the number”;
cin>>n;
add(n); // calling/invoking function sum() inside main function
return 0;
}

Scope Resolution operator

It is possible to declare local and global variables of the same name. C++ provides the unary
scope resolution operator (::) to access a global variable when a local variable of the same
name is in scope. The unary scope resolution operator cannot be used to access a local variable
of the same name in an outer block. A global variable can be accessed directly without the unary
scope resolution operator if the name of the global variable is not the same as that of a local
variable in scope.

#include<iostream.h> Output
int x=50; //Global variable
void display()
{
int x=10;
int y=20; //Local variables
cout<<x<<"\n";
cout<<y<<"\n";
cout<<::x<<"\n"; //Accessing global variable having the same name with local
cout<<x+y<<"\n";
cout<<::x+y<<"\n";
}
int main()
{
display(); //Calling function display() in the main function
return 0;
}

Overloaded Function

In C++, a program can have multiple functions with the same name. When two or more
functions within a program have the same name, the function is said to be overloaded. The
functions must be different somehow, or else the compiler would not know how to associate a
call with a particular function definition.
The compiler identifies a function by more than its name; a function is uniquely identified by its
signature. A function signature consists of the function’s name and its parameter list. In the
parameter list, only the types of the formal parameters are important, not their names. If the
parameter types do not match exactly, both in number and position, then the function signatures
are different.
#include<iostream.h>
int add(int x, int y) //Overloaded function add () with two integer parameter
{ int c;
c=x+y;
cout<<c<<"\n";
return (c); }
float add(float x, float y) //Overloaded function add () with two float parameter
{float c;
c=x+y;
cout<<c<<"\n";
return (c);}
float add(int x, int y, float k) //Overloaded function add () with three parameter
{float c;
c=x+y+k;
cout<<c<<"\n";
return(c);}
int main()
{add(3.5,2);
add(5,2);
add(2,3,15.5);
return 0;}

Default arguments

During function definition or declaration we can specify a default value (initial value) for each of
the parameters. This value will be used if the corresponding argument is left blank when calling
to the function. If a value for that parameter is not passed when the function is called, the default
value is used, but if a value is specified this default value is ignored and the passed value is used
instead.
e.g. #include <iostream.h>
int add (int a=5, int b=10) //Default values for a is 5 and b is 10
{
int sum; Output
sum=a+b;
return (sum);
}

int main ()
{
cout << add (2,5)<<"\n"; //Both parameters a and b are assigned
cout << add (2)<<"\n"; //parameter a is assigned but b is assigned by default 10
cout << add (); // Both parameters a and b takes default value
return 0;
}

Recursive function

A recursive function is a function that calls itself, either directly or indirectly (through another
function).

e.g. ( ) {
( )

f(0)=0, f(1)=f(1-1)+12, f(2)=f(2-1)+22…..f(n)=f(n-1)+n2, where n is any natural number

Recursive function is applicable in any function/ mathematical problems that call itself.
Factorial of a number
N!=N.(N-1).(N-2)....(1)!, where 1!=1
e.g. 5!=5*4!=5*4*3!=5*4*3*2!=5*4*3*2*1!=120
#include<iostream.h>
int fact(int n)
{int x;
if(n==1)
x=1;
else
x=x*fact(n-1);
cout<<x;
return 0;}
int main()
{
fact(5);
return 0;
}

Fibonacci series:-The Fibonacci series can be defined recursively as follows:

f (0) = 0, f (1) = 1, f (n) = f (n-1) + f (n-2) where n is any positive integer

e.g. Fabonacci series of a number between 0 and 7 is: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55

#include<iostream.h>
int fab(int n)
{
int f;
if(n==0)
{f=0;
return(f);}
else if(n==1)
{f=1;
return(f);}
else
{f=fab(n-1)+fab(n-2);
return(f);}}
int main()
{
cout<<fab(10);
return 0;
}

Recursion vs. Iteration


Both iteration and recursion are based on a control statement. Iteration uses a repetition structure;
recursion uses a selection structure. Iteration and recursion both involve a termination test:
Iteration terminates when the loop-continuation condition fails; recursion terminates when a base
case is recognized. Iteration with counter-controlled repetition and recursion both gradually
approach termination: Iteration modifies a counter until the counter assumes a value that makes
the loop-continuation condition fail; recursion produces simpler versions of the original problem
until the base case is reached. Both iteration and recursion can occur infinitely: An infinite loop
occurs with iteration if the loop-continuation test never becomes false; infinite recursion occurs
if the recursion step does not reduce the problem during each recursive call in a manner that
converges on the base case.

Function and arrays

Sometimes arrays can be used as parameter in the function and the elements can be passed when
the function is called in another function.

e.g. write c++ program that have two functions sum(), Product(); sum() function computes the
sum of array elements of array x; product() function computes the product of array elements of
array x.

#include<iostream.h>
int sum(int a[], int n)
{
int s=0;
for (int i=0; i<=n;i++)
{
s=s + a[i];
}
cout<<s<<"\n";
return (s);
}
int product(int a[], int n)
{
int p=1;
for (int i=0; i<=n;i++)
{
p= p*a[i];
}
cout<<p<<"\n";
return (p);
}
int main()
{
int x[]={20,30,5,1,6,7};
sum(x,5);
product(x,5);
}

You might also like