Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions in C++. Functions  Groups a number of program statements into a unit & gives it a name.  Is a complete and independent program.  Divides.

Similar presentations


Presentation on theme: "Functions in C++. Functions  Groups a number of program statements into a unit & gives it a name.  Is a complete and independent program.  Divides."— Presentation transcript:

1 Functions in C++

2 Functions  Groups a number of program statements into a unit & gives it a name.  Is a complete and independent program.  Divides a large program into smaller units.  Are written to avoid replication of code

3 Functions  Executed by the main function or any other function of the program to perform its task.  Function code is stored in only one place in memory, even if it is executed many times in the program.  Functions are also known as sub-routines or procedures in different languages.

4 Types of Functions  There are two types of functions  Built-in functions(standard functions)  Functions that have already been defined as a part of language.  User defined functions  Created by the a user  written as a part of program to perform a specific task

5 User Defined Functions  Has three parts:  Function declaration(prototype)  Function definition  Function calling

6 Function Declaration  Also called prototype (model/sample).  Only provides the model/sample of the function.  In function declaration:  Name of function.  Type of data returned by the function.  Number & types of arguments/parameters used in function.

7 Function Declaration  Function declaration is terminated by a semicolon.  Similar to declaration of a variable and the rules for naming the functions is also same as for naming variables  Syntax: type function-name(arguments if any);

8 Function Declaration  Examples: void display(); void myFunction( void); int sum(int, int); float sum(); void print(int, float, char);

9 Function Definition  Actual code of the function is called function definition.  Function definition is always outside the main () function.  Can be written before or after the main() function.

10 Function Definition  Consists of two parts:  Declarator:  Heading line of the function definition.  It is same as the function declaration but it is NOT terminated with a semicolon.  Body of the Function:  Set of statements enclosed in braces after the declarator.  These statements are written to perform a specific task

11 Function Definition  General format of function definition: type function-name(parameter) { set of statements }

12 Calling the Function  Executing the statements of a function to perform a task is called calling of the function (function invoking or execution)  A function is called by referencing its name.  The parameters(if any) are given in the parentheses after the name of function otherwise left blank.

13 Calling the Function  If the function has a return value of numeric type it can be called in an arithmetic expression.  When a function is called,  the control shifts to the function definition.  The statements of the body of the function are executed.

14 Calling the Function  After execution:  The control returns to the calling function  and the next statements that comes immediately after the function call is executed.  E.g. function-name(parameters if any);

15 void func1( ) ; semicolon Function declaration Return type void main( ) { ------- func1(); ------ } semicolon No return Type Function call void func1( ) { ------- ------ } No semicolon Declarator Function Body Function Definition

16 Example # 1 #include void display(); void main() { clrscr(); cout<<“this is first line”<<endl; display(); cout<<“ok”; getche(); } // end of main void display() { cout<<“my first function”<<endl; }

17 Example # 2 #include void starline(); void main() { starline(); cout<<“Name Age”<<endl; starline(); cout<<“ali 19”<<endl; cout<<“huma 20”<<endl; starline(); getche(); }// end of main void starline() { for(int i=0 ; i<10 ; i++) cout<< “*”; cout<<endl; } Output: ********** Name Age ********** ali 19 huma 20 **********

18 Passing Arguments to Functions  An argument is a piece of data passed from a program to the function.  Arguments allows a function to operate with different value.  Arguments are placed in parentheses.  These are either constants or variables

19 Example # 3a (passing constants) #include void sum(int, int); void main() { clrscr(); sum(2, 2); cout<<“exit”; getch(); } void sum( int x, int y) { int s; s = x + y ; cout<<“sum is = ”<< s << endl; }

20 Example # 3b (passing variables) #include void sum(int, int); void main() { clrscr(); int a, b; cout<<“enter 1st value”; cin>> a; cout<<“enter 2nd value”; cin>> b; sum(a, b); cout<<“exit”; getch(); } void sum( int x, int y) { int s; s = x + y ; cout<<“sum is = ”<< s << endl; }

21 1(a). Write a function called circleArea()that finds the area of a circle. 1(b). Repeat the above program to pass radius of the circle as argument passed as variable to the function. 2(a). Write a program to find factorial of a number using functions.(without argument) 2(b). Repeat the above program to pass a number as argument to the function body. 3. Write a program for a calculator by passing three arguments to function body first is the numeric number, 2 nd is the arithmetic operator, 3 rd is the other numeric number.

22 Passing Array as Argument  When array variable is passed as an argument.  Only starting address of array is passed.  No separate copy of array in the body of the function is made.  It only assigns the starting address of same memory area of the array to array name used in the function declaration.  Function can change the contents of the array by directly accessing the memory cells where array elements are stored.

23 Declaring function with Array as Argument  If a 1-D array is passed. void myfunction( int []); void max(int [], float []);  If a 2-D array is to be passed void myFunction( int [][]); void max(int [][], float [][]);

24 Function Definition with Array Arguments  The name of array and its type is given in the declartor.  E.g. void myFunction( int a[]) { body of the function }  Size of the array can be given in the function declaration and in the function definition.

25 Calling function with Array Arguments  When a function that uses array arguments is called (invoked), only name of the array without subscripts is given.  Reason being is that only memory address of array is passed.  The elements are accessed from the same memory location.  Name of array used in the function call and function definition may be same or different.

26 Example(passing Array as Argument) #include void find(int [ ], int ); //function declaration void main() { int arr[5], i, n ; cout<<“enter elements in array”; for( i=0; i<=4; i++) cin>>arr[i]; cout<<“enter a number to find”; cin>>n; find(arr, n); //function call getch(); } //end of main void find( int x [ ], int a ) { int p=0; for(int c=0 ; c<=4; c++) if(a = = x[c]) { p = c+1; break; } if (p = = 0) cout<<“number not found”; else cout<<“number found at position ”<< p ; }

27 Passing Arguments  There are two ways to pass arguments  By value  By reference  By value  When constants or variables are passed to function, it creates new variables to hold the values of these arguments.  The function gives these new variables the names and the data type of variable arguments specified in the declarator.

28 Passing Arguments(By value)  It initializes these parameters to values passed.  They are then accessed like other variables by statements in function body.  Passing arguments in this manner in which function creates copies of the arguments passed to it is called passing by value

29 Passing Arguments(By Reference)  Reference provides a different name for the variable and represented by an ampersand (&)  Instead of the passing value of the variable reference of the original variable, in the calling function is passed.  It is actually the memory address of the original variable that is passed.  Any change in the reference variable also changes the original variable.  By default array variable are passed by reference.

30 Example # 1(reference variables) #include void swap(int &, int &); void main() { int a, b; cout<<“enter value of A”; cin>>a; cout<<“enter value of B”; cin>>b; swap(a,b); cout<<“values after swapping”<<endl; cout<<“value of A is =“<<a<<endl; cout<<“value of B is =“<<b<<endl; getch(); } void swap( int & x, int & y) { int temp; temp = x; x = y; y = temp; }

31 Returning Values From Functions  When a function completes its execution, its returns a single value to the calling function.  Usually this return value consists of an answer to the problem the function has solved.  A function can return only one value  It can be any type except string and array  The type of data that a user-defined function returns is declared in function declaration.

32 Return Statement  The return statement is used to return the calculated value from the function definition to the calling function.  Syntax: return expression;  Declaration of function that return a value float temp(); int sum(int, int); float radius(float );

33 Calling a function that returns a value  The function that return a value can be called in an arithmetic expression.  In this case the function is treated as a variable.  The value returned by the function may be assigned to a variable or it can be directly sent to output device.  E.g. r = temp();  r is a variable that receives the returned value(r is a float type variable)  To print the returned value directly on screen  E.g cout<<“the returned value is”<< temp();

34 Example # 1(function that returns a value) #include int sum(int, int); void main() { clrscr(); int a, b, ans; cout<<“enter 1st value”; cin>> a; cout<<“enter 2nd value”; cin>> b; ans = sum(a, b); // cout<<“the answer is ”<<sum(a,b); cout<<“answer is = ”<<ans; getch(); } int sum( int x, int y) { int s; s = x + y ; // return x + y; return s; }

35  Write a function that uses array as argument to find largest number in an array.  Write a function that finds factorial of number passed as argument by reference.  Write a function that calculates and returns the age of the student.  Write a function that compares two number passed as argument to the function body and display the largest number as output.

36 Types of Variables  Variables can be declared  Inside the main function,  Inside user-defined function or  outside the main.  Effect of these variables declared in these places is different.

37 Types of Variables  Based on their effect there are three categories:  Local variables (automatic variables)  Global variables(external variables)  Static variables

38 Automatic Variables  Variables declared inside the main or user-defined function.  Also called local variables  Keyword auto can be used to specify the automatic variable. e.g void myfunction() { auto int abc; // same as int abc auto float x; // same as float x ---- ----- }

39 Automatic Variables  Lifetime:  An automatic variable is not created until the function in which it is defined is called.  When control transfer to the function definition the variables are created and space is reserved.  When control returns to the calling function the variables are destroyed.  The time period between the creation and destruction of variables is called lifetime of the variable.

40 Automatic Variables  Visibility:  Automatic variables are only visible within the function in which they are defined.  Also called scope of the variable. e.g.

41 External variables  Variables declared outside the main or user- defined function.  Also called global variables.  E.g #include int a; // global variable int sum(int, int); // function declaration void main() { a=10; --- } int sum(int x, int y) { cout<< value of a <<a; ---- }

42 External variables  Lifetime and visibility:  External variables exist for the life of the program.  Memory is reserved when the program begins  And remain in existence until the program ends.  These variables are visible to all those function that follow the variable’s definition.

43 Static variables  Are special variables that are declared inside a function using the keyword static  Visibility:  these variables can only be accessed in the function in which they are declared  Lifetime:  Remain in existence for the lifetime of the program.  Their initialization takes place only once when the function is called for the first time.  Used when a function needs to remember a value when it is not being executed i.e. between calls to the functions.

44 Example (Static variables) #include int temp(int ); void main() { int i; for(i=1; i<=3 ;i++) { cout<<temp(i)<<endl; } cout<<“ok”; } int temp(int x) { static int c=10; c =c * x; return c; }

45 Overloaded Functions  Declaring more than one function with the same name but  different number of arguments  Different type of arguments  E.g void sum(); void sum(int, int); void sum(float, float);  In order to avoid confusion compiler check the number of arguments, and type of arguments.

46  Create a menu having following functionality.  A function that convert the temperature from Fahrenheit to Celsius(c= 5/9(f-32))  A function that determines if the number is prime or not.  A function to calculate cube of a number.  A function that determines the largest number in an array passed as argument.  A function to input the values  A function to display the output  Use return statement,different type of variables, arguments passing where necessary.


Download ppt "Functions in C++. Functions  Groups a number of program statements into a unit & gives it a name.  Is a complete and independent program.  Divides."

Similar presentations


Ads by Google