Home / Notes / Class 12 / Computer Science / Programming and arrays

Programming and arrays: Class 12 Computer Science

Written by Usman Tariq (Computer Science)

Functions in C, parameters and return values, scope of variables, one-dimensional and two-dimensional arrays, strings as character arrays, common array algorithms such as searching and sorting, and introduction to pointers.

Key points

A function is a named block of code that does one job and can be used again. Using functions divides a large program into small parts, avoids repeating code and makes testing easier. Examples of library functions are printf, scanf and sqrt. Programmers also write their own, called user-defined functions.

A function has a return type, a name and a list of parameters. Example: int add(int a, int b) { return a + b; }. A call such as s = add(3, 4); gives s = 7. A function that returns nothing has the type void. A function must be declared (a prototype such as int add(int, int);) before it is called, or written above main.

The values in the call are arguments and the variables in the function are parameters. In call by value, a copy of the argument is passed, so changes inside the function do not change the original. In call by reference a pointer is passed, so the function can change the original variable.

Scope is the part of the program where a variable can be used. A local variable is declared inside a function and exists only there. A global variable is declared outside all functions and can be used by all of them, but too many globals make a program hard to understand.

An array is a collection of variables of the same type stored in consecutive memory locations under one name. Declaration: int marks[5]; creates five integers. Indexes start at 0, so the valid elements are marks[0] to marks[4]. Using marks[5] is out of bounds and can crash the program or give wrong values.

Initialisation: int a[5] = {10, 20, 30, 40, 50}; If fewer values are given, the rest become 0. The size can be left out when values are listed: int a[] = {1, 2, 3}; has size 3. Elements are read or changed using the index, for example a[2] = 35;.

Arrays are usually processed with a for loop. To read and add five numbers: int a[5], i, s = 0; for (i = 0; i < 5; i++) { scanf("%d", &a[i]); s = s + a[i]; } The memory used is the number of elements times the size of one element, so 5 integers of 4 bytes use 20 bytes.

A two-dimensional array is a table with rows and columns. int m[2][3] has 2 rows and 3 columns, so 6 elements. m[1][2] is row 1, column 2 (counting from 0). Values can be set as int m[2][3] = {{1, 2, 3}, {4, 5, 6}}; Nested loops are used, the outer one for rows and the inner one for columns.

A string in C is a character array that ends with the null character '\0'. char name[6] = "Ahmed"; needs 6 elements, five letters plus the null. Functions from string.h include strlen (length), strcpy (copy), strcat (join) and strcmp (compare, giving 0 if equal). The format code %s prints a string, and strings cannot be compared with ==.

Common array algorithms:

  • Largest element: set max to a[0], then for each other element, if it is greater than max, replace max.
  • Linear search: compare each element with the key from the start until found or the end is reached.
  • Binary search: for a sorted array, compare the key with the middle element and discard half each time.
  • Bubble sort: repeatedly compare neighbours and swap them if out of order, so the largest value moves to the end in each pass.

Swapping two values needs a temporary variable: t = a[j]; a[j] = a[j+1]; a[j+1] = t;. For n elements bubble sort needs up to n − 1 passes. Linear search may need n comparisons, while binary search needs about log₂ n.

A pointer is a variable that stores the address of another variable. int *p = &x; makes p hold the address of x, and *p means the value at that address. The name of an array is the address of its first element, which is why arrays are passed to functions without copying all the values.

Study tip: Write array loops with the condition i < size, never i <= size. Trace array output questions with a table showing the index and value at every step. Learn one short program each for sum, largest value, linear search and bubble sort.

Definitions and flashcards

Say the meaning first, then open the card to check.

Function

A named block of code that performs one task and can be called again.

Parameter

A variable in the function header that receives a value.

Return value

The result that a function sends back to the caller.

Array

A group of same-type variables stored in consecutive memory under one name.

Index

The position number of an element, starting from 0.

String

A character array that ends with the null character.

Local variable

A variable that can be used only inside the function where it is declared.

Pointer

A variable that stores the memory address of another variable.

Sorting

Arranging the elements in ascending or descending order.

Formula sheet

NameFormulaWhat it means
Array memoryelements × size of one elementBytes used by an array
Address of elementbase + i × sizeMemory address of a[i]
Elements of 2D arrayrows × columnsTotal number of elements
Bubble sort passesn − 1Passes needed for n elements

Short questions with model answers

These are the kind of questions asked for 2, 3 and 5 marks. Try each one before opening the answer.

What is an array? Why is it used? (2 marks)

An array is a set of elements of the same data type kept in consecutive memory locations under one name. It is used to store many related values, such as the marks of 50 students, without declaring 50 separate variables, and it allows loops to process them.

Differentiate between call by value and call by reference. (3 marks)

In call by value, a copy of the argument is sent to the function, so the original does not change. In call by reference, the address of the variable is sent using a pointer, so the function works on the original and can change it.

Declare a 3 by 3 integer array and write code to print the sum of all its elements. (5 marks)

int m[3][3], i, j, s = 0; for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { scanf("%d", &m[i][j]); s = s + m[i][j]; } printf("%d", s); The outer loop moves over rows, the inner loop over columns, and each value is read and added to s.

What is the difference between local and global variables? (2 marks)

A local variable is declared inside a function and can be used only in that function. It is created when the function is called and removed when it ends. A global variable is declared outside all functions and can be used anywhere in the program for its whole run.

Explain the working of bubble sort. (3 marks)

Bubble sort compares each pair of neighbouring elements and swaps them if they are in the wrong order. After the first pass the largest element is at the end. The process repeats for the remaining elements, so after each pass one more element is in its final place. With n elements it takes n − 1 passes. It is easy to write but slow for large arrays.

Why does a string of 5 letters need an array of 6 characters? (3 marks)

A string in C must end with the null character, written '\0', which tells functions where the string stops. This extra character takes one element, so 5 letters need 6 elements.

Numericals with worked steps

An array int a[10] is stored from address 1000 and each int takes 4 bytes. Find the total memory and the address of a[3].
  1. Total memory = 10 × 4 = 40 bytes
  2. Address of a[3] = 1000 + 3 × 4
  3. = 1000 + 12 = 1012

Answer: 40 bytes; a[3] is at address 1012

What is the output? int a[5] = {2, 4, 6, 8, 10}; int s = 0, i; for (i = 1; i < 5; i += 2) s += a[i]; printf("%d", s);
  1. i = 1: s = 0 + a[1] = 4
  2. i = 3: s = 4 + a[3] = 12
  3. i = 5 fails i < 5

Answer: 12

Sort 5, 2, 4 with bubble sort and show each pass.
  1. Pass 1: compare 5 and 2, swap: 2, 5, 4. Compare 5 and 4, swap: 2, 4, 5
  2. Pass 2: compare 2 and 4, no swap. The array is 2, 4, 5
  3. A further pass has no swaps, so sorting ends

Answer: 2, 4, 5

How many bytes does int m[4][5] occupy if int is 4 bytes?
  1. Elements = 4 × 5 = 20
  2. Bytes = 20 × 4 = 80

Answer: 80 bytes

Common mistakes

  • Using index 1 as the first element. Indexes start at 0.
  • Writing a[5] for the last element of a 5-element array, which is out of bounds.
  • Comparing strings with == instead of strcmp.
  • Forgetting the null character when sizing a character array.
  • Expecting a function to change a normal variable passed by value.

Practise this chapter

Practice questions and timed test Printable worksheet

Previous: Software development