understanding functions by dk mamonai 09ce37

9
OBJECT: TO BECOME FAMILIAR  WITH FUNCTIONS IN C++. Function The function is one of the fundamental building blocks of C++ programming language. A function is a sub program that contains some program statements. The function collects a number of program statements and forms a unit with a particular name. This function then can be called at any sta ge in the program. The functi on name declar ation follows the sa me rul es of identi fiers. The  parentheses () are always followed by the function name in the function. The basic idea to create the functions is to divide a large program containing hundreds of statements in the small units or blocks so that the program becomes more clearer and conceptable. A single program may contain hundreds or even thousands of function but each program should contain the main function because main function is the gate way to enter in C++. The function also contains some return type and  parameters. The return type is type of some data that will be returned by the function at its end. The return type may be of type int, type float, type long, type long double, type char, void (empty) or user defined data type. The return type is given before the function name. The parameters are the series of variables separated by comma contained in the parentheses that pass the arguments through the function. void point(int x, int y) { statement; statement; statement; } Parameters Function name Return type Function Body

Upload: darya-memon

Post on 07-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Understanding Functions by Dk Mamonai 09CE37

8/6/2019 Understanding Functions by Dk Mamonai 09CE37

http://slidepdf.com/reader/full/understanding-functions-by-dk-mamonai-09ce37 1/9

O BJECT : T O BECOME FAMILIAR WITH FUNCTIONS IN C++.

Function

The function is one of the fundamental building blocks of C++ programming language. Afunction is a sub program that contains some program statements. The function collectsa number of program statements and forms a unit with a particular name. This functionthen can be called at any stage in the program. The function name declaration followsthe same rules of identifiers. The parentheses () are always followed by the functionname in the function. The basic idea to create the functions is to divide a large programcontaining hundreds of statements in the small units or blocks so that the programbecomes more clearer and conceptable. A single program may contain hundreds or eventhousands of function but each program should contain the main function because main

function is the gate way to enter in C++. The function also contains some return typeand parameters . The return type is type of some data that will be returned by thefunction at its end. The return type may be of type int, type float, type long, type longdouble, type char, void (empty) or user defined data type. The return type is givenbefore the function name. The parameters are the series of variables separated bycomma contained in the parentheses that pass the arguments through the function.

void point(int x, int y)

{

statement;

statement;

statement;

}

Parameters

Function name

Return type

Function Body

Page 2: Understanding Functions by Dk Mamonai 09CE37

8/6/2019 Understanding Functions by Dk Mamonai 09CE37

http://slidepdf.com/reader/full/understanding-functions-by-dk-mamonai-09ce37 2/9

The Function Declaration

In case of variables we observed that we cannot use variables without declaring them,here the scenario is same i.e. we cannot use our own defined functions without declaringthem because the compiler is unfamiliar with the functions developed by the users sothe programmer should first tell the compiler that there is a function which has thisreturn type data and takes these arguments. The function should be declared before it iscalled otherwise the compiler will complain. The function declaration includes thefunction return type, the function name and the declaration of its parameters in theparentheses and the semicolon at the last. The function declaration is also known as

prototype because it is the blueprint for the function. The function declaration tells thecompiler that the function looking like this is on the way in the program and do not beconfused with it. The syntax for declaring a function is,

int charline(int a, char ch);

In above function declaration syntax a user defined function named charline is declared.It has integer return type and the two parameters i.e. integer a and character ch . Notethat the function can have any return type and can contain number of parameters in theparentheses.

The Function Definition

The function definition tells the actual purpose and process of the function. The functiondefinition contains the block of code that is executed when ever that function is called.The whole definition of the function resides in the curly braces of the function body. Thefunction definition starts with the declarator . Declarator is same as declaration but without the semicolon i.e. void charline(int a, char ch) then the body of the function follows.The function return type, the function name and the parameters in the parenthesesshould match the function declaration correspondents. If the function is first declaredbefore the calling then you can place the function definition in any place through out theprogram but if you do not have declared the function then you should place the functiondefinition first before its calling. This approach of placing the definition first byeliminating the function declaration is not considered as standard approach and suitsonly in very small programs. The better approach is to declare the function at the topbefore it is called rather than by placing definition first.

Parameters

Function name

Return type

Note: semicolon here

Page 3: Understanding Functions by Dk Mamonai 09CE37

8/6/2019 Understanding Functions by Dk Mamonai 09CE37

http://slidepdf.com/reader/full/understanding-functions-by-dk-mamonai-09ce37 3/9

Note: no semicolon here

Note: semicolon here

Note that the declarator is always not terminated by the terminator. When ever thefunction is called each time the control is transferred to the body of the that function.The syntax of the function definition is as under,

int charline(int a, char ch){

for(int i=1; i<=a; i++)cout<<ch;

cout<<endl;

}

Function calling

When the function is declared and defined, now to utilized and make the most of function, the function is called. The function calling transfers the control from the pointof calling directly to the function definition. The function calling carries the constantvalues or variables in the arguments in the parentheses (if used) and passes them fromthe function definition and evaluates the result. The function calling does not containthe return type and always terminated by the terminator. The same function can becalled multiple number of time in a program, which evaluates the beauty of the breakingthe program in to functions. The syntax of calling the function is given as,

charline(10, ‘*’);

Declarator

Function body

Function name

Constant arguments

Page 4: Understanding Functions by Dk Mamonai 09CE37

8/6/2019 Understanding Functions by Dk Mamonai 09CE37

http://slidepdf.com/reader/full/understanding-functions-by-dk-mamonai-09ce37 4/9

Table 6.1, Function components.

Component Purpose Example

Declaration

(Prototype)

Specifies function name, argument types, andreturn value. Alerts compiler (and programmer)that function is coming up later.

void funct();

Call Causes the function to be executed. funct();

DefiningFunction

The function itself. Contains the lines of code thatconstitute the {// lines of code} void funct()

Declarator First line of definition void funct()

The simple function

Program (funct.cpp)

#include <iostream.h>#include <conio.h>

void charline(int a, char ch);

void main(){

clrscr();charline(45, ’*’);

charline(45, ’_’);charline(25, ‘+’);getch();

}

void charline(int a, char ch){

for(int i=1; i<=a; i++)cout<<ch;cout<<endl;

}

The output must be:

*********************************************---------------------------------------------+++++++++++++++++++++++++

Page 5: Understanding Functions by Dk Mamonai 09CE37

8/6/2019 Understanding Functions by Dk Mamonai 09CE37

http://slidepdf.com/reader/full/understanding-functions-by-dk-mamonai-09ce37 5/9

Passing arguments to the function

The arguments are the data with any data type, which are passed through the function.When the user creates certain function, the function provides some parameters and thearguments are the data that are placed in the place parameters to pass those datathrough that function. The data type of the arguments and the data type of theparameters should match with each other. You can pass an argument through thefunction either by constants or by variables.

Passing constant as arguments

For passing the constant arguments you have to place the constants of any data type inthe arguments where as the data types of the constant arguments and the parametersshould match. When you have passed the constants as the arguments now you can geta fixed particular result. Examine the below program:

Program (ConstArg.cpp)

#include <iostream.h>#include <conio.h>

void charline(int a, char ch);

void main(){

clrscr();

charline(45, ’*’);charline(45, ’_’);charline(25, ‘+’);getch();

}

void charline(int a, char ch){

for(int i=1; i<=a; i++)cout<<ch;cout<<endl;

}In the above program the constant arguments are passed through the functioncharline . In first function call the integer constant 45 and the character constant ‘*’ are passed as the arguments. In second function call the integer constant 45 and thecharacter constant ‘-‘ are passed as the arguments and in the last function call theinteger constant 25 and the character constant ‘+’ are passed as the arguments. Nowthese constant arguments are place in the memory of the parameter variable, the

Page 6: Understanding Functions by Dk Mamonai 09CE37

8/6/2019 Understanding Functions by Dk Mamonai 09CE37

http://slidepdf.com/reader/full/understanding-functions-by-dk-mamonai-09ce37 6/9

integer constants 45, 45, 25 are placed in the parameter a and the character constants ‘*’, ‘-’, ‘+’ are place in the parameter ch . In the body of the function charline the forloop is executed integer constant number of time and prints the character constant thatmuch number of time.

So if you are passing the constants as arguments then the values for the arguments areset to remain constant and can not be altered. Also the data type of the constantarguments should match the corresponding parameter’s data type.

Passing variables as arguments

The phrase “ passing the variable” does not mean that the whole variable is passed asthe argument but the data/value stored in that variable is passed thought the functionas the argument. When passing the variable as arguments the data type of the variableshould match the data type of the corresponding parameter. The advantage of thevariable arguments is that unlike constant arguments, you can place the values in thearguments according to the situation and make the function and program generalpurpose. Examine the below program:

Program (VarArg.cpp)

#include <iostream.h>#include <conio.h>

void charline(int a, char ch);

void main(){

int intin;char chin;clrscr();cout<<”Enter the character: “;cin>>chin;cout<<”Enter the number of times: “;cin>>intin;charline(intin, chin);getch();

}void charline(int a, char ch){

for(int i=1; i<=a; i++)cout<<ch;cout<<endl;

}

Page 7: Understanding Functions by Dk Mamonai 09CE37

8/6/2019 Understanding Functions by Dk Mamonai 09CE37

http://slidepdf.com/reader/full/understanding-functions-by-dk-mamonai-09ce37 7/9

In the above program the variables intin and chin are passed through the function asthe arguments. The program at the startup will ask you to enter the values of characterchin and the integer intin then it passes the value placed in the these variable as thearguments through the function. In this program you can pass the arguments accordingto the situation so the program has become generalized by the use of variable

arguments.

Returning Value from the function

The function can return a value after passing the arguments through its definition by thereturn statement. When you define a function you first give its return type that can beinteger, floating point, character or void (empty). The return statement in the functionbody returns a value of the type that was declared as the return type of the functionwhen the function completes its execution. This return value is send to the calling of thefunction. The data type declared as the return type of the function should match withthe value that the function returns. Examine the below program:

Program (ReturnValue.cpp)

#include <iostream.h>#include <conio.h>

int add(int a, int b);

void main(){

int num1, num2;clrscr();cout<<”Enter first number: “;cin>>num1;cout<<”Enter second number: “;cin>>num2;cout<<”The addition is: “<<add(num1,num2);getch();

}

int add(int a, int b){

return (a + b);}

In the above program the function add is declared with the return type of integer,which means that when ever the function is called it will return an integer type valueand contains two integer type parameters i.e. a and b . When the function add is called,the values of num1 and num2 are passed through the function definition and the additionof num1 and num2 is returned to the calling as the integer type value.

Page 8: Understanding Functions by Dk Mamonai 09CE37

8/6/2019 Understanding Functions by Dk Mamonai 09CE37

http://slidepdf.com/reader/full/understanding-functions-by-dk-mamonai-09ce37 8/9

Reference Arguments

When we pass the argument with the variables the copy of that variable is passedthrough the function and no effect is implemented on the actual variable but when thevariables are passed by the reference the actual variables are affected and modified bythe function. The reference provides another name for what ever the variable is usedand the address of the variable is passed through the function. The references are mostcommonly used for passing the arguments through the function. We use the referenceargument when we need to modify the actual variable. When declaring a referencevariable the ampersand sign “&” is used which tells the compiler that the variable used isa reference variable―another name for what ever the variable is used in the arguments.The ampersand sign can be used with the variable name or with the data type as:

int &var1; //Perfectly Legalint& var1; //Perfectly Legal

Program (Reference.cpp)

#include <iostream.h>#include <conio.h>

void swap(int& a, int& b);

void main(){

int num1, num2;clrscr();

cout<<”Enter first number: “;cin>>num1;cout<<”Enter second number: “;cin>>num2;cout<<”num1 = “<<num1<<endl;cout<<”num2 = “<<num2<<endl;swap(num1, num2);cout<<”num1 = “<<num1<<endl;cout<<”num2 = “<<num2<<endl;getch();

}

void swap(int& a, int& b){

int temp;temp=a;a=b;b=temp;

}

Page 9: Understanding Functions by Dk Mamonai 09CE37

8/6/2019 Understanding Functions by Dk Mamonai 09CE37

http://slidepdf.com/reader/full/understanding-functions-by-dk-mamonai-09ce37 9/9

In above program the user defined function swap is declared, which contains tworeference arguments and a and b are two reference variables which will pass throughthe body of the function and the effects will be found on these variables. The programfirst will input the values of num1 and num2 from the user then these variables arepassed through the function swap which will swap the values of num1 and num2 . Now

you will observe that the values of num1 and num2 are swapped which is the indicationthat some effect is implemented on these variables by the function.