You are on page 1of 32

Programming in C++ Functions

Chapter5Chapter5-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
y y y y

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().

I-P-O (Input Process Output)

Bad Development Approach main() { ----------------. . . -----------return 0; } Functions are easer to

Wise Development Approach main() { -------}

Design Build Extend Modify Understand function f1() Reuse { Better Organization ---

--} function f2() { ----}


3

Fig 4.1 Hierarchical boss function/worker function relationship.

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). y Functions make programs easier to understand. y Functions can be called several times in the same program, allowing the code to be reused.
y

C++ Functions types


y y

y
y y
y y

Functions come in two varieties: user-defined and builtin(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 Then main() can use other functions Not only main() can call but other function can call another one according to your need
7

Method

Description

Example

ceil( x ) cos( x ) exp( x )

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 floor( 9.2 ) is 9.0 integer not greater than x floor( -9.8 ) is -10.0 fmod( x, y ) remainder of x/y as a fmod( 13.657, 2.333 ) is floating-point number 1.992 log( x ) natural logarithm of x (base log( 2.718282 ) is 1.0 e) 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 sin( 0.0 ) is 0 (x in radians) sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 tan( x ) trigonometric tangent of x tan( 0.0 ) is 0 (x in radians) Fig. Math library functions.
8

rounds x to the smallest integer not less than x trigonometric cosine of x (x in radians) exponential function ex

ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 cos( 0.0 ) is 1.0

C++ Functions
y

The three components associated with C++ functions are


x The function declaration x The function definition x The calling function

C++ Functions
y

Using functions in your program requires


first declare the function and
 tells the compiler the name, return type, and type of parameters(variables) of the function.  The declaration of a function is also called function prototype.  No function can be called from any other function that hasn't first been declared

define the function


 consists of the function header and its body  The header is exactly like the function prototype  The body of the function is a set of statements enclosed in braces.

Calling a function
 Main can call any function in your program  Other function can call another user-defined function or library function  Syntax: function_name(paramet_value1,parameter_value2,)
10

Functions Declaration
1.

Function declaration

a) b) c)

There are three ways to declare a function:


Write your prototype into a file, and then use the #include directive to include it in your program. Write the prototype into the file in which your function is used. 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 bad programming 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 and type of argument parameters)-error checking cannot be performed prior to use.

11

Function Declaration
For functions you write yourself, you must include the prototype y Prototype Syntax:
y

return_type function_name(type ParameterName1, type parameterName2...);

Return_type: This specifies the type of data that the function returns for the calling construct y Function_name: the given name of the function(follows the same name convention as variable in C++. y Parameter Type: the type of variables whose values are expected to be transmitted to the function. y Note: The function prototype and the function definition must agree exactly about the return type, the name, and the parameter list. If they do not agree, you will get a compile-time error.
y
12

Function Declaration
y

Examples: 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 Declarations { 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 } Definition
14

Example1: void potentialEnergy(float mass) { 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; } Function Definition

15

Functions Definition
consists of the function header and its body y The header is exactly like the function prototype, except that the parameters must be named, and there is no terminating semicolon. y The body of the function is a set of statements enclosed in braces. y Function Definition Syntax: return_type function_name ( type parameterName1, type parameterName2,...) {
y

statements; }
y

A function definition must agree in return type and parameter list with its prototype. Function Body

Function header

16

Example: Function definition #include<iostream.h> 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; } 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; } void display(int max)//definition of display function { cout<<"The maximum one is:"<<max<<endl; }

Function declaration

main() function Body

findMax function Body

display() function body

17

Functions Execution

int main(){ --------------findMax() -------display() ---------

findMax()

Display()

18

Scope of Variables
y

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
y y y y

Variables declared within the function are said to have "local scope." They exist only locally within the function itself Cannot be accessed from the other functions 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 the function returns, the variables no longer exist!


Thats fine! We dont need them anymore!
20

Block Variables
You can also declare variables that exist only within the body of a compound statement (a block): A block variables scope is restricted to the block in which the variable is declared. int main(void) Scope of a { Scope of y int y; { int a = y; cout << a << endl; } cout << a << endl; }
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; float k2=9/5.0; int main() { float tc,tf; tc=faranehtToCelcius(); tf=celciusToFaraneiht();

Global Scope

Local to main()

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

End of Todays Session .to be continued

25

Passing an argument
y

arguments can be passed to function using


 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; cout<<swap before swap: x:<<x<<y:<<y<<endl; temp=x; x=y; y=temp; cout<<swap after swap: x:<<x<<y:<<y<<endl; }

27

Passing an argument
2. Passing by Reference
#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
y y y y

y y y y y y y y y y y y

//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

You might also like