Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by.

Similar presentations


Presentation on theme: "Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by."— Presentation transcript:

1 Functions Chapter 5

2 Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by the main function or any other function of the program to perform its task. Functions are identified by name and can return a single value. We need to tell the compiler the name of our function, what parameters it has, and the type of information it returns

3 What Do Function Do? Avoid unnecessary repetition – In large programs, one often has to execute a piece of code several times. Instead of writing the code several times, the code is written only once as a function and this function is called to execute it code. Program Organization – If the operation of a program could be divided into separate activities, and each activity placed in a separate subroutine, then each subroutine could be written and checked out more or less independently. Separating the code into modular functions also made programs easier to design and understand. Independence – There is an advantage in making subroutines as independent from the main program and from one another as possible. For instance, subroutines were invented that had their own "private" variables; that is variables that could not be accessed from the main program or the other subroutine. This meant that a programmer did not need to worry about accidentally using the same variable names in different subroutines; the variables in each subroutine were protected from inadvertent tampering by other subroutines.

4 Structure of Function Functions are of two types 1.Built-in functions Already defined as a part of the language and can be used in any program i.e. getch(), clrscr() 2.User defined functions Created by a user Program to perform specific task Structure of User define Function 1.Function Declaration(Prototype) 2.Function Definition 3.Function Calling

5 Function Declaration (PROTOTYPE) The function declaration is also called Prototype. Prototype means sample or model Only provide the model of the function In function declaration, the following information about the function is provided to compiler – Name of function – Type of data returned by the function – The number and types of arguments or parameters used in the function Semi colon indicate the end of function declaration void line(void); int Sum( int, int ); The prototype is written before the main ( ) function, This causes the prototype to be visible to all the functions in a file.

6 Function Definition The function itself is referred to as the function definition. The set of instructions that are written to perform a specific task Function definition is always outside the main() function. Can be written before or after the main() function but main () will be executed first Can be written in the separate file and include in the program by using #include directive Function definition consists of two parts – Declarator – Body of Function

7 Function Definition Declarator – Heading line function definition – Same as function declaration but it is not terminated by the semicolon(;) Body of Function – The set of statements enclosed in braces after the declaration are called the body of the function – The statement in the body of function performed specific task /* Function definition- Draw Line at the Screen*/ void line(void) { int j; for (j=1;j<=11;j++) printf("\xDB"); printf("\n"); }

8 Calling a Function Executing the statements of a function to perform a task is calling of the function The parentheses lets the compiler know that you are referring to a function and not to a variable or some thing else. e.g. prinf(), getch(), line() This function call causes control to be transferred to the code in the definition of the line(). This function execute the written statements in the function, and then returns to the main (), to the statement immediately following the function call.

9 Simple Function #include void line(void); /*Prototype of function line() */ void main (void) { clrscr(); line(); printf("\xDB Turbo C \xDB\n"); line(); getch(); } /* Function defination- Draw Line at the Screen*/ void line(void) { int j; for (j=1;j<=11;j++) printf("\xDB"); printf("\n"); }

10 Local Variables The variables that are declared inside the main function or inside any user-defined function are called local variables The lifetime of a variable is the time period between the creation and destruction of the variable. When the control is transferred to a function, the local variables or variables declared inside that function are automatically created and they occupy memory spaces to store data. When the control returns to the calling function, the variables of that function are destroyed and their data is lost Thus, Local variables can only be accessed from within the function in which they are declared. They are not available outside that function printf(“%d”,j); /*what happened, if this statement used in main()*/

11 A Sound Example This program uses the special character ‘\x7‘, which is called BELL in the standard ASCII code. On the PC, printing this character, instead of ringing a bell, causes a beeping sound. void beep (void) ; void main (void) { beep ( ) ; } void beep (void) { long count ; printf ( “ \x7 “) ; delay ( 10000 ) ; /* delay in mili-seconds*/ printf ( “ \x7 “ ) ; }

12 Delay function The delay function suspends execution for interval (milliseconds). With a call to delay, the current program is suspended from execution for the time specified by the argument milliseconds. void delay ( unsigned milliseconds ) ; For(j=1;j<100000;j++) /*delay*/ ; /*null statement*/

13 Functions that Return a Value A function that perform some function and returns a value. Similar like getche() - returns the value of the first character typed on the keyboard.

14 /* Implementation of lower case character using function */ char getlc (void) ; void main (void) { char chlc; printf ( “ Type ‘a’ for the selection, ‘b’ for the second: “ ) ; chlc = getlc ( ) ; switch ( chlc ) { case ‘ a ’ : printf (“ \n You typed an ‘ a ‘.“ ) ; break; case ‘ b ’ : printf (“ \n You typed a ‘ b ‘.“ ) ; break; default : printf (“ \n Non-existent selection.“ ) ; } getch ( ); } char getlc (void) { char ch; ch = getche ( ) ; if ( ch > 64 && ch < 91 ) ch = ch + 32 ; return ( ch ) ; } Output: Type ‘a’ for the selection, ‘b’ for the second: a You typed an ‘ a ‘. Type ‘a’ for the selection, ‘b’ for the second: A You typed an ‘ a ‘. Type ‘a’ for the selection, ‘b’ for the second: c You chose a non-existent selection.

15 The return Statement The return() statement has 2 purposes. 1.Executing it immediately transfer control from the function back to the calling program, 2.whatever is inside the parentheses following return is returned as a value to the calling program. The return() statement need not to be at the end of the function. It can occur anywhere in the function; as soon as it is encountered, control will return to the calling program. char getlc (void) { char ch; ch = getche ( ) ; if ( ch > 64 && ch < 91 ) return (ch + 32) ; else return ( ch ) ; }

16 Limitation of return ( ) statement Can only use it to return one value by a function.

17 Using Argument to pass data to a Function The mechanism used to convey information to a function is the argument. The argument in the calling program is referred to as the “Actual Argument”, while the argument in the called function is the “Formal Argument”. For example: printf() and scanf() functions; – the format strings and the values used inside the parentheses in these function are arguments.

18 Bar Graph Example /* Draws Bar-graph and Implementation of Function Arguments */ void bar ( int ) ; void main (void) { printf (“ Ali \t “) ; bar (10) ; printf (“ Babar \t “); bar (15) ; printf (“ Faraz \t “) ; bar (20) ; getch ( ); } void bar (int score) { int count ; for ( count =1 ; count < = score ; count ++ ) printf ( “ \xCD “ ) ; /*Draw double line*/ printf ( “ \n “ ) ; } Output: Ali ========== Babar =============== Faraz ====================

19 External Variable Variables that are declared outside the main() or any other function are called Global variables or External variables. /* Implementation of External Variables */ void oddeven ( void ) ; /* Function Prototype */ void negative ( void ) ; int keynum; /* External Variables */ void main (void) { printf ( “ Type Keynum: “ ) ; scanf ( “ %d ”, &keynum ) ; oddeven ( ); /* Function Call */ negative ( ); }

20 Preprocessor Directives Are the instructions to the compiler itself, Rather than being translated into machine language Preprocessor directives are instructions to the compiler. Preprocessor directives always start with a number # sign. The directives can be placed anywhere in a program, but are often used at the beginning of a file, before main (), or before the beginning of particular functions.

21 Example /* Implementation of define directive */ # define PI 3.14159 float area ( float ) ; /* Function Prototype */ void main (void) { float radius ; printf ( “ Enter radius of the sphere: “ ) ; scanf ( “ %f ”, &radius ) ; printf ( “ Area of the sphere is %.2f “, area (radius) ); } float area ( float rad ) { return ( 4 * PI * rad * rad ) ; }

22 Macros The additional power comes from # define is the ability to use arguments. A # define directive can take arguments, much as a function does. A Macro generates more code but executes more quickly than a functions. # define PR ( n ) printf ( “ %.2f \n “, n ) ; /* macro definition */ void main (void) { float num1 = 12.34 ; float num2 ; num2 = 5.0 / 2.5 ; PR ( num1 ) ; PR ( num2 ) ; }

23 #include Directives The # include directive causes one source file to be included in another. Instead of having to rewrite all the macro every time you wrote a program that used them, you could insert them into the.cpp source file using the # include directive /* Implementation of the # include directive */ # include # include " c:\ tc\bin\ my.h " void main ( void ) { int a, b, ans = 0 ; printf ( " Enter any two numbers: \n " ) ; scanf ( " %d %d ", &a, &b ) ; mul ( a, b ) ; } /* Implementation header file my.h */ void mul ( int, int ) ; void mul ( int aa, int bb ) { int ans ; ans = aa * bb ; printf ( " Answer = %d ", ans ) ; }

24 #include Directives Two ways to include header files 1.The variation shown above # include ”my.h” shows the file name surrounded by quotes. This causes the preprocess or to start searching for the file in the directory containing the current source file. 2.The other approach is to use angle brackets # include. This format causes the preprocessor to start searching in the standard header directory.

25 Standard Header Files Each library function provided with Turbo C is associated with a header file: that is, – a file with the extension.h that is kept in the \ INCLUDE directory. – The prototype for the function is part of the corresponding header file.

26 Lab Write a program that prints out the larger of two numbers. Use a function to do the actual comparison of the two numbers. Pass the two numbers to the function as arguments and have the function return the answer with return() Implement the above function in separate header file and include in main program


Download ppt "Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by."

Similar presentations


Ads by Google