Functions, Arrays & Strings
10h
Class hours
7
Topics
0%
0/7 done
Why This Unit Matters
Master functions to write modular, reusable code. Then store and process collections of data with arrays. Finally, handle text with strings and the powerful C string library.
Functions
A function is a self-contained block of code that performs a specific task. C provides two categories: library functions (built-in, from headers like stdio.h, math.h) and user-defined functions that you write yourself.
Why use functions?
- Reusability — write once, call many times
- Modularity — break a large problem into smaller, manageable pieces
- Readability — each function has one clear job
- Easier debugging — isolate and test each unit independently
Function anatomy
| Part | Syntax | Purpose |
|---|---|---|
| Prototype | int max(int a, int b); | Declaration before main — tells the compiler the signature |
| Definition | int max(int a, int b) { ... } | The actual implementation |
| Call | max(x, y) | Executes the function and receives the return value |
Demonstrates function prototype, void function, and a function that returns a value.
"Why is a function required in C?" and "Write a program using a function to find the smallest of three numbers" appear frequently in TU BCA exams. Know the difference between prototype, definition, and call.
Call by Value vs Call by Reference
When you call a function, C can pass arguments in two ways, which differ in whether the original variable can be modified inside the function.
| Feature | Call by Value | Call by Reference |
|---|---|---|
| What is passed | A copy of the value | Address of the variable (&x) |
| Original variable | Unchanged after the call | Can be modified through the pointer |
| Mechanism | Normal parameters (int a) | Pointer parameters (int *a) |
| Use case | When you do not need to modify the original | Swap, output parameters, large structs |
The classic illustration is a swap function: it silently fails with call by value but works correctly with call by reference.
Run and observe — swapByValue leaves x and y unchanged; swapByRef correctly exchanges them.
"Explain call by value and call by reference with an example" is a standard 5-mark question. Always show the swap program for both, and state clearly why value-swap does not work.
Recursion
Recursion is a technique where a function calls itself. Every recursive solution requires two parts:
- Base case — the condition under which the function stops calling itself (prevents infinite recursion)
- Recursive case — the part where the function calls itself with a simpler input
Call stack for factorial(3)
factorial(2) → 2 × factorial(1)
factorial(1) → returns 1 (base case)
factorial(2) → returns 2 × 1 = 2
factorial(3) → returns 3 × 2 = 6
Enter 6 to see 6! = 720 and Fibonacci(6) = 8.
Recursion vs Iteration
| Aspect | Recursion | Iteration |
|---|---|---|
| Mechanism | Function calls itself | Loop (for/while) |
| Memory | Uses call stack — more memory per call | Uses a fixed set of variables |
| Speed | Slower due to function call overhead | Generally faster |
| Code clarity | Elegant for tree/divide-conquer problems | More explicit for simple loops |
| Risk | Stack overflow if base case is wrong | Infinite loop if condition is wrong |
"Differentiate between iteration and recursion. Write a program to print the first 15 Fibonacci terms using recursion." — a very common 5–8 mark question. Know the base cases: F(0) = 0, F(1) = 1.
1D Arrays
An array is a collection of elements of the same data type stored in contiguous memory locations under a single variable name. Elements are accessed by a zero-based index.
Declaration and initialization
float marks[5] = {85.5, 90.0, 76.0, 88.5, 92.0};
Common array operations
- Traverse — loop from index 0 to n-1 to read or print all elements
- Find max / min — keep a running maximum or minimum
- Sum and average — accumulate with sum += arr[i]
- Linear search — compare each element until found
- Bubble sort — repeatedly swap adjacent out-of-order elements
Enter 5 numbers. The program finds sum, maximum, and average.
Sorts a hardcoded array of 5 integers in ascending order.
Array programs with loops (sum, max, sort) are common 5-mark questions. Always mention that arrays are zero-indexed and that the last valid index is n-1.
2D Arrays & Matrices
A 2D array is an array of arrays — a table with rows and columns. In C, elements are stored in row-major order: all elements of row 0 are stored first, then row 1, and so on.
Declaration
mat[0][0] mat[0][1] mat[0][2] mat[0][3]
mat[1][0] ...
Matrix operations
| Operation | Formula | Condition |
|---|---|---|
| Addition | C[i][j] = A[i][j] + B[i][j] | Both matrices must be same size |
| Subtraction | C[i][j] = A[i][j] − B[i][j] | Both matrices must be same size |
| Multiplication | C[i][j] = Σ A[i][k] × B[k][j] | Cols of A must equal Rows of B |
| Transpose | T[j][i] = A[i][j] | Flips rows and columns |
Adds and multiplies two hardcoded 2×2 matrices.
"Write a C program to perform matrix multiplication" is a frequent 5-mark question. Always state the condition: columns of the first matrix must equal rows of the second.
Strings & String Functions
In C, a string is a character array terminated by the null character '\0'. There is no dedicated string type — strings live in char arrays, and the standard library <string.h> provides all manipulation functions.
Declaration and I/O
scanf("%s", name); /* reads until whitespace */
fgets(name, 50, stdin); /* reads full line including spaces */
Standard string functions — <string.h>
| Function | Purpose | Example |
|---|---|---|
| strlen(s) | Returns length excluding \0 | strlen("hello") → 5 |
| strcpy(dst, src) | Copies src into dst | strcpy(s3, s1) |
| strcat(dst, src) | Appends src to the end of dst | strcat("Hello", "World") → "HelloWorld" |
| strcmp(a, b) | Returns 0 if equal, <0 if a<b, >0 if a>b | strcmp("abc","abc") → 0 |
| strchr(s, ch) | Finds first occurrence of ch in s | strchr("hello", 'l') → pointer |
| strlwr / strupr | Convert to lower / upper case (Turbo C) | strupr("hello") → "HELLO" |
Enter 'hello' — the program reverses it manually using strlen.
Demonstrates the four most-tested string functions from <string.h>.
"Read a string and reverse it without using any string-handling function" has appeared in multiple TU BCA exam years. Also know all four core functions (strlen, strcpy, strcat, strcmp) with their signatures and return values.
Practice & Quiz
Active Recall Questions
Try to answer each question from memory before revealing the answer. Active recall is proven to be significantly more effective than re-reading.
What is the difference between call by value and call by reference?
What is recursion? What are its two required parts?
What is the index of the first element of an array in C?
What string functions does string.h provide? List the main ones.
What is a 2D array? How do you declare one?
Exam-Style Questions
Questions matching the style and marks distribution of TU BCA (CACS 151) past papers. Attempt each before revealing the full solution.
Write a C program using recursion to calculate n! (factorial).
5 marksWrite a C program to sort an array of n integers using bubble sort.
5 marksWrite a C program to count vowels and consonants in a string without using string.h.
5 marksQuick Revision
How to Remember
How to Remember Unit 3
Unit 3 introduces functions, call types, recursion, arrays, and strings — the tools that make C programs powerful. These analogies and mnemonics make the concepts memorable.
Mnemonics
Recursion Requirements
BR
Core String Functions
SSCC
Memory Tricks
Call by Value — Xerox Copy
Call by value gives the function a photocopy. You can scribble all over the copy — the original document (variable) is completely unaffected. The copy is discarded when the function returns.
Call by Reference — Shared Document
Call by reference shares the original document. The function holds a pointer to the real file. Any change through the pointer modifies the original. This is how swap works correctly.
Array Indexing — Ground Floor is 0
C starts counting from 0, not 1. An array of 5 elements is like a building with floors 0, 1, 2, 3, 4. The ground floor is 0. Accessing floor 5 doesn't exist — that's a bug.
2D Array — Excel Spreadsheet
Think of a 2D array as a spreadsheet. mat[row][col] — the first index is the row (which horizontal line), the second is the column (which vertical line). Row comes before column, just like coordinates (y,x) in math.
Stack Overflow from Recursion — Infinite Plates
Each function call is a plate placed on a stack. A recursive call adds another plate on top. Infinite recursion = infinite plates = the table collapses (stack overflow). Always have a base case to stop adding plates.
String Terminator \0 — The Invisible Sentinel
Every C string ends with \0 (ASCII 0, null character). strlen counts characters up to but NOT including \0. When you declare char str[50], position 49 is reserved for \0. Always allocate length+1.
Recursion Call Stack — factorial(4)
Stack builds up during the recursive calls (going down). Stack unwinds during the returns (going back up). Result is computed on the way back.
Before the Exam: Unit 3 Checklist