Tag Archives: functions

Methods in C#

A method, also known as a function, is a module of code that a programmer can create and then call on later on in the program. Many methods already exist in programming languages such as C# but the programmer also has the ability to make their own. A method will usually perform a single task. Many methods can work together to achieve a goal.

Methods should have descriptive names (they should represent an action and are usually in the form of a verb). Spaces cannot be used in method names and you should always avoid use of special characters eg. $%^!@. The method name itself should also not contain brackets because brackets are used for parameters. When you create a new method, the method name should be unique and not already exist in the language (it should not be a reserved word that is used for a statement or method).

Method names should follow a consistent naming convention throughout your code eg. using camel case or mixed case. Examples of suitable method names include CalculateScore, AddNumbers, MultiplyNumbers, GetUserDetails, etc.

Watch the video below and then scroll down for examples and sample code.

Creating methods

Lets break up the method into its different components and look at each component…

What is an access modifier?

Access modifiers include public and private (or just left empty). Public means other parts of the program can see and use this method. If we don’t want that we use private instead or no access modifier (leave it out).

What is a return type?

Methods are able to return a variable back to the code that called it known as the return type. If a method returns an integer value then the return type is an int and if a method returns a true or false value then the return type is a bool. Even if the method doesn’t return any value, it still has a return type. If the method doesn’t return a value, then its return type is void (which means nothing). You might notice that many functions have a return type of void.

What are parameters?

In the same way that methods can pass a variable back to the code that called it, the calling code can pass variables into the method. These variables are known as parameters. The variables that are passed into the method are identified in the parameter list part of the method (inside the brackets). When you specify a parameter you must specify the variable type and the name. If there are no parameters, then the brackets are left empty.

Below is an example of a method in C# for a calculator that is used to add two numbers together. There are two parameters in this method (separated by commas). The parameters in this method are num1 and num2. These are the two numbers that will be added together (they are of the float data type). Notice that the return type is also float meaning that the result of this method (the sum of num1 and num2) will be returned as a float value.

public static float AddNumbers(float num1, float num2)
 {
   float total = num1 + num2;
   return total;
 }

The method above will add two numbers together (the two parameters num1 and num2) and then return the answer as a float back to the part of the program that called the method.

The word static means that this particular method is associated with the class, not a specific instance (object) of that class. What this means is that you are able to call a static method without actually creating an object of the class.

Many methods have the word void in their declaration. The word void basically means that the method will not return any value to the part of the program that called it.

Using methods

Once you have created a method the next thing to do is use it. Using a method is known as calling or invoking a method. To call a method that was named AddNumbers, you would write:

AddNumbers();

If the method contained a parameter or multiple parameters (eg. the values 5 and 10), then they would be included inside the brackets like this:

AddNumbers(5,10);

The below example shows how to call a method and pass variables into the method. You do not need to write int inside the brackets where the function is called.

int number1 = 10;
int number2 = 30
AddNumbers(number1,number2);

When you call a method you do not need to provide the variable type with the variable that is being passed into the method. If the method AddNumbers() in the example code above returns a value, then it should be stored in a variable or used in a statement, for example:

int result = AddNumbers(5,10);

Sample code

Here is an example using parameters and a return type of void. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      AddNumbers(5, 10);
    }
    public static void AddNumbers(int num1, int num2)
    {
      int total = num1 + num2;
      Console.WriteLine("The sum of the two numbers is " + total);
    }
  }
}

Here is an example using parameters and a return type of int. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int answer = AddNumbers(5, 10);
      Console.WriteLine(answer);
    }
    public static int AddNumbers(int num1, int num2)
    {
      int total = num1 + num2;
      return total;
    }
  }
}

Here is an example using no parameters. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int answer = AddNumbers();
      Console.WriteLine(answer);
    }
    public static int AddNumbers()
    {
      int total = 5 + 10;
      return total;
    }
  }
}

Methods in C#

In C#, methods are like functions. Methods can be created to store a list of instructions that can then be called on later on in the program. Methods can be used more than once so if there are instructions you need to use constantly throughout a program, then it makes sense to write them only once and call on them when needed rather than writing the instructions multiple times.

Methods also allow you to break up different tasks in your program an make them easily identifiable, rather than having a heap of different tasks in one big block of code (or spaghetti code).

The code below shows how to make a command-line calculator that breaks up each function of the calculator (adding, subtracting, multiplying and dividing numbers and checking which calculation option the user chose). The methods are declared and then called on in the program.

Sample C# code

using System; // tells this file we will be using the System namespace

namespace MyCSharpApp // new namespace called MyCSharpApp which will contain classes
{
  class MainClass // new class called MainClass
  {
    public static void Main (string[] args) //new method called Main (executes as soon as the app runs)
    // which has to be a public static void and will receive an array of strings
    {
      Console.WriteLine ("Hello World!");
      Console.WriteLine ("What is your name?");
      // WriteLine method is used to write a string to the console
      string name = Console.ReadLine();
      // we can add this method so the program will wait until the user
      // types something in or presses a key to continue
      // By creating a variable called name, now the ReadLine input is stored in a variable
      Console.WriteLine("Hi there, " + name);
      calculator ();
    }

    public static void calculator()
    {
      Console.WriteLine("Enter two numbers...");
      Console.WriteLine ("Enter the first number:");
      float num1 = float.Parse (Console.ReadLine ());
      // float.Parse() is used to convert string to float
      Console.WriteLine ("Enter the second number");
      float num2 = float.Parse (Console.ReadLine ());
      // could write Console.WriteLine(num1+num2);
      // or could use a method instead...
      Console.WriteLine ("Select an option\n1 - Add\n2 - Subtract\n3 - Multiply");
      int option = int.Parse(Console.ReadLine());
      checkOption (option, num1, num2);
    }

    // this creates a new method called addNums which takes two float arguments
    public static float addNums(float n1, float n2)
    {
      float answer = n1 + n2;
      return answer;
    }

    // this creates a new method called subtractNums which takes two float arguments
    public static float subtractNums(float n1, float n2)
    {
      float answer = n1 - n2;
      return answer;
    }

    // this creates a new method called multiplyNums which takes two float arguments
    public static float multiplyNums(float n1, float n2)
    {
      float answer = n1 * n2;
      return answer;
    }

    public static void checkOption(int option, float n1, float n2){
      if (option == 1) {
        Console.WriteLine ("The answer is: " + addNums (n1, n2));
      }

      else if (option == 2) {
        Console.WriteLine ("The answer is: " + subtractNums (n1, n2));
      }

      else if (option == 3) {
        Console.WriteLine ("The answer is: " + multiplyNums (n1, n2));
      }

      else {
        Console.WriteLine ("Option not recognised.");
      }
    }

  }
}

PHP include and require functions

The PHP include and require functions are used to include other PHP files in a PHP file. For example, a webpage which needs to have a header, content section, and footer can be made into three PHP files – the main file can then include the header and the footer files in it. This is useful if you have PHP code that needs to be included in many pages across a site and can save time coding as well as reducing the risk of human error when repeating code.

The include and require functions work similarly but do have a key difference. The include function will include a file but the rest of the code will not break if the other file can’t be found or loaded. On the other hand, the require function is used when another file is required but will break the rest of the page if it can’t be found or loaded.

Watch the video below and then scroll down to see the sample code.

Sample code

There are a few files involved here. You can also download the background image and CSS code used for the template.

Step 1: Create an index.php file and add the following code.

<html>
<head>
  <title>Home page</title>
 	<meta charset="utf-8"/>
 	<link rel="stylesheet" href="theme.css" type="text/css"/>
<body>
  <?php include 'header.php'
  // can also use require which does the same thing as include
  // however, if using require and the required file is missing,
  // errors will result in none of the rest of the page loading whereas
  // include will not kill the rest of the page.
  ?>

  <div id="content">
 	<h2>Welcome to my website</h2>
 	<p>The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.</p>
 	<p>The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.</p>
  </div>

  <?php include 'footer.php'?>
</body>

</html>

Step 2: Create a header.php file and include the following code:

<html>
<head>
</head>
<body>
 
<div id="header">
 <h1>My website</h1>
</div>
 
<div id="nav">
  <ul>
     <li><a href="index.php">Home</a></li>
     <li><a href="about.php">About</a></li>
     <li><a href="products.php">Products</a></li>
     <li><a href="support.php">Support</a></li>
     <li><a href="contact.php">Contact us</a></li>
  </ul>
</div>
</body>
</html>

Step 3: Create a footer.php file and include the following code.

<html>
<head>
</head>
<body>
<div id="footer">
 Copyright....2015.
</div>
</body>
</html>

Step 4: Create a theme.css file and include the following code. Change the CSS styling as you wish.

#header{
 background-image:url("background.png");
 background-color:#334a94;
 height:80px;
 color:#FFFFFF;
 text-align:left;
 padding-left:20px;
 padding-top:10px;
 font-family:Arial;
}
 
#nav{
 background-color:#334a94;
 height:30px;
 padding:5px;
}
 
#content{
 width:500px;
 padding:10px;
}

h2{
  font-family:"Tahoma";
}

p{
  font-family:"Palatino Linotype";
}
 
#footer{
 background-color:#334a94;
 color:#FFFFFF;
 clear:both;
 text-align:center;
 padding:20px;
}


ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 100%;
    background-color: #334a94;
}

#nav li{
    display: inline;
}

li a {
    
  font-family:Calibri;
  font-size: 14pt;
  font-style:none;
    color: #FFFFFF;
    padding: 8px 16px 8px 16px;
    text-decoration: none;
}

li a:visited {
    background-color: #4CAF50;
    color: #FFFFFF;
}

li a:hover {
    background-color: #786ED4;
    color: #000000;
}

Step 5: Download this image and include it in the same folder along with the three PHP files and one CSS file. You can add more pages (eg. about.php or products.php) and include the header and footer in each file.

Variable scope in PHP (local and global variables)

This tutorial explains variable scope in PHP. The scope of a variable refers to where a variable can be used in a program. A variable’s scope can either be global or local

Global variables are variables that have been declared outside of a function and can be accessed anywhere in the program including inside functions. Local variables are made inside a function and can only be access inside that function they were created in. In other words, the local variable from one function cannot be used in another function or outside the function in the main part of the program. However, local variables can be made global if the programmer needs to use the variable outside the function it was created in.

Watch the video below and then scroll down to see the sample code.

Sample PHP code:

<?php
  $globalVariable = 10;

  function scopeCheck(){
    global $globalVariable;
    // $globalVariable can be accessed by this function because it is now global
    $globalVariable = 20;
    echo $globalVariable;

    $localVariable;
    // $localVariable can only be accessed inside this function because it is local
    // Writing global $localVariable; will make the variable global.
    $localVariable = 50;
  }

  scopeCheck();
  echo $globalVariable; // this will work because variable is global
  echo $localVariable; // this will not work because variable is local
?>

Default arguments in PHP functions

This tutorial explains how to specify a default argument in a function, if an argument is expected but has not been provided to the function. Any provided argument will override the default argument, but the default argument will prevent problems from occurring if no argument is given when it is expected.

Providing default argument cam prevent errors from occurring if no argument is provided to a function when the function is called in the program. An argument may not be provided to a function, for example, if a user does not provide some information in a form or from some other method of user input.

Watch the video below and then scroll down to see the sample code.

Sample PHP code:

<?php
  function message($greeting, $name = "friend"){
    return "$greeting $name";
  }

  echo message("Hello there, " , "Batman");

  // Default arguments are used when no argument is given to the function.
  // In this example friend will be the default argument if no argument is given for $name.
  // However, if a second argument is provided (eg. "Batman"), then that
  // will override the default argument.
?>

Array implode and explode functions in PHP

This tutorial shows how to use the implode and explode functions on arrays in PHP. The implode function is used to turn an array into a string, whereas the explode function is used to turn a string into an array. Watch the video below and then scroll down to see the commented sample code.

Sample PHP code:

<?php
  $avengers = array("Iron Man","Thor","Hulk","Hawkeye","Black Widow");
  // implode - turns an array into a string
  $avengersString = implode(' ',$avengers);
  // implode(' ',$avengers); will add a space between each array item in the new string

  echo $avengersString; // displays the string

  // explode - turns a string into an array
  $superheroesString = "wolverine,batman,hulk,spider-man,storm,iron man";
  $superheroesArray = explode(',',$superheroesString);
  // explode(',',$superheroesString); will add each item occuring after a comma in
  // the string as a separate element in the array.

  echo $superheroesArray[5]; //displays the 6th element in the array
?>

Creating and calling functions in PHP

Functions allow you to write lines of code that can be used again and again in different parts of a program without actually having to write the lines of code several times. You can create a function that runs some lines of code (usually a specific set of instructions) and then ‘call’ that function to be used later on.

In the PHP language (like all other modern languages) there are a range of built-in functions that you can use in your programs. Many functions exist such as math functions (eg. to round a number), date functions (eg. to display the current time and date), and string functions (eg. to count how many characters are in a string, or convert a string to lowercase/uppercase). However, you can make your own functions and use them in your program.

Watch the video below to see how to create functions without parameters, with a parameter, and with more than one parameter. Then scroll down to see the sample PHP code.

Sample PHP code:

1
2
3
4
5
6
7
8
<?php
 function add($a,$b){
 $c = $a + $b;
 echo $a , " + " , $b , " = " , $c;
 }
 
 add(5,10);
?>

PHP Manual references:

Creating and using methods (functions) in C#

A method, also known as a function, is a module of code that a programmer can create and then call on later on in the program. Many methods already exist in programming languages such as C# but the programmer also has the ability to make their own. A method will usually perform a single task. Many methods can work together to achieve a goal.

In Unity, the Start method contains all of the code that will run for an object when a scene begins. The Update method contains all of the code that runs every single frame of the scene.

This is the basic syntax of a method:

<return type> <name>(<parameters>)
{
// code that runs inside the method goes here
}

Methods should have descriptive names (they should represent an action and are usually in the form of a verb). Spaces cannot be used in method names and you should always avoid use of special characters eg. $%^!@. The method name itself should also not contain brackets because brackets are used for parameters. When you create a new method, the method name should be unique and not already exist in the language (it should not be a reserved word that is used for a statement or method).

Watch the video below to learn how to create and use methods in C# and then scroll down to see the sample code.

Creating methods

Lets break up the method into its different components and look at each component…

What is a return type?

Methods are able to return a variable back to the code that called it known as the return type. If a method returns an integer value then the return type is an int and if a method returns a true or false value then the return type is a bool. Even if the method doesn’t return any value, it still has a return type. If the method doesn’t return a value, then its return type is void (which means nothing). You might notice that the Start and Update functions have a return type of void.

What are parameters?

In the same way that methods can pass a variable back to the code that called it, the calling code can pass variables into the method. These variables are known as parameters. The variables that are passed into the method are identified in the parameter list part of the method (inside the brackets). When you specify a parameter you must specify the variable type and the name. If there are no parameters, then the brackets are left empty.

Below is an example of a method in C# for a game in Unity that is used to apply damage to a player’s health. There are two parameters in this method (separated by commas). The parameters in this method are damageAmount and health. Notice that the return type is int.

int applyDamage(int damageAmount, int health)
{
 return health - damageAmount;
}

The above method is a simple example. In an actual game, the player’s health could instead be stored in a variable inside a script so it wouldn’t need to be read into a method. However, the example above shows the structure of methods.

Using methods

Once you have created a method the next thing to do is use it. Using a method is known as calling or invoking a method. To call a method that was named myMethod, you would write:

myMethod();

If the method contained a parameter (eg. the value 10), it would be called like this:

myMethod(10);

The below example shows how to call a method and pass a variable into the method. You do not need to write int inside the brackets where the function is called.

int x = 10;
myMethod(x);

When you call a method you do not need to provide the variable type with the variable that is being passed into the method. If the method myMethod() in the example code above returns a value, then it should be stored in a variable, for example:

int result = myMethod(x);

Here is another example of the applyDamage() method:

using UnityEngine;
using System.Collections;
 
public class hitFromLaserScript: MonoBehaviour {
 
 void Start()
 {
 int x = applyDamage(5, 100);
 print ("Player health: " + x);
 
 }
 
 int applyDamage(int damageAmount, int health)
 {
 return health - damageAmount;
 }
 
}

Variable scope

Now that you are using functions in JavaScript, it is really important to understand variable scope. JavaScript has two variable scopes: global and local.

  • A global variable is a variable which is declared outside a function and its value can be accessed and modified throughout your program
  • A local variable is a variable which is declared inside a function definition. It is created and then destroyed every time the function runs, and cannot be accessed or modified from outside the function.

Make sure that you watch the video on variable scope here to see how it works. Sample code is available for you to try out below.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Variable scope</title>
 <script type="text/javascript">
 
 // A local variable is defined inside a function and can only be used inside a function it's declared in
 // A global variable can be used anywhere in the program
 
 var name = "Smith"; //global variable
 
 function printName(){
 document.write(name + " inside function<br/>");
 // the name variable is being used inside the function
 }
 
 printName(); // this will run the printName function
 
 document.write(name + " outside of function<br/>"); // this uses the name variable outside of the function
 
 function printName2(){
 var name2="Mary"; // name2 is a local variable created inside this function
 document.write(name2 + " inside function<br/>");
 }
 
 printName2(); // this will run the printName2 function
 
 // what will happen when the line of code below runs?
 document.write(name2 + " outside of function<br/>");
 // the statement on the line above will not work because the variable name2 cannot be accessed outside of the function
 // If you go to the JavaScript Console in your browser, you will see an error has been reported when running the code
 // The error will look like: Uncaught ReferenceError: name2 is not defined
 // This error occurs because name2 can only be used by the printName2 function, and not outside the function.
 
 </script>
 
</head>
<body>
 
</body>
</html>

Functions with more than one parameter

In the previous sample code, we looked at how to use a parameter in a function. This sample code shows how to use multiple parameters. Make sure you also watch the video that explains functions and parameters here.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Functions with multiple parameters</title>
 <script type="text/javascript">
 
 // define the function and set the parameters separated by comma
 function addNumbers(num1, num2){
 // function code goes here, eg:
 var answer = num1 + num2;
 document.write(answer + "<br/>");
 }
 
 // call the function three times with different parameters
 addNumbers(2,6);
 addNumbers(3,1);
 addNumbers(30,14);
 // notice that there is a <br/> tag in the function, so a new line will be added each time the function is called
 
 </script>
 
</head>
<body>
 
</body>
</html>

Functions with a parameter

The sample code shows how to make a function which uses a parameter.  A parameter is like a special variable which is used in a function to refer to a piece of data which is provided as input to the function. These pieces of data are also often called arguments.

The code below shows how to use just one argument. If you want to use more than one argument, see the sample code here. You can also watch the video which explains functions and parameters here.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Functions with parameters</title>
 <script type="text/javascript">
 
 /* functions can also use one or more parameters
 a parameter is like a special variable which is used in a function to
 refer to a piece of data which is provided as input to the function. These pieces of
 data are also often called arguments.
 */
 
 // define the function and set the parameter eg. message
 function saymessage(message){
 // function code goes here
 alert(message);
 }
 
 // call the function to be used and provide "Hello world" as an argument to the function.
 saymessage("Hello there");
 </script>
 
</head>
<body>
 
</body>
</html>

Defining and using functions in JavaScript

Want to make your own functions in JavaScript? This tutorial explains how to define and call your own functions in JavaScript. It also explains how to use one or more parameters in your function. You can watch the video below or click here to view it on YouTube.

Functions allow you to write lines of code that can be used again and again in different parts of a program without actually having to write the lines of code several times. You can create a function that runs some lines of code (usually a specific set of instructions) and then ‘call’ that function to be used later on. Have a look at the sample code below.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Functions</title>
 <script type="text/javascript">
 
 // This is how you define a function
 function saymessage(){
 // function code goes here
 // more function code goes here
 // example of simple function code below:
 alert('Hello world');
 }
 
 // this is how you 'call' the function
 saymessage();
 
 //or you can call the function from an event like in a form, in the body section below
 </script>
 
</head>
<body>
 <form>
 <input type="button" value="click me" onclick="saymessage();"/>
 </form>
 
 
</body>
</html>

The sample code below shows how to make a function which uses a parameter.  A parameter is like a special variable which is used in a function to refer to a piece of data which is provided as input to the function. These pieces of data are also often called arguments.

The code below shows how to use just one argument. If you want to use more than one argument, scroll further down the page.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Functions with parameters</title>
 <script type="text/javascript">
 
 /* functions can also use one or more parameters
 a parameter is like a special variable which is used in a function to
 refer to a piece of data which is provided as input to the function. These pieces of
 data are also often called arguments.
 */
 
 // define the function and set the parameter eg. message
 function saymessage(message){
 // function code goes here
 alert(message);
 }
 
 // call the function to be used and provide "Hello world" as an argument to the function.
 saymessage("Hello there");
 </script>
 
</head>
<body>
 
</body>
</html>

This sample code below shows how to use multiple parameters.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Functions with multiple parameters</title>
 <script type="text/javascript">
 
 // define the function and set the parameters separated by comma
 function addNumbers(num1, num2){
 // function code goes here, eg:
 var answer = num1 + num2;
 document.write(answer + "<br/>");
 }
 
 // call the function three times with different parameters
 addNumbers(2,6);
 addNumbers(3,1);
 addNumbers(30,14);
 // notice that there is a <br/> tag in the function, so a new line will be added each time the function is called
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Variable scope