Module: (Java) Subroutines: procedures and functions - 1


Problem

9 /11


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 curly bracketed block within which it is declared< /em>

The main program in Java is also a subroutine, so all variables declared inside main() are local variables 
Other subroutines don't "know" anything about the local variables of other subroutines.

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.

In Java, when the program starts, all global variables are automatically set to zero (boolean variables become false)


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
static void test() {   int i = 5; System.out.println(i); } static void test() {   int i = 5;   System.out.println(i); } public static void main(String[] args) { { int i = 7;   System.out.println(i);   test(); } public class Main { int i; static void test() {   i = 2; } public static void main(String[] args) { { test(); System.out.println(i); }

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