GCSE Link: 2.10 (Subroutines)

Again, there's nothing new here. Everything below has been copied over from the GCSE page.

A subroutine is a set of instructions inside an algorithm stored under one name.

Subroutines save us from repeating the same code over and over again. They give your program more structure and readability whilst reducing the amount of code you have to write.

There are two types of subroutines: procedures and functions.

A procedure is a subroutine which doesn't return a value.

Example 1 shows a procedure to output the string "Hello" in C#.

Example 1
static void Greeting1() {
  Console.WriteLine("Hello");
}

Now, when we want to use this procedure, we can call it like this: greeting1();


Subroutines can also take parameters (inputs)

Example 2 shows a procedure to output the string "Hello " + the user's name.

Example 2
static void Greeting2(string name) {
  Console.WriteLine("Hello" + name);
}

Now, if this procedure is called with the code greeting2("Rujul"); it will output "Hello Rujul".

A function is a subroutine which does return a value.


Example 3 shows a function to convert inches to centimetres.

Example 3
static double InchesToCms(double inches) {
return inches * 2.54;
}


Example 4 shows a function to return the maximum of two numbers.

Example 4
static int Max(int a, int b) {
if (a > b) return a;
else return b;
}

The scope of a variable tells you which parts of the program it can be used in.

Local variables have a local scope: they can only be used inside the structure they're defined in.

Global variables have a global scope: they can be used anywhere.

Example 5 shows a program with both local and global variables. Note: this will not work in C#, but imagine this to be written in a C#-like pseudocode.

Example 5
int x = 0; int y = 0;

static void Move(int p, int q) {
  x += p; y += q;
}

Move(2, 6); Move(4, 1);

Console.WriteLine(x);
Console.WriteLine(y);

The outputs of this program are 6 and 7.



State the local and global variables in Example 5.

x and y are global variables: they are used throughout the program.
p and q are local variables: they can only be used inside the Move subroutine.