Difference between revisions of "Subroutines - Functions"
(→Data Type Subroutines) |
(→Function Example) |
||
Line 1: | Line 1: | ||
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 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. | ||
− | == | + | == Subroutine Example == |
<syntaxhighlight lang="csharp" line> | <syntaxhighlight lang="csharp" line> | ||
class Program | class Program |
Revision as of 21:56, 17 December 2016
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.
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 }