Chapter 6 User-Defined Functions
Chapter 6 User-Defined Functions
Chapter 6 User-Defined Functions
User-defined Function
1
Definition: A function is a block of statements that performs a
specific task. The function is also known as procedure or
subroutine in other programming languages
2
Examples:
Computing Averages:
Suppose we often need to compute the average of two double values. The C
library doesn’t have an “average” function, but we can easily define our own.
Here’s what it would look like:
double average(double a, double b)
{
return (a + b) / 2;
}
• The word double at the beginning is average’s return
type: the type of data that the function returns each time
it’s called.
• The identifiers a and b (the function’s parameters)
represent the two numbers that will be supplied when
average is called. Each parameter must have a type (just
like every variable has a type); in this example, both a and b
have type double.
• A function parameter is essentially a variable whose initial 3
Examples:
Computing Averages:
Every function has an executable part, called the body,
which is enclosed in
braces. The body of average consists of a single return
statement.
4
Examples:
Computing Averages:
/* Computes pairwise averages of three numbers */
#include <stdio.h>
double average(double a, double b)
{
return (a + b) / 2;
}
int main(void)
{
double x, y, z;
printf("Enter three numbers: ");
scanf("%lf%lf%lf", &x, &y, &z);
printf("Average of %g and %g: %g\n", x, y, average(x, y));
printf("Average of %g and %g: %g\n", y, z, average(y, z));
printf("Average of %g and %g: %g\n", x, z, average(x, z));
return 0;
} 5
Examples:
Computing Averages:
Printing a Countdown
Not every function returns a value. For example, a function whose
job is to produce output may not need to return anything.
Consider the following function, which prints the message T
minus n and counting, where n is supplied when the function is
called:
void print_count(int n)
{
printf("T minus %d and counting\n", n);
7
Examples:
Printing a Countdown
/* Prints a countdown */
#include <stdio.h>
void print_count(int n)
{
printf("T minus %d and counting\n", n);
}
int main(void)
{
int i;
for (i = 10; i > 0; --i)
print_count(i);
return 0;
}
Output
T minus 10 and counting
T minus 9 and counting and so on. 8
Function Calls
A function call consists of a function name followed by a list of
arguments, enclosed in parentheses:
average(x, y);
average(x, y)
print_count(i)
A call of a void function is always followed by a semicolon to turn
it into a
statement:
print_count(i);
Enter a number: 34
Not prime
10
Testing Whether a Number Is
Prime
/* Tests whether a number is prime */
#include <stdio.h>
int is_prime(int n)
{
int divisor;
if (n <= 1)
return false;
for (divisor = 2; divisor * divisor <= n; divisor++)
int main(void)
if (n % divisor == 0) {
return 0; int n;
return 1; printf("Enter a number: ");
} scanf("%d", &n);
if (is_prime(n) == 1)
printf("Prime\n");
else
printf("Not prime\n"); 11
Flow of control of
a program with
functions
12
Class Practice:
Write a C program with a function that
takes 2 numbers as integer parameters and
returns the minimum of the two numbers.
13
Class Assignment 1:
Write a C program with a function that
takes n as an integer parameter and
returns the sum from 1 to n.
14
Function Declarations
A function declaration provides the compiler with
a brief indication of a function whose full
definition will appear later. A function declaration
as follows:
15
Example forward declaration
#include <stdio.h>
double average(double a, double b); /* DECLARATION */
int main(void)
{
double x, y, z;
printf("Enter three numbers: ");
scanf("%lf%lf%lf", &x, &y, &z);
printf("Average of %g and %g: %g\n", x, y, average(x,
y));
printf("Average of %g and %g: %g\n", y, z, average(y,
z));
printf("Average of %g and %g: %g\n", x, z, average(x,
z));
return 0;
}
double average(double a, double b) /* DEFINITION */
{ 16
Arguments
Call by Reference
20
Arguments
Call by reference Example
#include<stdio.h>
void swap (int *a, int *b); //Forward declaration
int main(void){
int x = 5, y = 10;
printf("Before calling the swap function\n");
printf(" x = %d, y = %d\n", x, y);
swap(x,y); //Function call
printf("After calling the swap function\n");
printf(" x = %d, y = %d\n", x, y);
return 0;
} void swap (int *a, int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
printf(" Inside the function after swapping \n");
printf(" a = %d, b = %d\n", *a, *b);
} 21
Self study:
22
Array Arguments
Arrays are often used as arguments. When a
function parameter is a one-dimensional array,
the length of the array can be (and is normally)
left unspecified:
Note that
total = sum_array(b[], LEN); /*** WRONG ***/
28
The return Statement
A non-void function must use the return statement to specify
what value it will return. The return statement has the form
return expression ;
The expression is often just a constant or variable:
Example:
return 0;
return status;
29
Program Termination
Since main is a function, it must have a return type. A program
terminates with the return statement or end of main function for a
void main function.
30
Program Termination
The exit Function
C allows us to pass EXIT_SUCCESS instead (the effect is the
same):
exit(EXIT_SUCCESS); /* normal termination */
Passing EXIT_FAILURE indicates abnormal termination:
exit(EXIT_FAILURE); /* abnormal termination */
31
Program Termination
The exit Function
return expression;
in main is equivalent to
exit(expression);
32
Recursion
A function is recursive if it calls itself. For example, the
following function computes n! recursively, using the formula n!
= n × (n – 1)!:
int fact(int n)
{
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}
33
Recursion
Some programming languages rely heavily on recursion, while
others don’t even allow it. C falls somewhere in the middle: it
allows recursion, but most C programmers don’t use it that often.
34
Recursion
Here’s another example of recursion: a function that computes xn,
using the formula xn = x * xn–1.
int power(int x, int n)
{ if (n == 0)
return 1;
else
return x * power(x, n - 1);
}
The call power(5, 3) would be executed as follows:
power(5, 3) finds that 3 is not equal to 0, so it calls
power(5, 2), which finds that 2 is not equal to 0, so it calls
power(5, 1), which finds that 1 is not equal to 0, so it calls
power(5, 0), which finds that 0 is equal to 0, so it returns 1, causing
power(5, 1) to return 5 × 1 = 5, causing
power(5, 2) to return 5 × 5 = 25, causing
power(5, 3) to return 5 × 25 = 125.
35
Recursion
We can find the factorial and power of a number using recursion.
But we have other options to find the quantities.
37
an array with
Recursion 7 elements
Increase low
Increase low
38
Recursion
Quick Sort Algorithm:
18 is greater than 12
Send 18 to high
location, decrease high
39
Recursion
Quick Sort Algorithm:
Put 12 to ow or high
40
Recursion
Quick Sort Program:
#include <stdio.h> /* Sorts an array of integers using Quicksort algorithm */
#define N 10
void quicksort(int a[], int low, int high);
int split(int a[], int low, int high);
int main(void)
{
int a[N], i;
printf("Enter %d numbers to be sorted: ", N);
for (i = 0; i < N; i++)
scanf("%d", &a[i]);
quicksort(a, 0, N - 1);
printf(“\nIn sorted order: ");
for (i = 0; i < N; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
} 41
Recursion
Quick Sort Program:
void quicksort(int a[], int low, int high)
{
int middle;
if (low >= high) return;
middle = split(a, low, high);
quicksort(a, low, middle - 1);
quicksort(a, middle + 1, high);
}
42
Recursion
Quick Sort Program:
int split(int a[], int low, int high)
{
int part_element = a[low];
for (;;) {
while (low < high && part_element <= a[high])
high--;
if (low >= high) break;
a[low++] = a[high];
while (low < high && a[low] <= part_element)
low++;
if (low >= high) break;
a[high--] = a[low];
}
a[high] = part_element;
return high;
}
43
44