Moving on to C# 5: Functions

Subroutines, no! Functions.

Functions are the equivalent to subroutines in Small Basic, except they are better. Subroutines are quite useful when you need to run the same bit of code a number of times, or even if you just want to separate a bit of code to make your program easier to understand.

Functions let you do this and more.

In fact, you already know about functions because you use them SB every time you use the Small Basic library to, for instance, make shapes, do maths, do something in the graphics or text windows. Let's take an example.

The Maths part of the of the SB library lets you get a random number between 1 and some other number. You provide that number either as a constant or a variable and the GetRandomNumber function gives you the random number back or, as we say, it returns the random number.

It looks like this:

num = GetRandomNumber(100)  'this is SB code

So this is a function like the ones we can write in C#. In this example we are giving the function the value 100 (this is called a parameter and we talk of passing parameters to functions) and it returns a value between 1 and 100 which is assigned to the variable num.

You cannot write subroutines like this is SB. You can't provide parameters for a subroutine and you cannot return a value from a subroutine. This, in my view, is one of the major deficiencies in SB.

A function in C# looks like this:

// A C# function
int square(int x){
    return x*x;
}

You can probably guess that this function returns the square of the parameter that is passed to it.

Let's have a quick look at the syntax. The function must have a name, square, in this case. Following the name of the function is a pair of braces inside of which is the name of the parameter. This is a bit like a variable and remember that in C# variables have to have a type; in this case its name is x (very original!) and it is an int (an integer, or whole number). Next is a pair of curly braces which enclose the code for the function. To return a value from the function we use the return statement and here we are returning x*x, i.e. the square of x.

You've probably noticed that I've missed something. What's this int before the name of the function? Well, like variables and parameters, functions must have types, too. The type of the function is the type of the value that it returns. So this function has the type int because the value it returns (x*x) is an int.

Using functions is the same as in SB. to use the one above you would write something like this:

// How to use a function in C#
int num1;
int num2 = 10;

num1 =  square(num2);

An example

Now you need to know how to put a program together that uses functions. So fire up Visual Studio Express and let's get coding.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SmallBasic.Library;

namespace CSSB1
{
    class Program
    {
        static void Main()
        {
           
        }
    }
}

This is where you start. You might remember that, previously, I told that all the code we write will go inside the innermost curly braces. This is now going to change. The main program goes there but any functions that we write go outside. Like this:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SmallBasic.Library;

namespace CSSB1
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1;
            int num2 = 10;

            num1 = square(num2);

            TextWindow.WriteLine(num1);

            TextWindow.Read();
        }
        static int square(int x)
        {
            return x * x;
        }
    }
}

As you can see this is the same the previous code with the addition of a text window to write the result to (and a text window read so that the program waits for you to press a key before terminating).

Look at where the function is. It's inside the braces for class Program but outside (and at the same level as) Main.

There´s one more thing, too. In this program (and others until we get to object-oriented programing) the function is preceded with the word static. This is not terribly important at this stage, as long as you remember that it has to be this way (and if you're happy with that you can skip to the end of the paragraph). Basically, a static function (or variable) is one that does not need to be created by creating an object. Objects can be created when you run a program but static functions and variables always exist whether you create objects or not. I'm not going to go any further with this, except to say that Main is ALWAYS static and anything (function or variable) that it uses directly has to be static, too.

Ok, another example.

A new random function

I´m going to demonstrate a new random function that will return a random number within a range, e.g. 1 to 15 or 0 to 5. First you can take a look at it, then I´ll explain. Here it is:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SmallBasic.Library;

namespace CSSB1
{
    class Program
    {
static void Main(string[] args)
        {
            int num1 = 5;
            int num2 = 10;
            int num3;
            for (int i = 0; i < 100; i++)
            {
                num3 = randomRange(num1, num2);
                TextWindow.WriteLine(num3);
            }

            TextWindow.Read();
        }
        // return a random number in the range bottom to top
        static int randomRange(int bottom, int top)
        {
            int result;
            int range = top - bottom +1;

            result = Microsoft.SmallBasic.Library.Math.GetRandomNumber(range);
            result = result - 1;
            result = result + bottom;

            return result;
        }
    }
}

There are some new features here but, first, let´s take a look at the main part of the program then we´ll look at the function.

In the main program we declare three variables, all integers. We set the value of the first two and leave the third undefined. Now we have a loop that runs 100 times. This calls the new function randomRange with the first two integers as parameters. The return value goes into the third integer and is displayed in the text window. All straightforward, I hope.

The purpose of the function is to return a number within the range given.

Look at the function, now. First the format. Notice we have two parameters (we can have as many as we want) separated by commas. Next notice that we have declared variables in the function. These are called local variables and are entirely private to the function, they cannot be accessed outside of the function. (In SB you cannot do this, you have to use what are  known a global variables that can be accessed from anywhere.)

Inside the function we first get the range of numbers that we need, e.g. in the example it is 5 to 10, so the range is 6 because we will be returning 5, 6, 7, 8, 9 or 10. Next we use the SB library function to get a number from 1 to that range (here, 1 to 6) then we subtract 1 to get it in the range 0 to 5, we then add on the bottom of the range and get, in this case a number between 5 and 10. We return that number.

That´s it!

Just one thing to note in case it is not clear. The names of the parameters in the function and the names of the parameters in the function call do NOT have to match, but their types MUST be the same.

Comments

Popular posts from this blog

Just Enough Python

Learn to code with C

Introduction to Python by Andrew Ng