3.2.2, 3.2.10 - Subroutines, parameters and return values (C#)
Define reusable named code, pass data into it and return a result to its caller. Native C# written answers remain C#. C# execution is unavailable here; a labelled optional Python demonstration supports exploration.
Defining and calling subroutines
A subroutine is a named block of code that is defined separately and executed when the program calls its name.
Subroutine
A named out-of-line block of code called to perform a task. A procedure performs a task without returning a value; a function returns a value to its caller.
In C#, these are methods. This simple procedure has return type void, meaning it returns no value:
static void ShowWelcome()
{
Console.WriteLine("Welcome to the club");
}
Place this method inside class Program, outside Main. A statement ShowWelcome(); inside Main calls it. Defining the method does not display the message by itself. During a call, execution enters its body, performs the output, then resumes after the calling statement. Two calls display the message twice.
Subroutines avoid duplicated code, make the main program easier to read and let a named task be tested separately. If the welcome text changes, change its definition once rather than every copy. Names such as ShowWelcome and CalculateCost describe what each subroutine does, helping to decompose a larger problem.
Passing more than one parameter
Parameters pass data into a subroutine so the same code can work with different inputs on different calls.
static void ShowReceipt(int quantity, double unitPrice)
{
Console.WriteLine("Quantity: " + quantity);
Console.WriteLine("Cost: " + quantity * unitPrice);
}
The caller uses ShowReceipt(3, 4.0);. The first supplied value becomes quantity and the second becomes unitPrice for that call. The receipt displays quantity 3 and cost 12. A later ShowReceipt(2, 5.0); uses a new pair and displays quantity 2 and cost 10. The order of supplied values must match the definition's documented meaning and types.
The interface here is: accept an integer item quantity and a real unit price in pounds; display the quantity and total cost; return no value. Both inputs are available within the body. The code does not need to read or alter an unrelated variable in Main. Other resources may distinguish arguments from parameters; AQA uses parameter for both the supplied data and the names receiving it.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account