B. RAMAMURTHY CH.4 IN KERNIGHAN AND RITCHIE C TEXTBOOK C Language: Functions 5/11/2013 Amrita-UB-MSES
Topics 5/11/2013 Amrita-UB-MSES Purpose of functions Function design Function definition Function call
Functions 5/11/2013 Amrita-UB-MSES Functions are modular units that perform a specific operation It provides the ability to divide the program into coherent modules Functions can be parameterized providing a general solution that can be customized with specific parameters Functions offers a method for spreading the code around many files, thus providing a method for organization of code (into libraries, say) Once defined, a function can be called from anywhere accessible and any number of times resulting in reusability, standardization and uniform application of operations
Function Design 5/11/2013 Amrita-UB-MSES Lets say you want to turn Fahrenheit to Celsius converter into a function rather than dumping all the code in the main function. fcel Value in F Converted value in C celf Value in C Converted value in F
Function Definition 5/11/2013 Amrita-UB-MSES Define the prototype Type function name (parameter type, parameter type…); 2. Define the header Return type function name (param type name, param type name…) 3. Define the body of the function { local variable statements one or more return statements} Example: float fcel (float); float fcel (float fah) { float celsius = (5.0/9.0) * (fah ); return celsius; }
Function Call 5/11/2013 Amrita-UB-MSES It is not enough defining the function: it needs to be activated. This is done by calling the function. Calling a function involves specifying its name and actual parameter values. If there is a return value the call needs to be assigned to a variable. Example float fahren = 35.0; float celsius = fcel(fahren);
Complete Example 5/11/2013 Amrita-UB-MSES Lets write another function for Celsius to Farenheit. float celf (float celsi) { float fahr = celsi * 9.0/ ; return fahr; } Call: float fa = celf (35.0);
Demos 5/11/2013 Amrita-UB-MSES Lets add an input statement to the functions and complete the example. Scanf is the input statement. You provide the format(type) as well as the location (address) with name the input will be loaded into. Example: scanf(“%f”, &celsi); scanf(“%f”, &fahr); celsi fahr
Summary 5/11/2013 Amrita-UB-MSES We studied basics of a function design. We learned function definition and function call. Standard IO using printf and scanf was also illustrated. Parameter passing by value and reference was introduced. We will discuss this in detail later. We demoed the implementation of the functions.