Chapter5-Functions
A complex problem is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself. This is called modular programming. Modules in C++ are called functions Functions are modules that perform a task or group of tasks A function is a subprogram that can act on data and return a value. You write new C++ functions, and use functions that other programmers have written Every C++ program has at least one function, main().
Wise Development Approach main() { -------} function f1() { ----} function f2() { ----}
3
C++ Functions
main()
Function1()
Function2()
Function3()
Function3()
Function5()
Advantages of Functions
Functions
separate the concept (what is done) from the implementation (how it is done). Functions make programs easier to understand. Functions can be called several times in the same program, allowing the code to be reused.
come in two varieties: user-defined and built-in(Library) fucnction. Built in functions (e.g., abs, pow,ceil, rand, sqrt, etc.) are usually grouped into specialized libraries (e.g., iostream, stdlib, math, iomanip etc.)
user-defined functions is to be developed by
the programmer at the time of writing program main() is special user defined function Every C++ program must have main()function to indicate where the program begins it execution
Method
Descriptio
absolute va
8
C++ Functions
The
C++ Functions
Using
Calling a function
Main can call any function in your program Other function can call another user-defined function or library function
10
Functions Declaration
1.Function declaration
There are three ways to declare a function:
a)Write your prototype into a file, and then use the #include directive to include it in your program. b)Write the prototype into the file in which your function is used. c) Define the function before it is called by any other function. When you do this, the definition acts as its own declaration.
Possible
to define functions with out prototype but it is badprogramming practice for three reasons.
Requires that the file in the program must be in particular order If functionA() and functionB() are defined in order functionA() can call(use) functionB() but functionB() cannot use functionA(). function prototypes are a good and powerful debugging technique(indicates type of function 11
Function Declaration
For
functions you write yourself, you must include the prototype Prototype Syntax:
return_type function_name(type ParameterName1, type parameterName2...);
Return_type:
This specifies the type of data that the function returns for the calling construct Function_name: the given name of the function(follows the same name convention as variable in C++. Parameter Type: the type of variables whose values are expected to be transmitted to the 12
Examples:
Function Declaration
void square( double x, double y); double square(double ,double); double square(); int findMax(int x,int y, int z) int area(); int area(void); long area(int width, int length) BadFunction(); //returns int,has no parameters
Function prototype does not need to contain the names of the parameters, just their types.
13
Example1:
#include<iostream.h>
double kineticEnergy(float,float); void potentialEnergy(float); int main() Function Declaratio { float velocity, mass; cout<<"Enter the mass and velocity\n"; cin>>mass>>velocity; cout<<"The Kinetic Energy is: <<kineticEnergy(mass, velocity)<<endl; potentialEnergy(mass); return 0; } double kineticEnergy(float m,float v) { return (1/(float)2)*m*(v*v); }
Function Definiti
14
Function Definition float PE,h,g=9.81; cout<<"This is from potentialEnergy(float mass)\n\n"; cout<<"Enter the height:"; cin>>h; PE=mass*g*h; cout<<"The potential energy is: "<<PE<<endl; }
15
Functions Definition
consists of the function header and its body The header is exactly like the function prototype, except that the parameters must be named, and there is no terminating semicolon. The body of the function is a set of statements enclosed in braces. Function Definition Syntax: return_type function_name ( type parameterName1, type parameterName2,...) { statements; Function header }
A function definition must agree Function Body in return type and parameter list with its prototype.
16
int findMax(int,int,int);//function declarartion void display(int); int main() { int x,y,z,max; cout<<"Enter three numbers\n"; cin>>x>>y>>z; max=findMax(x,y,z); display(max); return 0;
Function declaration
} int findMax(int x, int y,int z)//definiton of findMax { int temp; if((x>y)&&(x>y)) temp=x; else if((y>x)&&(y>z)) temp=y; else if((z>y)&&(z>y)) temp=z; return temp;
Functions Execution
Display()
18
Scope of Variables
A
variable has scope, which determines how long it is available to your program and where it can be accessed.
Local Scope and Global scope
19
Local Variables
Variables declared within the function are said to have "local scope."
They exist only locally within the function itself C a n n o t b e a cce sse d fro m th e o th e r fu n cti n s o The parameters passed in to the function are also considered local variables
defined variables inside a set of braces within the function, those variables are available only within that block.
Once
Yo u ca n a l d e cl re va ri b l s th a t exi so a a e st o n l w i i th e b o d y of a compound y th n sta te m e n t ( a block ) : A b l ck va ri b l s sco p e i re stri d to o a e s cte th e b l ck i w h i th e va ri b lScope d e cl re d . o n ch a e i of a a s int main(void) Scope of { int y; { int a = y; cout << a << endl;
s xi e t n es o
Block Variables
e id s ut to
d a ! k or loc r Er e b th
21
Nested Blocks
void block(void) { for (int j=0;j<10;j++) { int k = j*10; cout << j << , << k << endl; { int m = j+k; cout << m << , << j << endl; } } }
22
#include<iostream.h> float celciusToFaraneiht float faranehtToCelcius(); float k1=5/9.0; Global Scope float k2=9/5.0; int main() { float tc,tf; tc=faranehtToCelcius(); Local to main() tf=celciusToFaraneiht(); cout<<"Celcius value is:"<<tc<<endl; cout<<"Faraneght equivalent is:"<<tf<<endl; return 0; }
23
float celciusToFaraneiht() { float Tc; cout<<"Enter temp. in Celcius:"; cin>>Tc; return (k2*Tc+32);
Local to celciusToFaraneiht(
} float faranehtToCelcius() { float Tf; cout<<"Enter temp. in faraneiht:"; cin>>Tf; return (k1*(Tf-32)); Local to faranehtToCelcius() }
24
25
arguments
Passing an argument
Pass by value Pass by reference
1. Pass by Value
The arguments passed in to the function are local to the function Changes made to the arguments do not affect the values in the calling function known as passing by value a local copy of each argument is made in the function
26
Passing an argument
Example: Pass by Value #include<iostream.h> void swap(int x, int y); int main() { int x=5,y=10; cout<<main before swap x:<<x<<y:<<y<<\n; swap(x,y); cout<<main before swap: x:<<x<<y:<<y<<endl; return 0; } void swap(int x, int y) { int temp; es tak y cout<<swap before swap: x:<<x<<y:<<y<<endl;d an f x s o temp=x; ue val of x=y; ng gi han y=temp; Exc 27 cout<<swap after swap: x:<<x<<y:<<y<<endl;
2. Passing by Reference
Passing an argument
#include<iostream> using namespace std; int duplicate(int&,int&,int&); int main() { int x=1,y=3,z=7; duplicate(x,y,z); cout<<"x="<<x<<",y="<<y<<",z="<<z<<endl; system("pause"); return 0; } int duplicate(int& a,int& b,int& c) { a*=2; b*=2; c*=2; return(a); return(b); return(c); }
28
Default parameters
//default values in parameter #include<iostream> using namespace std; Int divide(int,int=2); int main() { cout<<divide(12)<<endl; cout<<divide(20,4)<<endl; system("pause"); return 0; } int divide(int a,int b) { int r; r=a/b; return(r); }
29
Function overloading
30
Recursivity
31
example
32