Lecture 8 - Functions
Lecture 8 - Functions
Methodologies
Lecture 9 – Functions
Outline
However, we learnt to write only the simplest type of functions – those that
take no argument and return nothing.
In this Lecture, we shall learn how to write functions that take arguments,
those that return a result and those that do both.
3
Aspects of a Function
4
A function may or may not accept any argument. It may or may not return any
value.
Based on these facts, There are four different aspects of function calls.
function without arguments and without return value
function without arguments and with return value
function with arguments and without return value
function with arguments and with return value
Example for Function without argument and
return value
9
#include<stdio.h>
void printWelcome(); //function declaration
void main ()
{
printf("Hello ");
printWelcome(); //function call
}
void printWelcome() //function definition
{
printf(“Welcome to SIT 112 – Introduction to Programming");
}
10
#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Example for Function without argument and
with return value
11
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
12
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
14
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
16
#include<stdio.h> else
int even_odd(int); {
void main() printf("\nThe number is even");
{ }
int n,flag=0; }
printf("\nGoing to check whether a numb int even_odd(int n)
er is even or odd"); {
printf("\nEnter the number: "); if(n%2 == 0)
scanf("%d",&n); {
flag = even_odd(n); return 1;
if(flag == 0) }
{ else
printf("\nThe number is odd"); {
} return 0;
}
}
Types of Functions
We use function arguments to communicate with the function. There are
two types of function arguments:
Input arguments – ones that are used to pass information from the caller
(such as main function) to the function.
Output arguments – ones that return results to the caller from the
function. [we shall learn about these in the next lecture]
Types of Functions
No input arguments, no value returned – void functions without arguments
Input arguments, no value returned - void functions with arguments.
Input arguments, single value returned.
Input arguments, multiple value returned [next lecture]
17
void Functions with Input Arguments …
A function may take one or more arguments as input but returns no result.
Such functions should be declared as void, but each argument should be
declared in the bracket following the function name
An argument is declared in the same way as variables (its type followed by
the name of the argument).
Example: void print_rboxed(double rnum);
If there are more than one argument, they should be separated by comma.
Example: void draw_rectangle(int length, int width);
The following function example displays its argument value in a rectangular
box.
18
void Functions with Input Arguments…
19
Actual Arguments & Formal Parameters
• When the function call is encountered at run-time, the expression for the
actual argument is first evaluated, the resulting value is assigned to the
formal parameter, then the function is executed.
• Arguments make functions more versatile because they enable a function to
manipulate different data each time it is called.
20
Writing Modular programs using functions
22
Functions with Input Argument and a Single Result
By far, the must common types of functions in C are those that takes one or
more arguments and return a single result.
• For example, virtually all the functions in the <math.h> library, sqrt, log,
abs, sin, cos, etc. are in this category.
• Unlike void functions, for which the function call is a statement on its own,
functions that return a single result are often called as part of another
expression.
23
Functions with Input Argument and a Single Result…
26
Re-usability of Functions …
/* Uses the combination functions to computes the number /* Uses the factorial function to computes the
of combinations of n items taken r at a time */
number of combinations of n items taken
#include <stdio.h> r at a time. It assumes n >= r */
int factorial(int n);
int combinations(int n, int r); int combinations(int n, int r)
{
int main(void) {
int n, r, c; return factorial(n) / (factorial(r) *
factorial(n-r));
printf("Enter total number of components> "); }
scanf("%d", &n);
printf("Enter number of components selected> "); /* Computes n! for n greater than or equal to
scanf("%d", &r); zero */
if (r <= n) {
c = combinations(n, r); int factorial(int n) {
printf("The number of combinations is %d\n", c); int i, /* local variables */
} else {
printf("Components selected cannot exceed total product = 1;
number\n"); for (i = n; i > 1; --i) {
} product *= i;
system("pause"); }
return (0);
} /* Returns function result */
return (product);
}
27
Logical functions
As we saw with the functions draw_rectangle (int len, int wide|) and combination
(int n, int r), a function can have multiple arguments.
Below is another function that multiplies its first argument by 10 raised to the
power of its second argument.
Function call scale(2.5, 2)returns the value 250.0
30
Testing Function scale
32
Data Areas After Call scale(num_1, num_2);
33
Testing Functions Using Drivers
A function is an independent program module
As such, it can be tested separately from the program that uses it.
To run such a test, you should write a short piece of code called
driver that defines the function arguments, calls the functions, and
displays the value returned.
As long as you do not change the interface, your function can be
reused.
34
Why do we use Functions?
35
Procedural Abstraction
Procedural Abstraction – A programming technique in which a main
function consists of a sequence of function calls and each function is
implemented separately.
All of the details of the implementation to a particular subproblem is placed
in a separate function.
The main functions become a more abstract outline of what the program
does.
When you begin writing your program, just write out your algorithm in
your main function.
Take each step of the algorithm and write a function that performs it for
you.
Focusing on one function at a time is much easier than trying to write the
complete program at once.
36
Reuse of Function Subprograms
Functions can be executed more than once in a program.
Reduces the overall length of the program and the chance of error.
Once you have written and tested a function, you can use it in other
programs or functions.
37
Common Programming Errors
Remember to use a #include preprocessor directives for every standard
library from which you are using functions.
Place prototypes for your own function subprogram in the source file
preceding the main function; place the actual function definitions after the
main function.
The acronym NOT summarizes the requirements for argument list
correspondence.
Provide the required Number of arguments
Make sure the Order of arguments is correct
Make sure each argument is the correct Type or that conversion to the
correct type will lose no information.
Include a statement of purpose on every function you write.
Also be careful in using functions that are undefined on some range of
values.
38