Week 4 – Functions Introduction
Functions: Purpose Breaking a large problem into a series of smaller problems is a common problem- solving technique In programming, this technique is accomplished using functions Using functions is often referred to as modularity Each function can be thought of as a black box: a function is given some information, does a specific task (eg finding the square root of a number) with that information and returns a result
Function Calls We have already been using some common functions such as printf and scanf We have used functions in our programs without understanding how they actually work – this is often the case when a function is used (remember functions are like a “black box”) A function is called or “invoked” by using the name of the function followed by ( ) and including within the brackets any information that the function needs to do its job.
Program Example using Common Functions The program below uses the functions printf and scanf for formatted input and output. main( ) { int n1; printf(“Enter integer: “); /* the info provided to printf is a text string */ scanf(“%d”,&n1); /* 2 types of info are provided to scanf: the datatype to be read and the address it is to be placed */ printf(“n1: %d\n”, n1);/* the info provided to printf is a text string containing a format string and an integer value */ }
Standard Functions Functions such as printf and scanf format output and obtain input These functions are defined in the stdio.h header file (standard input/output) and we do not need to include the code for them in our program However #include is a preprocessor directive (executed before compiling) to include another file as part of the source code #include will include standard input/output function prototypes, such as for printf and scanf, from the stdio.h header file in the standard library Note: The C compiler on phobos does not require the #include but it is required by many compilers
Program Example using #include Directive The program below includes the preprocessor directive #include because it used the functions printf and scanf which are defined in the stdio.h header file. Note: The C compiler on phobos does not require the #include but it is required by many compilers #include main( ) { int n1; printf(“Enter integer: “); scanf(“%d”,&n1); printf(“n1: %d\n”, n1); }