Monday, January 7, 2013

5.5. Local and global variables


So far, we have declared the variables in "Main". Now our program has several "blocks" so it will behave differently depending on where we declare the variables.

Variables can be declared within a block (a function), and then only that block will know them, so they cannot be used from any other program block. This is what we call "local variables".

On the other side, if we declare a variable at the beginning of the program, out of all the "blocks" of the program, it will be a "global variable", which can be accessed from anywhere.

Let's see an example. We will create a function that calculates the power of an integer (a number raised to another), and the body of the program to use it.

The way to raise a number to another will be based on repeated multiplications, ie

    3 raised to 5 = 3 · 3 · 3 · 3 · 3

(multiply 5 times 3 by itself). In general, as we can need things like "6 raised to 100" (or any other number, which may be big), we will use the "for" command to multiply as many times as needed:

/*---------------------------*/
/*  C# Example #50:          */
/*  example50.cs             */
/*                           */
/*  Example of function      */
/*  with local variables     */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example50
{

  public static int power(int nBase, int nExponent)
  {
    int temporary = 1;       // Temporary value for the power
    int i;                   // To be used in loops

    for(i=1; i<=nExponent; i++)     // Multiplying "n" times
      temporary *= nBase;           // in the temporary value

    return temporary;               // After the multiplications,
  }                                 // we obtain the desired value


  public static void Main()
  {
    int num1, num2;
  
    Console.WriteLine("Enter the base: ");
    num1 = Convert.ToInt32( Console.ReadLine() );
  
    Console.WriteLine("Enter the exponent: ");
    num2 = Convert.ToInt32( Console.ReadLine() );

    Console.WriteLine("{0} to the power of {1} is {2}",
      num1, num2, power(num1,num2));
  }
 
}

In this case, the variables "temporary" and "i" are local to the function named "power",  so they do not exist for "Main". If  we tried to do "i = 5;" inside "Main", we would get an error message.

Similarly, "num1" and "num2" are local to "Main", so inside the function "power" we can not access their value (neither to read it nor to modify it), only from "main".

In general, we must try to keep local as many variables as possible (ideally, all them  should be were). This way, we make every part of the program work with its own data, and help prevent that a mistake in a part of the program can affect the rest. The correct way to "pass" data between different parts of the program is using the parameters and the return values of each function, as in the previous example.

Suggested exercises:
·       (5.5.1) Create a function "readInteger" which receives as parameters the text to be displayed on screen, the minimum acceptable value and the maximum acceptable value. It should ask the user to enter the value as many times as necessary, ask again in case of error, and return a correct value. Test it with a program that asks the user for a year between 1800 and 2100.
·       (5.5.2) Create a function "displayTimesTable" with an integer parameter, which will write the multiplication table of that number (for example, for the 3, we must get from 3x0=0 to 3x10=30).
·       (5.5.3) Create a function "isPrime", which receives an integer number and returns the Boolean value "true" if it is a prime number or "false" otherwise.
·       (5.5.4) Write a function that receives a string and a letter, and returns the number of times that letter appears in the string. For example, if the string is "Barcelona" and the letter is 'a', it should return 2 (appears 2 times).
·       (5.5.5) Create a function that receives a number and returns any results in the sum of its digits. For example, if the number is 123 the sum would be 6.
·       (5.5.6) Create a function that receives a letter and a number, and displays a "triangle" formed by this letter, which has that number as its starting width. For example, if the letter is * and the width is 4, it should show
****
***
**
*


No comments:

Post a Comment