Subroutines - Functions

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

A set of instructions designed to perform a frequently used operation within a program. This makes it easy to repeat code. A subroutine must be contained in a class, and should the class not be the same as the one calling it, it should be referred to directly or by instantiation. A function is still a subroutine but it also returns a value of a specific data type.

Subroutine Example

 1 class Program 
 2 {
 3     static void Main(string[] args)
 4     {
 5        greeting();
 6        greeting();
 7     }
 8 
 9     public static void greeting()
10     {
11         Console.WriteLine("Hello");
12         Console.WriteLine("Pleased to meet you");
13     }
14 }
15 //Output:
16 //Hello
17 //Pleased to meet you
18 //Hello
19 //Pleased to meet you

Every time greeting() is written, the program runs the greeting function.

Passing Variables

Variables may need to be passed across subroutines in order for them to execute correctly.

Example

 1 namespace Project
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             greeting("Geoff");
 8             greeting("Bob");
 9         }
10 
11         static void greeting(string name)
12         {
13             Console.WriteLine("Hello, " + name);
14         }
15     }
16 }
17 //Output:
18 //Hello, Geoff
19 //Hello, Bob

Functions

A subroutine may need to return a variable type to assign to a variable when called. This can be done using any data type.

Example

 1 namespace Project
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             int x modulus(16, 3);
 8         }
 9 
10         static int modulus(int a, int b)
11         {
12             return a / b;
13         }
14     }
15 }