100 likes | 304 Views
C Language: Functions. B. Ramamurthy Ch.4 in Kernighan and Ritchie C textbook. Topics. Purpose of functions Function design Function definition Function call. Functions. Functions are modular units that perform a specific operation
E N D
C Language: Functions B. Ramamurthy Ch.4 in Kernighan and Ritchie C textbook Amrita-UB-MSES-2013-4
Topics Purpose of functions Function design Function definition Function call Amrita-UB-MSES-2013-4
Functions 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 Amrita-UB-MSES-2013-4
Function Design Lets say you want to turn Fahrenheit to Celsius converter into a function rather than dumping all the code in the main function. Value in C Value in F celf fcel Converted value in F Converted value in C Amrita-UB-MSES-2013-4
Function Definition • Define the prototype Type function name (parameter type, parameter type…); • Define the header Return type function name (param type name, param type name…) • 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 - 32.0); return celsius; } Amrita-UB-MSES-2013-4
Function Call 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); Amrita-UB-MSES-2013-4
Complete Example Lets write another function for Celsius to Farenheit. float celf (float celsi) { float fahr = celsi * 9.0/5.0 + 32.0; return fahr; } Call: float fa = celf (35.0); Amrita-UB-MSES-2013-4
Demos 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 Amrita-UB-MSES-2013-4
Summary 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. Amrita-UB-MSES-2013-4