Uploaded by Bereket Abebayehu

functions

advertisement
CHAPTER – I
1.1 What is function?
A complex problem is often easier to solve by dividing it into several smaller parts, each of
which can be solved by itself. A function is a block of instructions that is executed when it is
called from some other point of the program. It provides a convenient way of packaging a
computational recipe, so that it can be used as often as required. Every C++ program has
at least one function, which is main() (uses other functions to solve the original problem), and all
the most trivial programs can define additional functions. Experience has shown that the best
way to develop and maintain large programs is to construct it from smaller pieces (modules).
This technique called “divide and conquer”. Using functions we can structure our programs in a
more modular way, accessing to all the potential that structured programming in C++ can offer
to us. You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is so each function performs a
specific task.
 The use of functions in a program allows
- a program to be broken into small tasks.
- a program to be written and debugged one small part at a time.
- several programmers to work on the same program.
- the code to be reused
 Summarized function basics.
C++ functions generally adhere to the following rules.
1. Every function must have a name.
2. Function names are made up and assigned by the programmer following the same rules
that apply to naming variables. They can contain up to 32 characters, they must begin
with a letter, and they can consist of letters, numbers, and the underscore (_) character.
3. All function names have one set of parenthesis immediately
following them. This helps you (and C++ compiler) differentiate them from variables.
4. The body of each function, starting immediately after
parenthesis of the function name, must be enclosed by braces.
1.2 Declaring, Defining and Calling functions
 Defining a Function: The general form of a C++ function definition is as follows:
1
return _ type, function _ name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the
parts of a function:
Return Type: A function may return a value. The return type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return type is the keyword void.
Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. The parameter list refers
to the type, order, and number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
Function Body: The function body contains a collection of statements that define what the
function does.
Example: Following is the source code for a function called max(). This function takes two
parameters num1 and num2 and returns the maximum between the two:
// function returning the max between two numbers
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;}
 Function Declarations: A function declaration tells the compiler about a function name
and how to call the function. The actual body of the function can be defined separately. A
function declaration has the following parts:
return _ type, function _ name( parameter list );
2
For the above defined function max (), following is the function declaration: int max (int num1,
int num2); Parameter names are not important in function declaration only their type is required,
so following is also valid declaration: int max(int, int); Function declaration is required when you
define a function in one source file and you call that function in another file. In such case, you
should declare the function at the top of the file calling the function.
 Calling a Function: 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 its 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. Function
calling has the following parts:
variable _ name = function _ name (parameter list);
For example:
#include <iostream.h>
// function declaration
int max(int num1, int num2);
int main (){
// local variable declaration:
int a = 100, b = 200, ret;
// calling a function to get max value.
ret = max(a, b);
cout<< "Max value is : " << ret <<endl;
return 0;
}
// function returning the max between two numbers
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;}
When we run the above code, the Output is: Max value is: 200
3
1.3 Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit. While calling a function, there are two
ways that arguments can be passed to a function:

Call by value: This method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument. By default, C++ uses call by
value to pass arguments. In general, this means that code within a function cannot alter the
arguments used to call the function. Consider the function swap() definition as follows.
// function definition to swap the values.
void swap (int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
Now, let us call the function swap() by passing actual values as in the following example:
#include<iostream.h>
#include<conio.h>
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x=y; /* put y into x */
y=temp; /* put x into y */
}
void swap(int x, int y);// function declaration
int main (){
int a = 100; // local variable declaration:
int b = 200;
cout<< "Before swap(substitute), value of a :" << a <<endl;
cout<< "Before swap, value of b :" << b <<endl;
// calling a function to swap the values.
4
swap(a, b);
cout<< "After swap, value of a :" << a <<endl;
cout<< "After swap, value of b :" << b <<endl;
getch();
return 0;}
When the above code is put together in a file, compiled and executed, it produces the following
result:
Before swap(substitute),, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
This shows that there is no change in the values though they had been changed inside the
function.

Call by pointer: The call by pointer method of passing arguments to a function copies the
address of an argument into the formal parameter. Inside the function, the address is used to
access the actual argument used in the call. This means that changes made to the parameter
affect the passed argument. To pass the value by pointer, argument pointers are passed to the
functions just like any other value. So accordingly you need to declare the function
parameters as pointer types as in the following function swap(), which exchanges the values
of the two integer variables pointed to by its arguments.
NB: To check the more detail about C++ pointers, kindly check C++ Pointers chapter. For now,
let us call the function swap () by passing values by pointer as in the following example:
// function definition to swap the values.
#include<iostream.h>
#include<conio.h>
void swap(int *x, int *y); // function declaration
void swap(int *x, int *y)
{ int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */
}
int main (){
int a = 100; // local variable declaration:
int b = 200;
cout << "Before swap, value of a :" << a << endl;
5
cout << "Before swap, value of b :" << b << endl;
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
getch();
return 0; }
When the above code is put together in a file, compiled and executed, it produces the following
result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

Call by reference: This method of passing arguments to a function copies the reference of
an argument into the formal parameter. Inside the function, the reference is used to access the
actual argument used in the call. This means that changes made to the parameter affect the
passed argument. To pass the value by reference, argument reference is passed to the
functions just like any other value. So accordingly you need to declare the function
parameters
as
reference
types
as
in the following function swap(), which exchanges the values of the two integer variables
pointed to by its arguments.
For now, let us call the function swap() by passing values by reference as in the following
example:
// function definition to swap the values.
#include<iostream.h>
#include<conio.h>
void swap(int&x, int&y)
{
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;}
6
int main (){
// local variable declaration:
int a = 100;
int b = 200;
cout<< "Before swap, value of a :" << a <<endl;
cout<< "Before swap, value of b :" << b <<endl;
/* calling a function to swap the values using variable reference.*/
swap(a, b);
cout<< "After swap, value of a :" << a <<endl;
cout<< "After swap, value of b :" << b <<endl;
getch();
return 0;}
When the above code is put together in a file, compiled and executed, it produces the following
result:
Before swap, value of a: 100
before swap, value of b: 200
after swap, value of a: 50
after swap, value of b: 60
By default, C++ uses call by value to pass arguments. In general, this means that code within a
function cannot alter the arguments used to call the function and above mentioned example while
calling max () function used the same method.
1.4 Default arguments and function overloading
 Default Values for Parameters (Default arguments)
When you define a function, you can specify a default value for each of the last parameters. This
value will be used if the corresponding argument is left blank when calling to the function. This
is done by using the assignment operator and assigning values for the arguments in the function
definition. If a value for that parameter is not passed when the function is called, the default
given value is used, but if a value is specified this default value is ignored and the passed value is
used instead. E.g.: Let us develop part of the program with default arguments.
#include<iostream.h>
#include<conio.h>
void Add_Display(int x=10, int y=20, int z=30)
{
cout<< (x+y+z)<<endl;
}
void Mult_Dispaly(long int x,long int y=70,long int z=90)
7
{
cout<< (x*y*z)<<endl;
}
void MIN_Display(int x,int y,int z=4)
{
cout<< (x-y-z)<<endl;
}
void main(){
int a=40, b=50, c=60;
Add_Display(a,b,c); //will print 150 (ie 40+50+60)
Add_Display(a,b); //will print 120 (ie 40+50+30)
Add_Display(a); //will print 90 (ie 40+20+30)
Add_Display(); //will print 60 (ie 10+20+30)
Mult_Dispaly(a,b,c); //will print 120000 (40*50*60)
Mult_Dispaly(a,b); //will print 180000 (40*50*90)
Mult_Dispaly(b); //will print 315000 (50*70*90) etc...
MIN_Display(a,b,c);
MIN_Display(a,b);
MIN_Display(c,b,5);//will print 5(60-50-5)
getch();
}
 Overloaded Functions
Unlike C, C++ lets you have more than one function with the same name. In other words, you
can have three functions called abs() in the same program. Functions with the same name are
called overloaded functions. C++ requires that each overloaded functions differ in its argument
list. Overloaded functions enable you to have similar functions that work on different types of
data. When the above code is compiled and executed, it produces the following result:
#include<iostream.h>
#include<conio.h>
int manip(int);
int manip(int, int);
int manip(int, double);
int main(){
int x = 2, y= 4, z;
double a = 3.1;
z = manip(x) + manip(x, y) + manip(y, a);
int m,n,k;
m= manip(x);
n= manip(x,y);
8
k= manip(y,a);
cout<<"\nFirst fun: "<<m;
cout<<"\nSecond fun:"<<n;
cout<<"\nThird fun: "<<k;
cout<<"\nTOTAL OF ALL OVERLOAD:"<< z << endl;
getch();
return 0;
}
int manip(int val)
{
return val + val * 2;
}
int manip(int val1, int val2)
{
return (val1 + val2) * 2;
}
int manip(int val1, double val2)
{
return val1 * val2;
}
1.5 Recursion versus Iteration
Both iteration and recursion are based on control structure. Iteration uses a repetition structure
(such as for, while, do…while) and recursive uses a selection structure (if, if else or switch).
Both iteration and recursive can execute infinitely-an infinite loop occurs with iteration if the
loop continuation test become false and infinite recursion occurs id the recursion step doesn’t
reduce the problem in a manner that coverage on a base case. Recursion has disadvantage as
well. It repeatedly invokes the mechanism, and consequently the overhead of method calls. This
can be costly in both processor time and memory space. Each recursive call creates another copy
of the method (actually, only the function’s variables); this consumes considerable memory.
N.B: Use recursion if:
A recursive solution is natural and easy to understand
A recursive solution doesn’t result in excessive duplicate computation.
The equivalent iterative solution is too complex and
of course, when you are asked to use one in the exam!!
Example:
The following code fragment computes the exponentiation An where A is a real number and N is
9
a positive integer. This time, we have to pass two arguments A and N. the value of A will not
change in the calls, but the value of N is decremented after each recursive call.
float expo (float A, int N)
{ if(N==1)
return A;
else
return A * expo(A,N-1);}
#include<iostream.h>
float expo(float A, int N){
if(N==1)
return A;
else
return A * expo(A,N-1);}
main(){
int s=2,a=4;
cout<<expo(s,a);
return 0;}
A function which calls itself is said to be recursive. Recursion is a general programming
technique applicable to problems which can be defined in terms of themselves. Take the factorial
problem, for instance which is defined as: - factorial of 0 is 1. Factorial of a positive number n is
n time the factorial of n-1. The second line clearly indicates that factorial is defined in terms of
itself and hence can be expressed as a recursive function.
C++ Program to Find Factorial of a Number using recursion
#include<iostream>
using namespace std;
int factorial(unsigned int n);
int main(){
unsigned int e;
cout << "Enter a positive integer: ";
cin >> e;
cout << "Factorial of " << e << " = " << factorial(e);
return 0;}
int factorial(unsigned int n){
if(n > 1)
return n * factorial(n - 1);
else
return 1;}
For n set to 4, the following figure shows the recursive call:
10
The stack frames for these calls appear sequentially on the runtime stack, one after the other. A
recursive function must have at least one termination condition which can be satisfied.
Otherwise, the function will call itself indefinitely until the runtime stack overflows.
The three necessary components in a recursive method are:
1. A test to stop or continue the recursion
2. An end case that terminates the recursion
3. A recursive call(s) that continues the recursion
Exercise: C++ Program to Find Factorial of a Number using Iteration
Iterative is just calculating it inside a loop of some kind, i.e. iterating one at a time until you
arrive to your answer. This is the more "natural" way of doing it. This is how you do it on paper.
#include<iostream.h>
#include<conio.h>
fact_iter(int n){
int result = 1;
for (int i = 1; i <= n; i++)
{
result *= i;
}
return result;
}
int main(){
int n;
while (1)
{
cout<<"Enter interger to compute factorial(0 to exit): ";
cin>>n;
11
if (n == 0)
break;
cout<<fact_iter(n)<<endl;}
return 0;}
1.7 Math Operations in C++
In addition to the various functions you can create, C++ also includes some useful functions you
can use. These functions are available in standard C and C++ libraries and called builtin
functions. These are functions that can be included in your program and then use. C++ has a rich
set of mathematical operations, which can be performed on various numbers. Following table
lists down some useful built-in mathematical functions available in C++. To utilize these
functions you need to include the math header file <cmath>.
S.N.
1
2
3
4
5
6
7
8
9
10
Function & Purpose
doublecos(double); This function takes an angle (as a double) and returns the cosine.
double sin(double); This function takes an angle (as a double) and returns the sine.
double tan(double); This function takes an angle (as a double) and returns the tangent.
double log(double); This function takes a number and returns the natural log of that number.
double pow(double, double); The first is a number you wish to raise and the second is
the power you wish to raise it to.
doublehypot(double, double); If you pass this function the length of two sides of a right
triangle, it will return you the length of the hypotenuse.
doublesqrt(double); You pass this function a number and it gives you this square root.
int abs(int); This function returns the absolute value of an integer that is passed to it.
doublefabs(double); This function returns the absolute value of any decimal number passed to it.
double floor(double); Finds the integer which is less than or equal to the argument passed to it.
Following a simple example to show few of the mathematical operations:
#include<iostream.h>
#include<conio.h>
#include<math.h>
int main (){ // number definition:
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;
cout<< "sin(d) :" << sin(d) <<endl;
// mathematical operations;
12
cout<< "abs(i) :" << abs(i) <<endl;
cout<< "floor(d) :" << floor(d) <<endl;
cout<< "sqrt(f) :" <<sqrt(f) <<endl;
cout<< "pow( d, 2) :" << pow(d, 2) <<endl;
cout<< "absolute of(s) :" << abs(s) <<endl;
getch();
return 0;}
When the above code is compiled and executed, it produces the following result:
sign(d) :-0.634939
abs(i) :1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2 ) :40149.7
absolute of(s): 10
1.8 Random Numbers in C++
There are many cases where you will wish to generate a random number. There are actually two
functions you will need to know about random number generation. The first is rand(), this
function will only return a pseudo random number. The way to fix this is to first call the srand()
function. Following is a simple example to generate few random numbers. This example makes
use of time() function to get the number of seconds on your system time, to randomly seed the
rand() function:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h> //for ramdom function
int main ()
{
int i,j;
// set the seed
/* generate 10 random numbers. */
for(i = 0; i< 10; i++ )
{
// generate actual random number
j= rand();
cout<<" Random Number : " << j <<endl;
}
getch();
return 0;
}
13
Download