Unit 3 of 4 · BCA Sem 1

Unit 3: Functions and arrays

Problem Solving Techniques notes · PTU syllabus (UGSEC2501)

5 min read6 topics17 exam questions
On this page
  1. Unit summary
  2. Defining and accessing functions
  3. Passing arguments
  4. Recursion
  5. Arrays
  6. Strings
  7. Storage classes
  8. Key terms
  9. Quick revision
  10. Important questions

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)
1

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().

ProcessElements of a function
  1. 1Function prototype (declaration) before main
  2. 2Function call from the calling function
  3. 3Function definition — header and body
  4. 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;
}
Key termsParts of a function
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 returnvoid greet(void)
Arguments, no returnvoid show(int n)
No arguments, return valueint getNumber(void)
Arguments and return valueint max(int a, int b)
ComparisonLibrary vs user-defined functions
Library functions
User-defined functions

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.

2

Topic 2

Passing arguments

ComparisonCall by value vs call by reference
Call by value
Call by reference (using pointers)

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 */
Key termsArgument data types and conversion
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
ClassificationMemory of a function call
Call stack
  • 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.

3

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 */
}
ProcessFactorial of 4 — calls go down, values return up
  1. 1

    fact(4) = 4 × fact(3)

  2. 2

    fact(3) = 3 × fact(2)

  3. 3

    fact(2) = 2 × fact(1)

  4. 4

    fact(1) = 1 (base case)

  5. 5

    fact(2) = 2 × 1 = 2

  6. 6

    fact(3) = 3 × 2 = 6

  7. 7

    fact(4) = 4 × 6 = 24

ComparisonRecursion vs iteration
Recursion
Iteration

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
Factorialn! = n × (n − 1)!, 0! = 1
Fibonaccifib(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
Powerpow(x, n) = x × pow(x, n − 1)
Sum of digitssum(n) = n mod 10 + sum(n / 10)
Tower of HanoiMove 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.

4

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);
Index01234
Value7085609075
Address (4-byte int, base 1000)10001004100810121016
Key termsArray points
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
TraversalVisit every element with a loop
SearchLinear search compares each element; binary search needs a sorted array
SortBubble sort swaps adjacent elements
Insert and deleteShift elements
Largest and smallestCompare 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
Additionc[i][j] = a[i][j] + b[i][j]
Transposet[j][i] = a[i][j]
Multiplicationc[i][j] = sum over k of a[i][k] × b[k][j] (columns of a = rows of b)
Key termsMultidimensional array points
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
5

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 */
Index0123
CharacterSBS\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, strncmpLimited-length versions
strchr and strstrFind a character or a substring
strrev and struprNon-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; } }
Key termsString handling points
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
6

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.

ComparisonStorage classes in C
Storage and default value
Scope and lifetime

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 */
Key termsPoints on storage classes
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

  1. Q1.What is a function prototype?
  2. Q2.Differentiate between actual and formal arguments.
  3. Q3.Differentiate between call by value and call by reference.
  4. Q4.What is recursion? What is a base case?
  5. Q5.Write the declaration of an array of 10 integers.
  6. Q6.How are arrays passed to functions?
  7. Q7.What is a string? How does C mark its end?
  8. Q8.Differentiate between strcpy and strcat.
  9. Q9.What is the default value of a static variable?
  10. Q10.What is the difference between auto and static storage classes?

Long-answer questions

  1. Q1.Explain the types of functions with examples.
  2. Q2.Explain call by value and call by reference with a swap program.
  3. Q3.Write a recursive program for factorial and the Fibonacci series.
  4. Q4.Write a program to sort an array using bubble sort.
  5. Q5.Write a program to add and multiply two matrices.
  6. Q6.Explain string handling functions with examples.
  7. 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.

WhatsApp us