INTRODUCTION TO COMPUTING AND PROGRAMMING
Functions and Subprograms
1
MSc. Nguyen Van Tien
Contents
1. Concepts and syntax
2. Function definition
3. Function prototype
4. Parameters and function calls
5. Recursive function
2
Concept
Why use subroutines:
There is work that needs to be done in many places in the
program separate that work into subroutines.
For convenience in management, presentation and development.
In C, a subroutine is called a function: it has a name, an input,
and an output.
There is a function to solve some problems specific to the main
program.
3
Concept
Functions in C may return a result via the function name or may
not return a result.
A function, once defined, can be called in the program.
Called multiple times with different parameters.
In C, the main() function is called first.
Functions are of two types: standard functions (functions written
by the C compiler) and user-defined functions.
4
Standard function
Standard functions are predefined functions in a certain library.
If you want to use library functions, you must declare the library
before using the command
#include <library name.h>
5
Standard function
Meaning of some commonly used libraries:
1. stdio.h:
- The library contains standard input/output functions.
- Includes functions printf(), scanf(), getc(), putc(), gets(), puts(),
fflush(), fopen(), fclose(), fread(), fwrite(), getchar( ), putchar(),
getw(), putw()…
6
Standard function
Meaning of some commonly used libraries:
2. math.h:
The library contains calculation functions.
Includes abs(), sqrt(), log() functions. log10(), sin(), cos(), tan(),
acos(), asin(), atan(), pow(), exp(),…
3. alloc.h:
The library contains functions related to memory management.
Includes functions calloc(), realloc(), malloc(), free(), farmalloc(),
farcalloc(), farfree(), ...
7
Standard function
Meaning of some commonly used libraries:
4. graphics.h:
The library contains graphics related functions.
Includes initgraph(), line(), circle(), putpixel(), getpixel(),
setcolor(), ...
To use library functions, we must see the syntax of the functions
and use the correct syntax
8
User-defined function
C allows you to define functions according to your need. These
functions are known as user-defined functions. For example:
Suppose, you need to create a circle and color it depending upon
the radius and color. You can create two functions to solve this
problem:
createCircle() function
color() function
9
User-defined function
- Raise the problem
- How to write a function
- The scope of the function
10
User-defined function
Raise the problem
Write a program to calculate S = a! + b! + c! where a, b, c are 3
positive integers entered from the keyboard.
Main program
Enter Calculate
Print S
a, b, c > 0 S = a! + b! + c!
Enter Enter Enter Cal Cal Cal
a>0 b>0 c>0 s1=a! s2=b! s3=c!
11
User-defined function
do {
printf(“Enter a positive integer: ”);
scanf(“%d”, &a);
} while (a <= 0);
do {
printf(“Enter a positive integer: ”);
scanf(“%d”, &b);
} while (b <= 0);
do {
printf(“Enter a positive integer: ”);
scanf(“%d”, &c);
} while (c <= 0);
12
User-defined function
{ Calculate s1 = a! = 1 * 2 * … * a }
s1 = 1;
for (i = 2; i <= a ; i++)
s1 = s1 * i;
{ Calculate s2 = b! = 1 * 2 * … * b }
s2 = 1;
for (i = 2; i <= b ; i++)
s2 = s2 * i;
{ Calculate s3 = c! = 1 * 2 * … * c }
s3 = 1;
for (i = 2; i <= c ; i++)
s3 = s3 * i;
13
User-defined function
Solution => Write once and use many times
General input, with n = a, b, c
do {
printf(“Enter a positive integer: ”);
scanf(“%d”, &n);
} while (n <= 0);
The command to calculate the general factorial, n = a, b, c
14
Syntax
<return type> <function name>([parameters])
{
<statements>
[return <value>;]
}
<return type> : any type of C (char, int, long, float,...). If not
returned, it is void.
<function name>: according to identifier naming rules.
<parameters> : the input form parameter is the same as the
variable declaration, separated by commas,
<value> : returned to the function via the return statement.
15
How to write a function
The following information should be determined:
• Function name.
• What will the function do?
• Inputs (if any).
• Output (if any).
Input 1
Function name
Input 2 Output (if any)
The job to be
Input n
done
16
How to write a function
Example 1
• Function name: PrintSum
• Job: calculate and output the sum of 2 integers
• Input: two integers x and y
• Output: none
void PrintSum(int x, int y) {
int s;
s = x + y;
printf(“Sum of %d and %d is %d”, x, y, s);
}
17
How to write a function
Example 2
• Function name: GetSum
• Job: calculate and return the sum of 2 integers
• Input: two integers x and y
• Output: an integer with the value x + y
int GetSum(int x, int y) {
int s;
s = x + y;
return s;
}
18
How to write a function
Example 3
• Function name: ReadPrintSum
• Job: input and output the sum of 2 integers
• Input: none
• Output: none
void ReadPrintSum(int x, int y) {
printf(“Enter two integers: ”);
scanf(“%d%d”, &x, &y);
printf(“Sum of %d and %d is %d”, x, y, x + y);
}
19
The scope of the function
Concept
Is the effective range of variables and functions.
Variable:
Global: declare inside and outside all functions (including main
function) and affect the entire program.
Local: declared in a function or block { } and valid only within
the function or block itself (including its sub-blocks). The local
variable will be deleted from memory at the end of the block
declaring it.
20
The scope of the function
int a; int Func2()
int Func1() {
{ int a2;
int a1; {
} int a21;
}
}
void main()
{
int a3;
}
21
Function prototype
It is common to place the function header/prototype above main
and the function definition below main function
void PrintSum(int x, int y); // prototype
void main()
{
…
}
void PrintSum(int x, int y)
{
printf(“Sum of %d and %d is %d”, x, y, x + y);
}
22
Parameters and function calls
• Arguments in C are the variables that are used to pass
certain values.
• reduce code complexity and improve readability in the C
program.
• user-defined functions which allow us to reuse the code.
• pass the data in the form of an argument to the calling
function.
• passing data : integer, floating-point. Arrays or strings
can also be passed as a data to other functions.
• The parameter in C refers to any declaration of variables
within the parenthesis during the function declaration.
• These are listed in the function's definition, separated by
23
Parameters and function calls
24
Parameters and function calls
Example: Write a program to swap 2 elements
#include<stdio.h>
int main()
// Pass by value
1 void Swap1 (int x, int y) { int m=12; n=28;
{
2
3
int temp = x; Swap1(m,n);
x = y;
4
y = temp; printf(“m=%d n=%d\n”,m,n”);
5
6
}
// Pass by address (pointer)
Swap2(&m,&n);
7
void Swap2 (int *x, int *y)
{
printf(“m=%d n=%d\n”,m,n”);
8
9
int temp = *x; Swap3(m,n);
*x = *y;
10 *y = temp; printf(“m=%d n=%d\n”,m,n”);
11 }
// Pass by reference return 0;
12 void Swap3 (int &x, int &y)
13 { }
14 int temp = x;
15 x = y;
16 y = temp;
17 }
18
25
Parameters and function calls
Pass by value
• Pass arguments to the function as values.
• Constants, variables, and expressions can be passed, but the
function will only receive a value.
• Used when there is no need to change the value of the
parameter after executing the function.
void PassByValue (int x)
{
…
x++;
} 26
Parameters and function calls
Pass by address
• Pass arguments to the function in the form of an address
(pointer).
• Do not pass a value to this parameter.
• Used when there is a need to change the value of the
parameter after executing the function.
void PassByAddress (int *x)
{
…
*x++;
}
27
Parameters and function calls
Pass by reference
• Pass arguments to the function in the form of an address
(pointer). Begins with & in the declaration.
• Do not pass a value to this parameter.
• Used when there is a need to change the value of the
parameter after executing the function.
void PassByReference (int &x)
{
…
x++;
} 28
Parameters and function calls
Note
Within a function, parameters can be passed in many ways.
void Combine(int x, int &y)
{
…
x++;
y++;
}
29
Parameters and function calls
Note
Using a reference is a way to return a value to a program.
int GetSum(int x, int y) {
return x + y;
}
void CalSum(int x, int y, int &sum) {
sum = x + y;
}
void CalSumDiff(int x, int y, int &sum, int &diff) {
sum = x + y; diff = x – y;
}
30
Principles when writing a function
1. Each function does only one job.
2. Independent of other functions.
3. Function parameters need to be specified.
4. Reusability is as high as possible.
5. The data that the function uses:
• Keep each relationship as simple as possible.
Avoid using global variables as much as possible.
• If using global variables, write detailed
instructions.
31
Recursive function
Concept
• A subroutine can call another subroutine.
• Calling itself is called recursion.
• This number of calls must have a limit (breakpoint)
For example
Calculate S(n) = n! = 1*2*…*(n-1)*n
We see S(n) = S(n-1)*n
So instead of calculating S(n) we will go to calculate S(n-1)
Similarly calculate S(n-2), …, S(2), S(1), S(0) = 1
32
Recursive function
Example
int factorial(int n)
{
if (n == 0)
return 1;
else
return factorial(n – 1) * n;
}
33
Recursive function
• A recursive function must have 2 parts:
1. The stop or must have a base case. In the example above,
the case n=0 is the base case.
2. Recursive part: is the part that calls back the function being
defined. In the above example, the recursive part is n>0
then n! = n * (n-1)!
• Using a recursive function in a program will make the
program easier to read, understand, and highlight the
problem more clearly. However, in most cases,
recursive functions consume more memory and run
slower than non-recursive functions.
• Depending on each specific lesson, the programmer
decides whether to use recursion or not (there are 34
THANK
FOR YOUR ATTENTION!
35