Functions
03603111 Programming Fundamentals I
Department of Computer Engineering, Faculty of Engineering at Sriracha
Course outline and schedule
2
Overview
3
Previous lesson recaps
4
Convenient counter-controlled style for loop
initialize;
while (condition) {
statement(s);
step;
}
for (initialize; condition; step)
statement
5
1
2
4
3
1
2
4
3
True
False
When to use which?
6
Arrays
// 10-element int array (40 bytes allocated), uninitialized
int xs[10];
// 3-element float array (24 bytes allocated), with initialization
double ys[] = { 1.0, 2.5, 4.5 };
// 5-element unsigned int array (20 bytes), initialized to 1, 2, 3, 0, 0
unsigned zs[5] = { 1, 2, 3 };
7
Value | 5 | 3 | 1 | 2 | 4 | 10 | 7 | 4 | 6 | 11 |
Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Operations on arrays
int arr[3];
arr[0] = 1;
arr[1] = arr[0] + 2;
arr[arr[0] + 1] = arr[0] + arr[1];
8
Value | 1 | 3 | 4 |
Index | 0 | 1 | 2 |
Variables, memory, and addresses
9
Address | Memory | Variable |
| | |
0xBC04 | A0 | exp |
0xBC05 | 86 | |
0xBC06 | 01 | |
0xBC07 | 00 | |
0xBC08 | 42 | name |
0xBC09 | 65 | |
0xBC0A | 63 | |
0xBC0B | 6B | |
0xBC0C | 00 | |
0xBC0D | 00 | |
0xBC0E | 00 | |
0xBC0F | 00 | |
0xBC10 | 04 | ptr |
0xBC11 | BC | |
| | |
int exp = 100000; // 0x186A0
char name[8] = "Beck"; // 0x42 0x65 0x63 0x6B 0x00
int *ptr = &exp; // 0xBC04
C null-terminated strings
char word[10] = "Hello!";
scanf("%9s", word);
10
Content | | | 'H' | 'e' | 'l' | 'l' | 'o' | '!' | '\0' | | | | | |
Memory | | | 48 | 65 | 6C | 6C | 6F | 21 | 00 | 00 | 00 | 00 | | |
Index | | | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | | |
Address | | 0xA10B | 0xA10C | 0xA10D | 0xA10E | 0xA10F | 0xA110 | 0xA111 | 0xA112 | 0xA113 | 0xA114 | 0xA115 | 0xA116 | |
Let’s continue with the lesson
Can we reduce this code duplication?
#include <stdio.h>
int main()
{
int a, b, c;
do {
printf("Enter value of dice A (1-6): ");
scanf("%d", &a);
} while (a < 1 || a > 6);
do {
printf("Enter value of dice B (1-6): ");
scanf("%d", &b);
} while (b < 1 || b > 6);
do {
printf("Enter value of dice C (1-6): ");
scanf("%d", &c);
} while (c < 1 || c > 6);
printf("Total value = %d\n", a + b + c);
return 0;
}
Enter value of dice A (1-6): 0
Enter value of dice A (1-6): 1
Enter value of dice B (1-6): 7
Enter value of dice B (1-6): 2
Enter value of dice C (1-6): 6
Total value = 9
Result
What if we have a command to “read_dice_value”?
int main()
{
int a, b, c;
a = read_dice_value("A");
b = read_dice_value("B");
c = read_dice_value("C");
printf("Total value = %d\n", a + b + c);
return 0;
}
13
Note how the code is much more readable compared to earlier
We can actually create such a command
int read_dice_value(char dice_name[])
{
int value;
do {
printf("Enter value of dice %s (1-6): ", dice_name);
scanf("%d", &value);
} while (value < 1 || value > 6);
return value;
}
14
What we’ve created is called a function
Return
type
Function name
Parameter
Return statement – type must match the return type
Function in action
#include <stdio.h>
int read_dice_value(char dice_name[])
{
int value;
do {
printf("Enter … %s (1-6): ",
dice_name);
scanf("%d", &value);
} while (value < 1 || value > 6);
return value;
}
int main()
{
int a, b, c;
a = read_dice_value("A");
b = read_dice_value("B");
c = read_dice_value("C");
printf("Total value = %d\n",
a + b + c);
return 0;
}
15
Call the function
Pass an argument
Assign return value to
Terminology
16
Function is an abstraction
17
By using functions, we can…
return-type function-name(parameter-list)
{
function-body
}
int max(int a, int b, int c)
18
Swapping two variables
a = b;
b = a;
int temp = a;
a = b;
b = temp;
19
Let’s put it in a function
#include <stdio.h>
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int a = 5, b = 10;
swap(a, b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
20
void means the function returns nothing
Parameters: value and reference semantics
21
Pointer review
int *ptr;
ptr = &exp;
*ptr = *ptr + 1000;
22
Correct version of swap()
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int a = 5, b = 10;
swap(&a, &b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
23
You’ve seen this kind of parameter passing in scanf()
Functions that returns nothing
24
Array and string parameters
25
Example: Counting string length
#include <stdio.h>
int my_strlen(char str[])
{
int count = 0;
while (str[count] != '\0')
count++;
return count;
}
int main()
{
char str[20];
printf("Enter a word: ");
scanf("%19s", str);
printf("Length of \"%s\" = %d\n", str, my_strlen(str));
return 0;
}
26
Enter a word: Hello!
Length of "Hello!" = 6
Result
Example: Adding to an array
#include <stdio.h>
void add_arr(int arr[], int size, int value) {
for (int i = 0; i < size; i++) {
arr[i] += value;
}
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
add_arr(arr, 5, 3);
printf("Updated array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
27
Updated array: 4 5 6 7 8
Result
Problem: Reversing a string
28
UNDERSTAND
SAMPLE INPUTS
WORK OUT
ALGORITHM
CODE
TEST
Blank sheet – work out your solutions here
29
Scope of variables
Local and global variables
#include <stdio.h>
int count = 0;
int inc1()
{
return ++count;
}
int inc2()
{
int count = 0;
return ++count;
}
int inc3()
{
static int count = 0;
return ++count;
}
int main()
{
printf("%d, %d, %d\n",
inc1(), inc2(), inc3());
printf("%d, %d, %d\n",
inc1(), inc2(), inc3());
printf("%d, %d, %d\n",
inc1(), inc2(), inc3());
return 0;
}
31
Local and global variables
32
Scope of variables
33
Can we put main() first?
int main()
{
double quintuple = common(2.0, 2.0) + triple(2.0);
}
double triple(double a)
{
return common(a, common(a, a));
}
double common(double a, double b)
{
return a + b;
}
34
Functions must be declared before use
// We can either rearrange the functions such that common() comes first
// Or we can use "forward declaration" like below:
double common(double a, double b); // forward declaration has no body
double triple(double a); // forward declaration has no body
int main()
{
double quintuple = common(2.0, 2.0) + triple(2.0);
}
double triple(double a)
{
return common(a, common(a, a));
}
double common(double a, double b)
{
return a + b;
}
35
With forward declaration,
this code now compiles
Recursive functions
Computing factorial
37
Translating mathematical definitions to code
38
Let’s work out fact_*(5) together!
Recursion
int fact_r(int n)
{
if (n == 0)
return 1;
else
return n * fact_r(n - 1);
}
39
Base case
Recursive step
Pre-order and post-order operations
Pre-order operation
void count(int n) {
if (n <= 0) {
return;
} else {
printf("%d ", n);
count(n - 1);
}
}
int main() {
count(5);
printf("\n");
}
Post-order operation
void count(int n) {
if (n <= 0) {
return;
} else {
count(n - 1);
printf("%d ", n);
}
}
int main() {
count(5);
printf("\n");
}
40
Printing is performed before calling itself
Printing is performed after calling itself
Try running and compare both versions!
That’s all for today!
41