Module: (C++) Subroutines: procedures and functions - 1


Problem

1/12

Subroutines: Introduction

Theory Click to read/hide

Subroutines
A subroutine is a separate part of the 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 in the program. 
Libraries that are imported into the program (for example, the mathematical library сmath.h) consist of subroutines that have already been compiled by someone. Programmers do not need to think about what algorithms they implement, but simply 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 routine should only do one task,  either just calculate something, or output some data, or do something else. 

Subroutines are of two types - procedures and functions.

Subroutines perform some actions, for example, display the result on the screen in a certain form (a simple example, the operator printf()  is a standard subroutine that prints information to the screen)

Function subroutines return a result (number, character string, etc.) that we can use in the main program.

Let's try to write a simple procedure:
Suppose we want to display the string "Error" 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 operator cout << "Error"; And now imagine that such a 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, procedures are needed.
A program with a procedure might look like this: #include<iostream> using namespace std; void printError() // procedure description { cout << "Error"; // procedure body - commands that the procedure will execute } main() { ... printError() // start the procedure for execution. We just specify the name of the procedure we want to execute. ... printError() ... } The procedure begins with the word void. There are empty brackets after the procedure name.
All statements that are executed in a procedure are indented. 

Procedures are written before the main function main()

To execute a procedure, in the main program you need to call it by name and remember to write parentheses!
You can call a procedure in a program any number of times.

Problem

Write a procedure that displays the phrase "Error. Division by zero!". Give the correct name to the procedure.