Unit 3: Functions and arrays
Problem Solving Techniques notes · PTU syllabus (UGSEC2501)
On this page
Unit summary
Functions break a large program into small reusable parts, arrays store many values of the same type, and strings are arrays of characters. This unit covers defining and calling functions, passing arguments, function prototypes and recursion, one- and two-dimensional arrays, passing arrays to functions, string handling and the storage classes automatic, external and static.
After this unit you can
- Define, declare and call functions with arguments and return values
- Explain call by value and call by reference
- Write recursive functions
- Process one- and two-dimensional arrays and pass them to functions
- Declare and manipulate strings
- Distinguish the storage classes auto, extern, static and register
PTU syllabus topics
- Defining and accessing functions
- passing arguments
- argument data types
- function prototypes
- recursion
- defining and processing arrays
- passing arrays to a function
- multi-dimensional arrays
- string declaration and manipulation
- storage classes (automatic, external, static)
Topic 1
Defining and accessing functions
A function is a named block of code that performs one task; C programs are collections of functions, starting with main().
- 1Function prototype (declaration) before main
- 2Function call from the calling function
- 3Function definition — header and body
- 4return value goes back to the caller
c#include <stdio.h>
int add(int a, int b); /* prototype */
int main(void) {
int s = add(5, 7); /* call */
printf("Sum = %d\n", s);
return 0;
}
int add(int a, int b) { /* definition */
return a + b;
}- Return type
- Type of the value returned — int, float, void
- Function name
- An identifier
- Parameters (formal arguments)
- Variables in the definition
- Arguments (actual arguments)
- Values in the call
- Body
- Statements in braces
- return
- Sends a value back and ends the function
Types of functions by arguments and return value
| Example | |
|---|---|
| No arguments, no return | void greet(void) |
| Arguments, no return | void show(int n) |
| No arguments, return value | int getNumber(void) |
| Arguments and return value | int max(int a, int b) |
Defined in
Header files
The programmer's program
Examples
printf, sqrt, strlen
add, factorial
Advantage
Ready to use, tested
Reuse, modularity, easier debugging
Exam tip
A function prototype tells the compiler the name, return type and parameter types so that calls can be checked.
Example
A function with return: int sum(int a, int b) { return a + b; } — calling printf("%d", sum(4, 5)); prints 9. The prototype int sum(int, int); goes before main.
Exam tip
Learn prototype, definition and call.
Topic 2
Passing arguments
What is passed
A copy of the value
The address of the variable
Effect on the original
Unchanged
Changed through the pointer
Syntax
swap(a, b)
swap(&a, &b)
Use
Protect data
Return several results
cvoid swapValue(int a, int b) { int t = a; a = b; b = t; } /* original unchanged */
void swapRef(int *a, int *b) { int t = *a; *a = *b; *b = t; } /* original swapped */
/* main: x = 5, y = 9; swapValue(x, y) leaves 5, 9; swapRef(&x, &y) gives 9, 5 */- Type match
- Arguments should match the parameter types
- Automatic conversion
- Float passed to an int parameter is truncated
- Arrays
- Passed by address
- Default return type
- Use int main(void)
- void
- Function returns nothing
Return address
Where to continue after the function
Parameters
Copies of arguments
Local variables
Created at call, destroyed at return
Stack frame
One per active call
Example
Tracing a swap: with a = 5 and b = 10, swapValue(a, b) swaps only copies, so afterwards a = 5 and b = 10. swapRef(&a, &b) receives the addresses and swaps the originals, so afterwards a = 10 and b = 5.
Exam tip
Arrays are always passed by reference in C: the function receives the address of the first element.
Topic 3
Recursion
Recursion is a function calling itself; it needs a base case (stopping condition) and a recursive case that moves towards the base.
clong fact(int n) {
if (n <= 1) return 1; /* base case */
return n * fact(n - 1); /* recursive case */
}- 1
fact(4) = 4 × fact(3)
- 2
fact(3) = 3 × fact(2)
- 3
fact(2) = 2 × fact(1)
- 4
fact(1) = 1 (base case)
- 5
fact(2) = 2 × 1 = 2
- 6
fact(3) = 3 × 2 = 6
- 7
fact(4) = 4 × 6 = 24
Mechanism
Function calls itself
Loop repeats
Memory
Uses stack for each call
Constant
Speed
Slower, overhead of calls
Faster
Code
Short, natural for trees, factorial, Fibonacci, Hanoi
Longer
Risk
Stack overflow without a base case
Infinite loop
Classic recursive functions
| Definition | |
|---|---|
| Factorial | n! = n × (n − 1)!, 0! = 1 |
| Fibonacci | fib(n) = fib(n − 1) + fib(n − 2), fib(0) = 0, fib(1) = 1 |
| GCD (Euclid) | gcd(a, b) = gcd(b, a mod b), gcd(a, 0) = a |
| Power | pow(x, n) = x × pow(x, n − 1) |
| Sum of digits | sum(n) = n mod 10 + sum(n / 10) |
| Tower of Hanoi | Move n − 1 discs, move the largest, move n − 1 again — 2ⁿ − 1 moves |
Example
Tower of Hanoi with 3 discs needs 2³ − 1 = 7 moves.
Topic 4
Arrays
An array is a collection of elements of the same type stored in contiguous memory and accessed by an index starting at 0.
cint marks[5] = {70, 85, 60, 90, 75}; /* declaration with initialisation */
int total = 0, i;
for (i = 0; i < 5; i++) total += marks[i];
printf("Average = %.2f\n", total / 5.0);| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Value | 70 | 85 | 60 | 90 | 75 |
| Address (4-byte int, base 1000) | 1000 | 1004 | 1008 | 1012 | 1016 |
- Declaration
- type name[size];
- Index
- 0 to size − 1
- Initialisation
- int a[3] = {1, 2, 3}; partial initialisation fills the rest with 0
- Size
- Fixed at compile time
- No bounds checking
- Going beyond the size is undefined behaviour
- Address of a[i]
- base + i × sizeof(type)
Common array operations
| Idea | |
|---|---|
| Traversal | Visit every element with a loop |
| Search | Linear search compares each element; binary search needs a sorted array |
| Sort | Bubble sort swaps adjacent elements |
| Insert and delete | Shift elements |
| Largest and smallest | Compare with a running maximum |
c/* bubble sort */
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - 1 - i; j++)
if (a[j] > a[j + 1]) { t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; }Passing arrays to a function
cfloat average(int a[], int n) { /* array decays to a pointer */
int s = 0, i;
for (i = 0; i < n; i++) s += a[i];
return (float) s / n;
}
/* call: average(marks, 5); — only the name is passed, no [] */- Arrays are passed by address, so changes inside the function affect the original; the size must be passed separately.
Two-dimensional arrays
cint m[2][3] = { {1, 2, 3}, {4, 5, 6} }; /* 2 rows and 3 columns */
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++)
printf("%d ", m[i][j]);Row-major storage of m[2][3]
| Element and address | |
|---|---|
| m[0][0], m[0][1], m[0][2] | 1000, 1004, 1008 |
| m[1][0], m[1][1], m[1][2] | 1012, 1016, 1020 |
| Address of m[i][j] | base + (i × columns + j) × size |
Matrix operations with arrays
| Rule | |
|---|---|
| Addition | c[i][j] = a[i][j] + b[i][j] |
| Transpose | t[j][i] = a[i][j] |
| Multiplication | c[i][j] = sum over k of a[i][k] × b[k][j] (columns of a = rows of b) |
- Declaration
- int a[3][4][5]; (three dimensions)
- Initialisation
- Row by row with nested braces
- Passing to a function
- All dimensions except the first must be given — int m[][3]
- Use
- Matrices, tables, images
Topic 5
Strings
A string is a character array ending with the null character '\0'.
cchar name[10] = "SBS"; /* stored as S B S \0 */
char city[] = {'B','T','I','\0'};
printf("%s %d\n", name, (int) strlen(name)); /* SBS 3 */| Index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| Character | S | B | S | \0 |
String functions of string.h
| Purpose | |
|---|---|
| strlen(s) | Length without '\0' |
| strcpy(d, s) | Copy s into d |
| strcat(d, s) | Append s to d |
| strcmp(a, b) | 0 if equal, negative if a < b, positive if a > b |
| strncpy, strncat, strncmp | Limited-length versions |
| strchr and strstr | Find a character or a substring |
| strrev and strupr | Non-standard — reverse and upper-case |
c/* length, copy, compare and reverse without library functions */
int len(char s[]) { int i = 0; while (s[i] != '\0') i++; return i; }
void rev(char s[]) { int i = 0, j = len(s) - 1; char t;
while (i < j) { t = s[i]; s[i++] = s[j]; s[j--] = t; } }- Reading
- scanf("%s") stops at a space; fgets reads a line
- Size
- Reserve one extra byte for '\0'
- Comparison
- Use strcmp — a == b compares addresses
- Assignment
- Use strcpy — s1 = s2 is not allowed
- Palindrome
- Compare characters from both ends
Topic 6
Storage classes
A storage class decides the scope (where visible), lifetime (how long it exists), default value and storage place of a variable.
auto
Stack; garbage
Block; until the block ends
register
CPU register if available; garbage
Block; until the block ends
static
Data segment; zero
Block (local static) or file; entire program run
extern
Data segment; zero
Whole program; entire program run
c#include <stdio.h>
int g = 10; /* global (extern) variable */
void counter(void) {
static int c = 0; /* initialised once, keeps its value between calls */
int a = 0; /* auto — reset on every call */
c++; a++;
printf("static %d auto %d\n", c, a);
}
int main(void) { counter(); counter(); counter(); return 0; } /* 1 1, 2 1, 3 1 */- auto
- Default for local variables
- register
- Request for fast access; cannot take its address
- static (local)
- Retains value between calls
- static (global)
- Visible only in its own file
- extern
- Refers to a variable defined in another place or file
- Scope rules
- Local hides global with the same name
Key terms
- Function
- Named block of code performing a specific task
- Prototype
- Declaration giving the name, return type and parameter types
- Call by value
- Passing a copy of the argument
- Call by reference
- Passing the address so the original can change
- Recursion
- A function calling itself
- Base case
- Condition that stops recursion
- Array
- Collection of same-type elements in contiguous memory
- String
- Character array ending with the null character
- Storage class
- Determines scope, lifetime and default value of a variable
- static variable
- Variable that retains its value between function calls
Quick revision
- Function = prototype, definition, call; void when no return value.
- Call by value copies; call by reference passes addresses (pointers).
- Recursion needs a base case; factorial, Fibonacci, GCD, Hanoi.
- Array index from 0; arrays go to functions by address; 2-D arrays are stored row by row.
- Strings end with '\0'; strlen, strcpy, strcat, strcmp.
- Storage classes: auto, register, static, extern.
Important exam questions
Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).
Short-answer questions
- Q1.What is a function prototype?
- Q2.Differentiate between actual and formal arguments.
- Q3.Differentiate between call by value and call by reference.
- Q4.What is recursion? What is a base case?
- Q5.Write the declaration of an array of 10 integers.
- Q6.How are arrays passed to functions?
- Q7.What is a string? How does C mark its end?
- Q8.Differentiate between strcpy and strcat.
- Q9.What is the default value of a static variable?
- Q10.What is the difference between auto and static storage classes?
Long-answer questions
- Q1.Explain the types of functions with examples.
- Q2.Explain call by value and call by reference with a swap program.
- Q3.Write a recursive program for factorial and the Fibonacci series.
- Q4.Write a program to sort an array using bubble sort.
- Q5.Write a program to add and multiply two matrices.
- Q6.Explain string handling functions with examples.
- Q7.Explain the storage classes of C with examples.
Stuck on this unit?
Message SBS on WhatsApp for help with Problem Solving Techniques, or to ask about studying BCA at Synetic.
