3Unit 3

Functions, Arrays & Strings

10h

Class hours

7

Topics

0%

0/7 done

Progress0/7 topics

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

PartSyntaxPurpose
Prototypeint max(int a, int b);Declaration before main — tells the compiler the signature
Definitionint max(int a, int b) { ... }The actual implementation
Callmax(x, y)Executes the function and receives the return value
main.cmax() and greet() functions

Demonstrates function prototype, void function, and a function that returns a value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"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.

FeatureCall by ValueCall by Reference
What is passedA copy of the valueAddress of the variable (&x)
Original variableUnchanged after the callCan be modified through the pointer
MechanismNormal parameters (int a)Pointer parameters (int *a)
Use caseWhen you do not need to modify the originalSwap, 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.

main.cSwap: call by value vs call by reference

Run and observe — swapByValue leaves x and y unchanged; swapByRef correctly exchanges them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"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(3) → 3 × factorial(2)
  factorial(2) → 2 × factorial(1)
    factorial(1) → returns 1  (base case)
  factorial(2) → returns 2 × 1 = 2
factorial(3) → returns 3 × 2 = 6
main.cFactorial & Fibonacci using recursion

Enter 6 to see 6! = 720 and Fibonacci(6) = 8.

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent

Recursion vs Iteration

AspectRecursionIteration
MechanismFunction calls itselfLoop (for/while)
MemoryUses call stack — more memory per callUses a fixed set of variables
SpeedSlower due to function call overheadGenerally faster
Code clarityElegant for tree/divide-conquer problemsMore explicit for simple loops
RiskStack overflow if base case is wrongInfinite loop if condition is wrong
Exam Tip

"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

int arr[10]; /* declares 10 ints — arr[0] to arr[9] */
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
main.cArray: sum, max, average

Enter 5 numbers. The program finds sum, maximum, and average.

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
main.cBubble Sort

Sorts a hardcoded array of 5 integers in ascending order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

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

int mat[3][4]; /* 3 rows, 4 columns — 12 elements */
mat[0][0]  mat[0][1]  mat[0][2]  mat[0][3]
mat[1][0]  ...

Matrix operations

OperationFormulaCondition
AdditionC[i][j] = A[i][j] + B[i][j]Both matrices must be same size
SubtractionC[i][j] = A[i][j] − B[i][j]Both matrices must be same size
MultiplicationC[i][j] = Σ A[i][k] × B[k][j]Cols of A must equal Rows of B
TransposeT[j][i] = A[i][j]Flips rows and columns
main.cMatrix addition and multiplication (2×2)

Adds and multiplies two hardcoded 2×2 matrices.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"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

char name[50]; /* 49 chars + \0 */
scanf("%s", name); /* reads until whitespace */
fgets(name, 50, stdin); /* reads full line including spaces */

Standard string functions — <string.h>

FunctionPurposeExample
strlen(s)Returns length excluding \0strlen("hello") → 5
strcpy(dst, src)Copies src into dststrcpy(s3, s1)
strcat(dst, src)Appends src to the end of dststrcat("Hello", "World") → "HelloWorld"
strcmp(a, b)Returns 0 if equal, <0 if a<b, >0 if a>bstrcmp("abc","abc") → 0
strchr(s, ch)Finds first occurrence of ch in sstrchr("hello", 'l') → pointer
strlwr / struprConvert to lower / upper case (Turbo C)strupr("hello") → "HELLO"
main.cReverse a string without strrev

Enter 'hello' — the program reverses it manually using strlen.

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
main.cString functions: strlen, strcpy, strcat, strcmp

Demonstrates the four most-tested string functions from <string.h>.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"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.

1

What is the difference between call by value and call by reference?

2

What is recursion? What are its two required parts?

3

What is the index of the first element of an array in C?

4

What string functions does string.h provide? List the main ones.

5

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 marks

Write a C program to sort an array of n integers using bubble sort.

5 marks

Write a C program to count vowels and consonants in a string without using string.h.

5 marks

Quick 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

BBase case — the stopping condition (returns directly)
RRecursive case — the self-call that moves toward the base
Remember: no Base case = infinite recursion = stack overflow

Core String Functions

SSCC

SStrlen — returns length (excludes \0)
SStrcpy — copies src to dst
CStrcat — concatenates (appends src to dst)
CStrcmp — compares (0=equal, neg=less, pos=greater)

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.

void f(int x) { x = 99; } // original unchanged f(a); // a is still the same
📁

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.

void f(int *x) { *x = 99; } // changes original! f(&a); // a is now 99
🏢

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.

int arr[5]; // floors 0,1,2,3,4 arr[5] = 99; // out of bounds! 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.

mat[0][0] mat[0][1] mat[0][2] mat[1][0] mat[1][1] mat[1][2]
🍽️

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.

factorial(n) → plate n factorial(n-1) → plate n-1 ... factorial(1) → plate 1 (stops)
🔤

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.

"hello" = 'h','e','l','l','o','\0' stlen = 5 (not counting \0)

Recursion Call Stack — factorial(4)

factorial(4) ← calls factorial(3)
factorial(3) ← calls factorial(2)
factorial(2) ← calls factorial(1)
factorial(1) → returns 1 (BASE CASE)
factorial(2) → returns 2 × 1 = 2
factorial(3) → returns 3 × 2 = 6
factorial(4) → returns 4 × 6 = 24

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

Know difference: call by value (copy) vs reference (address/pointer)
Can write swap function using call by reference with pointers
Know two parts of recursion: base case and recursive case
Can trace factorial(5) call stack step by step
Know array indexing starts at 0; last valid index is n-1
Can write bubble sort with nested for loops
Know 2D array declaration and access: mat[row][col]
Know matrix multiplication condition: cols(A) == rows(B)
Can list 4 core string functions: strlen, strcpy, strcat, strcmp
Know strings end with \0 (null terminator)
Can write reverse-string without strrev manually
Can write vowel/consonant counter using null-terminator loop
BCAStudyHub

Your complete interactive study guide for TU BCA Semester I — covering all subjects with interactive tools, past papers, and exam prep.

TU BCASemester I

Program Info

University
Tribhuvan University
Program
BCA — Bachelor in Computer Application
Semester
I (First)
Subjects
5 (4 live, 1 coming soon)

Made by SawnN