Function: A function is a named unit of a group of statements that can be invoked from other parts of the program. The advantages of using functions are: Functions enable us to break a program down into a number of smaller and smaller and simpler units. This makes the program more organized and structured and easier to debug. It helps in reusability of code and thus reduces program size. If similar code is required at several places in the program, the use of a function allows this code to be written just once, and to be called wherever it is required. It helps to execute the same set of statements with different set of values. Function Declaration/Prototype: Just as any variable is declare before it is used in a program, it is necessary to declare a function to inform the compiler that the function would be referenced at a later point in the program. Function declaration is also called function prototype. Syntax for function declaration: <return type> <function name> ( <data type of parameter> [<parameter name>],. ); Example: int sum ( int, int); A declaration (prototype) tells the compiler that later on in our program we are going to write a particular function. It also informs the compiler about: 1. the type of result to be returned; 2. the identifier of the function; 3. the number and types of parameters; It is terminated by a semicolon. <return type>: It is the data type of the value that is returned to the calling function after the function is executed. It can be any of the data types, available in C++. <function name>: It is the name of the function, which is given with accordance to the naming conventions used for naming an identifier. A function is called with the help of it s name. <data type of parameter>: These are the data types of the parameters/inputs that the function receives when it is called. In function declaration it is optional to give the name of the parameters. The different data types specify to the compiler, the total number of parameters, and the data type of these parameters that the function will receive, when it is called (invoked). Function definition: The function definition contains the function header and the function body i.e. the set of statements which are executed when the function is called. Syntax for function definition: <return type> <function name> (<data type of parameter> <name of <parameter>,. ) Statement 1; Statement 2; : return ( value / variable / expression );
Example: int sum ( int a, int b) int s = a + b; return s; Note: The return statement is used to return a value to the calling function. It is always the last statement in the function definition (if the function has return type). The data type of the value returned should match with the return type of the function. // Example 1 // Program to find the factorial of a number using a function Fact () #include<conio.h> long Fact( long); // Function Prototype long num; clrscr(); cout<< \n\tenter a No. : ; cin>>num; cout<<num<<! = <<Fact(num); // Function call with num as an actual parameter getch(); // Definition of function long Fact (long N) // Function header with N as a Formal parameter long I, f=1; for( i=1; i<=n; i++) f = f * i; return f; Function Body Order of Execution in the above program main() // Execution starts from the main() Function call to Fact() // Control is passed to the function definition of Fact() Execution of the Fact() // All the statements in the function Definition of Fact() are executed Execution of statement getch() // Control returns to the main(), to the statement which follows the function call statement of Fact() Function Header: It is the first line of the function definition, which specifies the following: Return type of the function Name of the function Name of the parameters, along with their data types Note: It is not terminated with semicolon.
Function Body: It is the set of statements, which are executed when the function is called. Function Call: It is the statement in the calling function, through which the control is passed to the function definition of another function. This will execute the statements is the called function and then the control is returned back to the statement in the calling function, which follows the function call statement. The function call consists of the function name, followed by actual parameters, if any, enclosed in parentheses. Calling Function: The function, which calls a function is called the calling function. In the above example main() is the calling function. Called Function: The function which is called by anther function is known as the called function. Formal Parameter: The parameters mentioned in the function header are called formal parameter. Actual Parameter: Values/Variables which are used while making a call to the function are called actual parameter. Difference between call by value and call by reference Call by Reference 1) The changes made to the formal parameters are reflected back to the actual parameters. 2) It provides a mechanism of returning more than one value. 3) The reference parameters require an 3) Not Available ampersand (&) sign before their name. 4) The Formal and Actual parameters share the same memory location. 5) void Swap(int & a, int & b) int temp = a; a = b; b = temp; // Program to illustrate the invoking of a function using call by value // and call by reference methods #include<conio.h> // Function to swap the values of two variables, // where both the parameters are value parameters void swapv ( int a, int b) int temp = a; a = b; b = temp; Call by Value 1) The changes made to the formal parameters are not reflected back to the actual parameters. 2) Not Available 4) The formal and actual parameters have different memory location. 5) void Swap(int a, int b) int temp = a; a = b; b = temp; cout<< Displaying the formal parameters of swapv () function <<endl; cout<<a<< \t <<b<<endl; // Function to swap the values of two variables, // where both the parameters are variable parameters void swapr( int&b, int&b)
int temp = a; a = b; b = temp; cout<< Displaying the formal parameters of swapr () function <<endl; cout<<a<< \t <<b<<endl; clrscr(); int x=5, y=7; swapv(x,y); cout<< The values of actual parameters after calling the swapv() function <<endl; cout<<x<< \t <<y<<endl; swapr(x,y); cout<< The values of actual parameters after calling the swapr() function <<endl; cout<<x<< \t <<y<<endl; getch(); Returning values from Functions: When a function completes its execution it can return a single value to the calling function. // Program to explain return statement int Sum(int x, int y) int z; z = x+y; return z; clrscr(); int a,b,c; cout<< \n Enter 2 numbers : ; cin>>a>>b; OUTPUT Displaying the formal parameters of swapv() function 7 5 The values of actual parameters after calling the swapv() function 5 7 Displaying the formal parameters of swapr() function 7 5 The values of actual parameters after calling the swapr() function 7 5 OR int Sum(int x, int y) return(x+y); c = Sum(a,b); // Function call statement, the returned value is stored in the variable c cout<< \n Sum = <<c;
Default Parameters: A function can assign a parameter a default value. So, a function can be called with less number of parameters than that defined if values have been set. These default values are used when no value corresponding to these parameters are specified in the call to that function. The default values have to be specified in the function prototype, and not in the function definition. For example: int Change(int, int &, int c=9); The following points should be considered while using the default parameters: If a function consists of value, reference and default parameters, then the default parameters are specified in the end of the parameter list, i.e. If a parameter has a default value, then all the parameters appearing to it s right must have a default value. Reference parameter cannot have a default value. // Program to show the usage of default parameters int Calculate(int, int b=20); int x=5, y=15; cout<<calculate(x); cout<<endl; cout<<calculate(x,y); int Calculate(int a, int b) return(b/a); Difference between Local and Global Variables Local Variables Global Variables 1) They are declared outside all the functions, and can be used in all the functions after its declaration. 1) They are declared in a function, and can be used only in the function in which they are declared. 2) If a local variable has the same name as that of a global variable, then the local variable is given preference. 3) For example void Show () int m =5; // Local Variable cout<<m<<endl; 2) To access the global variable explicitly, scope resolution operator(::), is used. 3) For example int m = 50; // Global Variable void Show () int m =5; // Local Variable cout<<m<<::m<<endl; In-Built functions in Header File <math.h> Function Usage Example Result 1. fabs(x) Calculates the absolute value of the floating point number x. 2. abs(x) Calculates the absolute value of the integer x. Output 4 3 cout<<fabs(-7.5); cout<<fabs(8.25); cout<<abs(-12); cout<<abs(25); cout<<abs(-17.25); cout<<abs(25.77); 3. log(y) Calculates natural logarithm of cout<<log(100); y. cout<<log(2); 4. log10(y) Calculates the base 10 cout<<log10(100); 2 7.5 8.25 12 25 17 25 4.60517 0.693147
logarithm of y cout<<log10(2); 0.30103 5. pow(x, y) Calculates the power x to y. cout<<pow(10,2); cout<<pow(125,1/3.0); 100 5 6. sqrt(x) Calculates the square root of x cout<<sqrt(25); cout<<sqrt(144); 5 12 7. sin(x) Computes the sine of x. The angle is specified in radians. cout<<sin(90); cout<<sin(90/(22/7.0)); 0.893997 0.540834 8. cos(x) Computes the cosine of x. The angle is specified in radians. cout<<cos(270); cout<<sin(90/(22/7.0)); 0.984382 0.841129 In-Built functions in Header File <ctype.h> Function Usage Example Result 1. isalpha( x) Check if character x is A-Z or a-z char x= B ; if(isalpha(x)) Albhabet cout<< Alphabet ; cout<< Not alphabet ; 2. isdigit( x) Check if character x is 0-9 char x= 9 ; if(isdigit(x)) cout<< Digit ; cout<< Not digit ; 3. islower( x) Check if character x is lower case alphabet a-z 4. isupper( x) Check if character x is Upper case alphabet A-Z 5. Isalnum( x) Check if character x is an alphanumeric i.e. A-Z, a-z, 0-9 6. tolower(x) Converts the character x to its lower case value i.e. if character is A-Z then it convert it to a-z. All other characters are left unchanged. It return ASCII of the lower case equivalent. 7. toupper(x) Converts the character x to its upper case value i.e. if character is a-z then it convert it to A-Z. All other characters are left unchanged. It return ASCII of the upper case char x= b ; if(islower(x)) cout<< Lowercase ; cout<< Not lowercase ; char x= B ; if(isupper(x)) cout<< Uppercase ; cout<< Not uppercase ; char x= b ; if(isalnum(x)) cout<< alphabet/digit ; cout<< other ; char x= H ; if(isupper(x)) cout<<(char)tolower(x); char x= h ; if(islower(x)) cout<<(char)toupper(x); Digit Lowercase Uppercase alphabet/ digit h H
equivalent. In-Built functions in Header File <conio.h> Function Usage Example Result 1. clrscr() To clear the screen clrscr(); Places the text cursor at first row, and first column on the screen 2. getch() Wait for a character input getch(); 3. gotoxy(c,r) To place the text cursor at column c and row r on the screen. gotoxy(3,6); Places the text cursor at third column and sixth row on the screen In-Built functions in Header File <stdlib.h> Function Usage Example Result 1. randomize() It is used to initialize the random number generator, so that each time a new random number is generated. randomize(); 2. random(n) It returns a random integer cout<<random(7); Will display any between 0 to n-1, both integer number inclusive. between 0-6. // Program find LCM of two number using function. int LCM( int a, int b) int i, lcm; for(i=a*b; i>=a; i--) if(i%a==0 && i%b==0) lcm=i; return lcm; int GCD(int a, int b) int i, gcd; for(i=1; i<=a; i++) if(a%i ==0 && b%i==0) gcd=i; return gcd;
int a, b, l,g; cout<< \n Enter 2 number : ; cin>>a>>b; l = LCM(a,b); cout<< \n LCM = <<l; g = GCD(a,b); cout<< \n GCD = <<g;