Module: Subroutines: procedures and functions - 1


Problem

1/11

Subroutines: Introduction

Theory Click to read/hide

A subroutine is a separate part of a program that has a name and solves its own separate task. The subroutine is located at the beginning of the main program and can be launched (called) from the main program by specifying the name.

Using subroutines allows you to avoid code duplication if you need to write the same code in different places programs. 
Libraries that are imported into a program (for example, System) consist of routines that have already been compiled by someone. Programmers don't have to think about what algorithms are implemented in them, they just apply them, thinking only about what exactly they are doing. This is a big time saver. There is no need to write an algorithm that has already been written by someone else.

Each subroutine should only do one task, either calculate something, or output some data, or do something else. 

Subroutines, or methods, are of two types -  functions (those that return the result of work) and procedures (those that do not).

Let's start with the second type. Let's try to write a simple example.
Suppose we need to display the string "Error" on the screen every time an error can occur in the code due to the fault of the user (for example, when he enters incorrect data).
This can be done by writing the statement
Console.WriteLine("Error");
Now let's imagine that this line needs to be inserted in many places in the program. Of course, you can just write it everywhere. But this solution has two drawbacks.
1) this string will be stored in memory many times;
2) if we want to change the output on error, we will have to change this line throughout the program, which is rather inconvenient.

For such cases, methods and procedures are needed.
A program with a procedure might look like this:

using System;
classProgram {
    static void PrintError() {
        Console.WriteLine("Error");
    }
    static void Main() {
        PrintError();
    }
}

 

A procedure starts with the word void. After the procedure name  empty brackets are written.
All statements that are executed in a procedure are indented. 
The Static  modifier means that the given field, method or property will not belong to each object of the class, but to all of them together.
Methods and procedures are written before the main method Main().

To refer to a procedure, in the main program you need to call it by name and do not forget to write parentheses.
You can call a procedure in a program any number of times.

Problem

Write a procedure that prints "Error. Division by zero! Give the correct name to the procedure and write the output in it.