You are on page 1of 13

Class -11 Function Notes

A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses: int main(void). Good C++ programmers write programs that consist of many of these small functions. These programmers know that a program written with numerous functions is easier to maintain, update and debug than one very long program. By programming in a modular (functional) fashion, several programmers can work independently on separate functions which can be assembled at a later date to create the entire project. Ideally, your main( ) function should be very short and should consist primarily of function calls. Functions are of 2 types: 1. Built in or Pre defined 2. User defined A function is a group of statements that is executed when it is called from some point of the program. Using functions we can structure our programs in a more modular way, accessing all the potential that structured programming can offer to us in C++. The following is its format:
type name ( parameter1, parameter2, ...) { statements }

where: type is the data type specifier of the data returned by the function. name is the identifier by which it will be possible to call the function. parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas. statements is the function's body. It is a block of statements surrounded by braces { }.

Here you have the first function example:

// function example #include <iostream.h> int addition (int a, int b) { int r; r=a+b; return (r); } int main () { int z; z = addition (5,3); cout << "The result is " << z; return 0; }

Every function has 3 statements 1. Declare a function 2. Call a function 3. Define a function

Function Declaration
In order to create and use a function, you must let the compiler know. Letting the compiler know about your function means you declare it. The syntax of declaring a function is:
ReturnType FunctionName();

An assignment, considered a function, is made of three parts: its purpose, its needs, and the expectation. Based on this formula, the expectation of function is the ReturnTypefactor. The simplest return type is void. Using this keyword, the simplest formula we can use is:
void FunctionName(); void display( int , int); // function taking 2 integer parameters int check(); function returning an integer value int check(int); function taking an integer parameter and returning an integer value

Function Definition
In order to use a function in a program, the compiler must know what the function does. To let the compiler know what the function is meant to do, define it; which also means describing its behavior. The syntax to define a function is:
void FunctionName() {Body}

To define a function using the rule we applied with the main() function. Define it starting with its return value (if none, use void), followed by the function name, its argument (if any) between parentheses, and the body of the function. Once you have defined a function, other functions can use it.

Function Body
As an assignment, a function has a body. The body of the function describes what the function is supposed to do. The body starts with an opening curly bracket { and ends with a closing curly bracket }. Everything between these two symbols belongs to the function.Here is an example:
void Message() {};

In the body of the function, you describe the assignment the function is supposed to perform. As simple as it looks, a function can be used to display a message. Here is an example:
void Message(){ cout << "This is C++ in its truest form.";}

A function can also implement a complete behavior. For example, on a program used to perform geometric shape calculations, you can use different functions to handle specific tasks. Imagine you want to calculate the area of a square. You can define a particular function that would request the side of the square:
cout << Enter the side of the square: ;

cin >> Side;

and let the function calculate the area using the formula Area = Side * Side. Here is an example of such a function:
void SquareArea() { double Side; cout << "\nEnter the side of the square: "; cin >> Side; cout << "\nSquare characteristics:"; cout << "\nSide = " << Side; cout << "\nArea = " << Side * Side; }

void SquareArea(); { ----- }

; at end means no definition i.e. no body of the function

Calling Functions
One of the main reasons of using various functions in a program is to isolate assignments; this allows to divide the jobs among different entities so that if something is going wrong, it might be easily know where the problem is. Functions trust each other, so much that one function does not have to know HOW the other function performs its assignment. One function simply needs to know what the other function does, and what that other function needs. Once a function has been defined, other functions can use the result of its assignment. Imagine you define two functions A and B. A=Max(A,B); When calling one function from another function, provide neither the return value nor the body, simply type the name of the function and its list of arguments, if any. For example, to call a function named Welcome() from the main() function, simply type it, like this:
int main() { Message(); // Calling the Message() function return 0; }

The compiler treats the calling of a function depending on where the function is declared with regards to the caller. You can declare a function before calling it. Here is an example:
#include <iostream> void Message() { cout << "This is C++ in its truest form."; } int main() { Message(); // Calling the Message() function

return 0; }

Calling a Function Before Defining it

The example we saw above requires that you define a function before calling it. C/C++, like many languages, allows to call a function before defining it. Unlike many languages, in C++, when calling a function, the compiler must be aware of the function. This means that, you must at least declare a function before calling it. After calling the function, you can then define it as you see fit. Here is an example:
#include <iostream> int main() { void Message();

Declare the function locally or globally

cout << "We will start with the student registration process."; Message(); // Calling the Message() function return 0; } void Message() { cout << "Welcome to the Red Oak High School."; }

To use any of the functions that ship with the compiler, first include the library in which the function is defined, then call the necessary function. Here is an example that calls the getchar()function:
#include <iostream> #include <stdio.h> int main() { cout << "This is C++ in its truest form...\n\n"; getch (); return 0; }

Returning a Value
void Functions
A function that does not return a value is declared and defined as void. Here is an example: void Introduction() { cout << "This program is used to calculate the areas of some shapes.\n" << "The first shape will be a square and the second, a rectangle.\n" << "You will be requested to provide the dimensions and the program " << "will calculate the areas"; }

Any function could be a void type as long as you are not expecting it to return a specific value. A void function with a more specific assignment could be used to calculate and display the area of a square. Here is an example:
void SquareArea() { double Side; cout << "\nEnter the side of the square: "; cin >> Side; cout << "\nSquare characteristics:"; cout << "\nSide = " << Side; cout << "\nArea = " << Side * Side; }

When a function is of type void, it cannot be displayed on the same line with the cout extractor and it cannot be assigned to a variable (since it does not return a value). Therefore, a void function can only be called.

The Type of Return Value

The purpose of a function identifies what the function is meant to do. When a function has carried its assignment, it provides a result. For example, if a function is supposed to calculate the area of a square, the result would be the area of a square. The result of a function used to get a students first name would be a word representing a students first name. The result of a function is called a return value. A function is also said to return a value. There are two forms of expectations you will have from a function: a specific value or a simple assignment. If you want the function to perform an assignment without giving you back a result, such a function is qualified as void and would be declared as
void FunctionName();

A return value, if not void, can be any of the data types we have studied so far. This means that a function can return a char, an int, a float, a double, a bool, or a string. Here are examples of declaring functions by defining their return values:
double FunctionName(); char FunctionName(); bool FunctionName(); string FunctionName();

If you declare a function that is returning anything (a function that is not void), the compiler will need to know what value the function returns. The return value must be the same type declared. The value is set with the return keyword. If a function is declared as a char, make sure it returns a character (only one character). Here is an example:

char Answer() { char a; cout << "Do you consider yourself a reliable employee (y=Yes/n=No)? "; cin >> a; return a; }

A good function can also handle a complete assignment and only hand a valid value to other calling functions.
int accept() { int x; cout<<Enter a number; cin>>x; return x; }

Main to call this function void main() { int a=accept(); or cout<<accept();}

The return value can also be an expression. Here is an example:

double SquareArea(double Side) { return (Side * Side); }

A return value could also be a variable that represents the result. Here is example:
double SquareArea(double Side) { double Area; Area = Side * Side; return Area; }

If a function returns a value (other than void), a calling function can assign its result to a local variable like this: Here is an example:
#include <iostream> int GetMajor() // a menu in a function and the function is returning the value accepted by user { int Choice; cout << "\n1 - Business Administration"; cout << "\n2 - History"; Value returned by the cout << "\n3 - Geography"; cout << "\n4 - Education"; function is stored in a cout << "\n5 - Computer Sciences"; variable cout << "\nYour Choice: "; cin >> Choice; return Choice; } int main() { int Major; cout << "Welcome to the student orientation program."; cout << "Select your desired major:"; Major = GetMajor(); cout << "You select " << Major; cout << "\n"; return 0; }

You can also directly display the result of a function using the cout operator. In this case, after typing cout and its << operator, type the function name and its arguments names, if any. So far, the compiler was displaying a warning because our main() function was not returning anything. In C++, a function should always display a return type, otherwise,

make it void. If you declare a function without a return type, by default, the compiler considers that such a function should return an integer. Therefore, the main() function we have used so far should return an integer as follows:
#include <iostream.h> int main() { cout << "This is C++ in its truest form...\n\n"; return 0; }

Strictly stated, the main() function can return any integer, which simply indicates that the program has ended. Returning 0 means that the program has terminated successfully. Since the main() function now returns an integer, you should indicate this on its declared line. A better version of the above main() function would be:
#include <iostream.h> int main() { cout << "This is C++ in its truest form...\n\n"; return 0; }

Arguments Parameters

In order to carry its assignment, a function might be supplied something. For example, when a function is used to calculate the area of a square, you have to supply the side of the square, then the function will work from there. On the other hand, a function used to get a students first name may not have a need; its job would be to supply or return something. Some functions have needs and some do not. The needs of a function are provided between parentheses. These needs could be as varied as possible. If a function does not have a need, leave its parentheses empty. In some references, instead of leaving the parentheses empty, the programmer would write void. In this book, if a function does not have a need, we will leave its parentheses empty. Some functions will have only one need, some others will have many. A functions need is called an Argument. If a function has a lot of needs, these are its arguments. The argument is a valid variable and is defined by its data type and a name. For example, if a function is supposed to calculate the area of a square and it is expecting to receive the side of the square, you can declare it as double CalculateArea(double Side); A function used to get a students first name could be declared as: string FirstName(); Here are examples of declaring functions; some take arguments, some dont: double CalculateArea(double Side); char Answer(); void Message(float Distance); bool InTheBox(char Mine); string StudentName(); double RectangleArea(double Length, double Width); void DefaultBehavior(int Key, double Area, char MI, float Ter);

Techniques of Passing Arguments In order to perform its assignment, a function may need arguments. Any function that wants to use the result of another function must supply the other functions required arguments, if any. When declaring a function that uses arguments, specify each argument with a data type and a name. Call by value: In call by value method, the called function creates a new set of variables and copies the values of arguments into them. The function does not have access to the original variables (actual parameters) and can only work on the copies of values it created. Passing arguments by value is useful when the original values are not to be modified. In call by reference method, a reference to the actual argument (original variable) is passed to the called function. (Reference is an alias for a predefined variable. i.e. the same variable value can be accessed by any of the two names: the original variables name and the reference name.) Thus, in call by reference method, the changes are reflected back to the original values. The call by reference method is useful in situations where the values of the original variables are to be changed using a function. Program to illustrate the call by value method of function invoking: #include<iostream.h> #include<conio.h> int change(int); void main( ) { clrscr( ); int orig=10; cout<<\nThe original value is<<orig<<\n; cout<<\nReturn value of function change()is<<change(orig)<<\n; cout<<\nThe value after function change() is over<<orig<<\n; getch(); } int change(int duplicate) { duplicate=20; return duplicate; } Output: The original value is 10 Return value of function change() is 20 The value after function change() is over 10 Program to illustrate the call by Reference method of function invoking: #include<iostream.h> #include<conio.h> int change(int&); void main( ) { clrscr( ); int orig=10; cout<<\nThe original value is<<orig<<\n; cout<<\nReturn value of function change()is<<change(orig)<<\n; cout<<\nThe value after function change() is over<<orig<<\n; getch(); } int change(int &duplicate) {

duplicate=20; return duplicate; } Output: The original value is 10 Return value of function change() is 20 The value after function change() is over 20

Default Arguments
Whenever a function takes an argument, that argument is required. If the calling function does not provide the (required) argument, the compiler would throw an error. Imagine you write a function that will be used to calculate the final price of an item after discount. The function would need the discount rate in order to perform the calculation. Such a function could look like this:
double CalculateNetPrice(double discountRate) { double OrigPrice; cout << "Please enter the original price: "; cin >> origPrice; return origPrice - (origPrice * discountRate / 100); }

Since this function expects an argument, if you do not supply it, the following program would not compile: Most of the time, a function such as ours would use the same discount rate over and over again. Therefore, instead of supplying an argument all the time, C++ allows you to define an argument whose value would be used whenever the function is not provided with the argument. To give a default value to an argument, when declaring the function, type the name of the argument followed by the assignment operator =, followed by the default value.
#include <iostream.h> double CalculateNetPrice(double discountRate = 25) { double origPrice; cout << "Please enter the original price: "; cin >> origPrice; return origPrice - (origPrice * discountRate / 100); }

int main() { double finalPrice; finalPrice = calculateNetPrice(); cout << "\nFinal Price = " << finalPrice << "\n\n"; return 0; }

The CalculateNetPrice() function, with a default value, could be defined as:

If a function takes more than one argument, you can provide a default argument for each and select which ones would have default values. If you want all arguments to have default values, when defining the function, type each name followed by = followed by the desired value. Here is an example: If a function receives more than one argument and you would like to provide default values for those parameters, the order of appearance of the arguments is very important.

If a function takes two arguments, you can declare it with default values. If you want to provide a default value for only one of the arguments, the argument that would have a default value must be the second in the list. Here is an example: double CalculatePrice(double Tax, double Discount = 25); When calling such a function, if you supply only one argument, the compiler would assign its value to the first parameter in the list and ignore assigning a value to the second (because the second already has a (default) value):

What do you understand by function overloading? Give an example illustrating its use in a c++ program. Ans: A function name having several definitions that are differentiable by the number or types of their arguments, is known as an overloaded function and this process is known as function overloading. Function overloading not only implements polymorphism but also reduces number of comparisons in a program and thereby makes the program run faster. Example program illustrating function overloading: //Program to find out area of a circle or area of rectangle using //function overloading. #include<iostream.h> #include<conio.h> void area(float r) //function1 { cout<<.\nThe area of the circle = .<<3.1415*r*r; } void area(float l,float b) //function2 { cout<<.\nThe area of the rectangle = .<<l*b; } void main( ) { float rad,len,bre; int n; Function1 is called clrscr( ); having one argument cout<<.\n1. Area of a Circle..; cout<<.\n2. Area of a Rectangle..; cout<<.\n\nEnter your choice: .; cin>>n; switch(n) { Function2 is called having 2 arguments

case 1: cout<<.\nEnter the radius: .; cin>>rad; area(rad); break; case 2: cout<<.\nEnter the length and breadth: .; cin>>len>>bre; area(len,bre); break; default: cout<<.\nYou have to enter either 1 or 2.; } //end of switch getch( ); }

What is function prototyping & function definition? In C++, a function prototype is a declaration to the compiler that a certain function exists, without a full definition. This allows other functions to call that function. The linker will later make sure that a function definition actually exists (perhaps somewhere else), and will turn the call to the function to a call to the correct function. Function prototypes exist in C++ and essentially
are initializations of functions, meaning that they define the type and the arguments of the function, they omit the contents. Most of the time these are located in a header (or .h) file, while the contents are in a C++ ( .cpp) file. Example: int add(int a, int b); //Function prototype. int add(int a, int b) // Function Definition. { return a + b; }

What is the difference between global variables and local variables? Give an example to illustrate the same. Ans: The local variables are the variables defined within any function (or block) and are hence accessible only within the block in which they are declared. In contrast to local variables, variables declared outside of all the functions in a program are called global variables. These variables are defined outside of any function, so they are accessible to all functions. These functions perform various operations on the data. They are also known as External Variables. Eg: #include<iostream.h> int a,b; void main() Local variable Global variable { or under float f; function scope ---; } In the above program segment, a and b are global variables, we can access a and b from any function. f is local variable to function main( ), we can access float f from main( ) only.

Differentiate between break, continue, exit & return

Ans break - The break statement is used to jump out of loop. After the break statement control passes to the immediate statement after the loop. Passes control out of the compound statement.
The break statement causes control to pass to the statement following the innermost enclosing while, do, for, or switch statement. The syntax is simply break;

continue - Using continue we can go to the next iteration in loop. exit - it is used to exit the execution of program. Exit terminates the entire program. If you just want
to stop looping, you use break. If you want to stop the current loop iteration and proceed to the next one, you use continue.

Note: break and continue are statements, exit is function.

return: Exits the function. Return exits immediately from the currently executing function to the calling routine, optionally returning a value. The syntax is: return [expression]; For example, int sqr (int x) { return (x*x); }
Expression or value is optional a void function will not have an expression or value

void display() { cout<<hello; return; }

What is goto statement in c++. Give example Goto performs a one-way transfer of control to another line of code; in contrast a function call normally returns control. The jumped-to locations are usually identified using labels. A statement label is meaningful only to a goto statement; in any other context, a labeled statement is executed without regard to the label. A jump-statement must reside in the same function and can appear before only one statement in the same function. The set of identifier names following a goto has its own name space so the names do not interfere with other identifiers. Labels cannot be re declared. #include<stdio.h> #include<conio.h> void main() { int x; printf("enter a number "); scanf("%f",&x); if (x%2==0) goto even; else goto odd;

even : printf("\n %f is even no"); return; odd: printf("\n %f is odd no"); getch(); }

Points to remember:

A C++ function can return a value. The function must be declared to have the same type as this value. If the function does not return a value then it must be given the type void. Information is passed into a function via the parameter-list. Each parameter must be given a type. If not declared to be otherwise then parameters are treated as value parameters If a parameter is a value parameter then the function operates on a copy of the value of the actual parameter hence the value of the actual parameter cannot be changed by the function. A function prototype provides information to the compiler about the return type of a function and the types of its parameters. The function prototype must appear in the program before the function is used. Any variable declared inside a function is local to that function and has existence and meaning only inside the function. Hence it can use an identifier already used in the main program or in any other function without any confusion with that identifier.