Ch-10 & 11 Function 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 or Library Function 2. User defined 1. LIBRARY FUNCTION # Include Directive The # include directive instructs the compiler to read and include another file in the current file. The compiler compiles the entire code. A header file may be included in one of two ways. include <iostream.h> or include "iostream.h" The header file in angle brackets means that file reside in standard include directory. The header file in double quotes means that file reside in current directory. LIBRARY FUNCTION C++ provides many built in functions that saves the programming time Mathematical Functions Some of the important mathematical functions in header file math.h are Function sin(x) cos(x) tan(x) asin(x) acos(x) exp(x) log(x) log 10(x) Meaning Sine of an angle x (measured in radians) Cosine of an angle x (measured in radians) Tangent of an angle x (measured in radians) Sin-1 (x) where x (measured in radians) Cos-1 (x) where x (measured in radians) Exponential function of x (ex) logarithm of x Logarithm of number x to the base 10 sqrt(x) pow(x, y) abs(x) fabs(x) Square root of x x raised to the power y Absolute value of integer number x Absolute value of real number x Character Functions All the character functions require ctype.h header file. The following table lists the function. Function Meaning It returns True if C is an uppercase letter and False if c is isalpha(c) lowercase. isdigit(c) It returns True if c is a digit (0 through 9) otherwise False. It returns True if c is a digit from 0 through 9 or an alphabetic isalnum(c) character (either uppercase or lowercase) otherwise False. islower(c) It returns True if C is a lowercase letter otherwise False. isupper(c) It returns True if C is an uppercase letter otherwise False. toupper(c) It converts c to uppercase letter. tolower(c) It converts c to lowercase letter. String Functions The string functions are present in the string.h header file. Some string functions are given below: strlen(S) strcat(S1, S2) strcpy(S1, S2) strcmp((S1, S2)==0) strcmp((S1, S2)>0) strcmp((S1, S2) <0) strcmpi((S1, S2)==0) strcmpi((S1, S2)>0) strcmpi((S1, S2) <0) strrev(s) strupr(s) strlwr(s) It gives the no. of characters including spaces present in a string S. It concatenates the string S2 onto the end of the string S1. The string S1 must have enough locations to hold S2. It copies character string S2 to string S1. The S1 must have enough storage locations to hold S2. It compares S1 and S2 and finds out whether S1 equal to S2, S1 greater than S2 or S1 less than S2. It compares S1 and S2 ignoring case and finds out whether S1 equal to S2, S1 greater than S2 or S1 less than S2. It converts a string s into its reverse It converts a string s into upper case It converts a string s into lower case Console I/O functions The following are the list of functions are in stdio.h It returns a single character from a standard input device getchar() (keyboard). It takes no parameter and the returned value is the input character. It takes one argument, which is the character to be sent to output putchar() device. It also returns this character as a result. It gets a string terminated by a newline character from the gets() standard input stream stdin. puts() It takes a string which is to be sent to output device. General purpose standard library functions The following are the list of functions are in stdlib.h It initializes / seeds the random number generator with a random number random(n) It generates a random number between o to n-1 atoi(s) It converts string s into a numerical representation. itoa(n) It converts a number to a string randomize() Some More Functions The getch() and getche() functions The general for of the getch() and getche() is ch=getche(); ch1=getch(); ch and ch1 are the variables of type character. They take no argument and require the conio.h header file. On execution, the cursor blinks, the user must type a character and press enter key. The value of the character returned from getche() is assigned to ch. The getche() fuction echoes the character to the screen. Another function, getch(), is similar to getche() but does not echo character to the screen. 2. USER DEFINE FUNCTION 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(); The declaration, called the FUNCTION PROTOTYPE, informs the compiler about the functions to be used in a program, the argument they take and the type of value they return 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; } Note: 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 student’s first name would be a word representing a student’s 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; Main to call this function void main() { int a=accept(); or cout<<accept();} cout<<”Enter a number”; cin>>x; return x; } 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 to a function – Parameters Sometimes the calling function supplies some values to the called function. These are known as parameters. The variables which supply the values to a calling function called actual parameters. The variable which receive the value from called statement are termed formal parameters. Consider the following example that evaluates the area of a circle. #include<iostream.h> void area(float); int main() { float radius; cin>>radius; area(radius); return 0; } void area(float r) { cout<< “the area of the circle is”<<3.14*r*r<<”\n”; } Here radius is called actual parameter and r is called formal parameter. A function used to get a student’s first name could be declared as: string FirstName(); Here are examples of declaring functions; some take arguments, some don’t: 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 function’s required arguments, if any. When declaring a function that uses arguments, specify each argument with a data type and a name. The function can be called using either of the following methods: i) call by value ii) call by reference CALL BY VALUE In call by value method, the called function creates its own copies of original values sent to it. Any changes, that are made, occur on the function’s copy of values and are not reflected back to the calling function. CALL BY REFERENCE In call be reference method, the called function accesses and works with the original values using their references. Any changes, that occur, take place on the original values are reflected back to the calling code. Consider the following program which will swap the value of two variables. using call by reference using call by value #include<iostream.h> void swap(int &, int &); int main() { int a=10,b=20; swap(a,b); cout<<a<<" "<<b; return 0; } void swap(int &c, int &d) { int t; t=c; c=d; d=t; } #include<iostream.h> void swap(int , int ); int main() { int a=10,b=20; swap(a,b); cout<<a<<" "<< b; return 0; } void swap(int c, int d) { int t; t=c; c=d; d=t; } output: 20 10 output: 10 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): Inline Function Functions save memory space because all the calls to the function cause the same code to be executed. The functions body need not be duplicated in memory. When the complier sees a function call, it normally jumps to the function. At the end of the function. it normally jumps back to the statement following the call. While the sequence of events may save memory space, it takes some extra time. To save execution time in short functions, inline function is used. Each time there is a function call, the actual code from the function is inserted instead of a jump to the function. The inline function is used only for shorter code. inline int cube(int r) { return r*r*r; } Some important points to be noted Function is made inline by putting a word inline in the beginning. Inline function should be declared before main() function. It does not have function prototype. Only shorter code is used in inline function If longer code is made inline then compiler ignores the request and it will be executed as normal function. Global Variable And Local Variable Local Variable : a variable declared within the body of a function will be evaluated only within the function. The portion of the program in which a variable is retained in memory is known as the scope of the variable. The scope of the local variable is a function where it is defined. A variable may be local to function or compound statement. Global Variable : a variable that is declared outside any function is known as a global variable. The scope of such a variable extends till the end of the program. these variables are available to all functions which follow their declaration. So it should be defined at the beginning, before any function is defined. Variables and storage Class The variable in C++ can have not only data types but also storage class that provides information about their location and visibility .The storage class decides the portion of the program within which variables are recognized. There are four storage classes in ‘C’ programming: (i) (ii) (iii) (iv) Local (auto). External (external/global). Register. Static (i) Automatic:- The local variables which are declared inside the function are called automatic variable. The scope of the variable is inside the function or block in which they are declared. It is created automatically when enter into function or block and destroyed automatically when out from function or block. e.g. main( ) { int a; /* Here a is automatic variable It may be declared with keyword auto. */ -----} (ii) External / Global: - The variable which has been declared before the main is called global variable. It can be used in all the functions in the program. It need not be declared in other functions .A global variable is also known as external variable. By default it takes the initial value zero. It may also declare with the keyword extern. extern datatype var_name; For example:int m; main() { int i; float balance; ---- ----- - -- - - - - - function(); } Here variable m is global variable. It is alive and active within program. This variable accessible for all function present in program. (iii) Register variable: - Register variable are used for storing the value of variable into CPU registers. Access time of automatic variable is more than accessing the register variable because automatic variable are stored in memory and access time of CPU register take less time than the access time of the variable which is stored in memory. So the variable which are used heavily can be assigned as register variable for fast processing Syntaxregister Ex:- data_type #include<stdio.h> var_name; main() { register int i; for( i=0; i< 20000; i++) cout<<“\n”<<i; } (iv) Static variable:Static variables are same as the automatic variable but it holds the latest value of the variable in the block or function in which they are declared. There are two types of static variable – (1) Local static, (2) Global static variable. This depends upon the creation of space of variable. When we declare inside function then local static, when we declared outside function the global static variable. Q. 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 case 1: cout<<.\nEnter the radius: .; having 2 arguments 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( ); } Q2. What is function prototyping & function definition? Ans: 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; } Q3. 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. Q4. 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; } 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. Q.1 Write a compelete C++ program with function to calculate the roots of a quardratic equation where the co-efficients are passing as argumet to the function. Q2.Write function to calculate the GCD(Greatest Common Diviser) and LCF(Lowest common factors) of two nos, passing as argument. Q3.Write a function to find the sum of the following series. If no of term is passing by parameters Series=(1)+(1+2)+(1+2+3)+(1+2+3+4)+…………..+N Q4. Write a menu driven program with function to perform conversion of 1. Celsius to Fahrenheit 2. Fahrenheit to Celsius Q. What is the fundamental difference between call by value and call by reference in the context of function call.