Module: Subroutines: procedures and functions - 1


Problem

9 /12


Local and Global Variables

Theory Click to read/hide

It is often necessary to use additional variables that will only be used in the subroutine. Such variables are called local (or local) and can only be manipulated within the subroutine in which they are created.
 

Local variable scope is the function or procedure within which it is declared

Thus, it is possible to limit the scope (scope) of a variable only to the subroutine where it is really needed. In programming, this technique is called encapsulation  - hiding a variable from being changed from outside.

If it is necessary to declare a variable that would be visible anywhere in the program (in any subroutine), then such variables are declared outside of all subroutines (see program 3 from the table below)
Such variables are called global.

Analyze three programs: is displayed on the screen
1) In this program, the variable i is local. A local variable is declared inside a subroutine 2) Here, even if there is a variable i in the main program (with value 7), a new local variable i with value 5 will be created. 
When you run this program, the screen will display the value 75
3) This program has a global variable i. Its value can be changed inside a subroutine, and inside the main program
The procedure will work with the global variable i and it will be assigned a new value equal to 2. The value 2
procedure test();
var i: integer;
begin
    i := 5;
    writeln(i);
end;
var i: integer;

procedure test();
var i: integer;
begin
    i := 5;
    writeln(i);
end;

begin
    i := 7;
    write(i);
    test();
end.
var i: integer;

procedure test();
begin
    i := 2;
end;

begin
    test();
    writeln(i);
end.

Problem

Write a procedure with a parameter n that displays a Christmas tree with a crown of height n
The main program must contain the input of the value of the variable n and the call of the procedure

Examples
# Input Output
1 5
    o
   ooo
  ooooo
 ooooooo
ooooooooo