Tag Archives: loop

Foreach loops in C#

This tutorial explains how to use the foreach loop to go through each element in an array. A foreach loop is simpler and easier to use than a for loop if you want to loop through each and every element in an array. There is no need to use a counter, specify an increment, or a condition. The foreach loop will simply loop through every element in the array.

Foreach loops are written in a way that is easy to understand, for example:

foreach (string item in itemsList){
   Console.WriteLine(item);
}

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

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an array of string type
      string[] names = {"Jim","Kate","Sam","Sally"};

      // Store length of names array in variable
      int arrayLength = names.Length;

      // Go through each name in names array and display on new line
      foreach (string name in names) {
        Console.WriteLine(name);
      }
      // Wait for user input before quitting program
      Console.ReadLine();
    }
  }
}

Next tutorial: Methods

Do while loops in C#

A do while loop is a type of loop which repeats code while a certain condition evaluates to true. However, unlike a while loop which tests the condition first, a do while loop tests the condition after running instructions inside the loop. This means that the code inside the loop will always run at least once even if the condition evaluates to false. This is an example of post-test repetition.

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

Sample code

Take a look at the sample code below. The counter is set to 99 and the condition being tested is counter < 10. However, the code inside the loop runs the first time even though the condition evaluates to false because a do while loop runs the code inside the loop before testing the condition (meaning that the instructions inside the loop will always run at least once).

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int counter = 99;
      do
      {
        Console.WriteLine("Counter is: " + counter);
        counter++;
      } while(counter < 10);
      Console.ReadLine();
    }
  }

}

Next tutorial: Arrays in C#

While loops in C#

This tutorial explains how to write a while loop in the C# language. A while loop is used to repeat a section of code while a condition evaluates to true. For example, keep asking for a password while the password being entered is wrong, or keep displaying a message a number is less than a certain number, or keep moving a character in a game to the right side of the screen while the right arrow key is being pressed on the keyboard.

A while loop is a pre-test loop meaning it tests a condition before running code inside the loop. If the condition being tested never evaluates to true then the loop will not run. After each iteration of a loop, if the condition being tested evaluates to false then the loop will exit and the rest of the program will run. It is important that you allow loops to eventually end by specifying a condition that will eventually evaluate to false, otherwise you will end up having an ‘infinite loop’ causing your program to crash.

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

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int counter = 0;
      while (counter < 10)
      {
        Console.WriteLine("The counter is " + counter);
        counter--;
      }
      Console.ReadLine();
    }
  }

}

Next tutorial: For loops in C#

Create a looping walk cycle animation in Adobe Flash / Animate

This tutorial explains how to create a looping walk cycle animation in Adobe Flash (Adobe Animate) like the one shown below.

WalkCycle

You can use the same technique for other types of internal animated loops. Watch the video below to find out how to do this using either the Adobe Flash or Adobe Animate software.

In this video I used the sprite sheet by soldiern at http://soldiern.deviantart.com/art/Sub-Zero-Sprite-Sheet-V2-210769129 (using Creative Commons CC3.0 license – https://creativecommons.org/licenses/by-sa/3.0/ ).

For loops in C#

For loops are used to repeat code a certain number of times. For example, a for loop could be used to repeat an instruction 10 times. For loops are much more useful than that though. For example, they can be used to process items in a list one-by-one (we will learn how to do that later).

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

The for loop is a little more complex than the while loop but at its simplest level it is very easy to set up. The syntax looks like this:

for(<initialise counter>;<condition>;<increment the counter>)
{
// do something
}

Semi-colons separate three important components of the for loop inside the ( and ) brackets. The first part is where a counter is initialised, for example int i=0. The second part is where the condition is specified, for example i<10. The third part is how much to increment the counter by each time the loop runs (each iteration), for example i++ would increment the counter by 1.

For loops are great for using as counters to repeat a section of code a certain amount of times. They are also great for repeating operations on each item in an array (looping through an array) or each character in a string. Below is an example of a for loop.

Sample code

This for loop will start with an integer value of 0 and then keep increasing the number by 1 and displaying its value until the value is no longer less than 10.

using System;

namespace MyApp
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      for (int i = 0; i < 10; i++) {
        Console.WriteLine (i);
      }
    }
  }
}

And another example shown below will repeat the word “Hello” 10 times.

using System;

namespace MyApp
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      for (int i = 0; i < 10; i++) {
        Console.WriteLine ("Hello");
      }
    }
  }
}

While loops in C#

While loops are used to repeat a section of code while a specified condition evaluates to true. For example, a user could keep being asked to enter a password while the password they are providing is incorrect. When the password they provide is correct, the loop will end.

The video below explains how to use while loops in C#. You can also scroll down to see the sample code.

Sample code

The sample C# code for a solution and project called MyApp is shown below. In this program, a variable called myNumber is created which is initially given an integer value of 1.

A while loop is created which checks if the value of myNumber is less than 10. While the value of myNumber is less than 10, the value is displayed to the user and then increased by 1, each time the loop repeats. Each repetition of a loop is called an iteration. Try the code below in your own program.

using System;

namespace MyApp
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      Console.WriteLine ("Hello World!");
      int myNumber = 1;
      while(myNumber < 10)
      {
        Console.WriteLine(x);
        myNumber++;
      }
      Console.ReadLine ();
    }
  }
}

Next tutorial: For loops

Foreach loops in PHP

This tutorial explains how to use the foreach loop to loop through each item (element) in an array. The foreach loop can only be used on arrays and objects in PHP. On each iteration of a foreach loop, the value of the current element being accessed is assigned to $value. Foreach loops can be used on both regular arrays and associative arrays.

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

The sample PHP code below shows how to use a foreach loop for both regular arrays and associative arrays:

<?php
  $normal_array = array("Mary","Bob","Joe","Tim");
  $assoc_array = array("Sarah"=>25,"Kim"=>18,"Alice"=>32,"Alan"=>17);

  // using a foreach loop on a regular array:
  foreach($normal_array as $value){
    echo "Name: $value</br>";
  }

  // using a foreach loop on an associative array:
  foreach($assoc_array as $key => $value){
    echo "$key's age is $value.</br>";
  }
?>

Looping through arrays with PHP

This tutorial explains how to loop through the elements in a PHP array. This works by using a for loop that will access elements in the array by their index. For each iteration of the loop, a different index will be accessed. You will also see how count() is used to count the number of elements in an array. The process for looping through each character in a string variable is basically the same as looping through each element in an array, as a string is basically an array of characters.

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

Sample PHP code to loop through each string element in an array and echo each element’s value on a new line:

<?php
  // create a new array
  $myArray = array("a","b","c");

  // loop through each element in the array
  // count will count all elements in an array
  for($i=0;$i<count($myArray);$i++){
    echo $myArray[$i] , "</br>";
  }
?>

Sample code to loop through an array and modify the value of each element in the array:

<?php
  // create a new array
  $myArray = array(1,2,3,4,5);

  // loop through each element in the array
  // count will count all elements in an array
  for($i=0;$i<count($myArray);$i++){
    // this will multiply each integer value by 2
    $myArray[$i] = $myArray[$i] * 2;
    echo $myArray[$i] , "</br>";
  }
?>

Break and continue in PHP

In this tutorial you will learn how to break a loop (stop a loop from running when a certain condition is met) and continue (skip an iteration of a loop). A for loop will be used for the example shown in this tutorial.

There may be situations where you may wish to use the break statement if you want a loop to stop running if a condition from an if statement inside the loop evaluates to true. Similarly, you may also want to skip an iteration of a loop using the continue statement.

Watch the video below and then scroll down to see the examples of break and continue being used in PHP code.

Sample PHP code for breaking a loop:

1
2
3
4
5
6
7
8
<?php
 for($i=0; $i<10; $i++){
 if($i==8){
 break;
 }
 echo $i , '</br>';
 }
?>

Sample code for using continue to skip an iteration of a loop:

1
2
3
4
5
6
7
8
<?php
 for($i=0;$i<10;$i++){
 if($i==5){
 continue;
 }
 echo $i , '</br>';
 }
?>

Sample code for using continue to skip any even numbers in a for loop:

1
2
3
4
5
6
7
8
<?php
 for($i=0;$i<10;$i++){
 if($i%2==0){
 continue;
 }
 echo $i , '</br>';
 }
?>

Sample code for using continue to skip any odd numbers in a for loop:

1
2
3
4
5
6
7
8
<?php
 for($i=0;$i<10;$i++){
 if($i%2!=0){
 continue;
 }
 echo $i , '</br>';
 }
?>

PHP Manual references:

Do while loops in PHP

In the previous tutorial, we looked at how while loops can be used to test a condition before running a loop. While that test condition evaluates to true, the loop will continue running. The while loop tests a condition before the loop runs and will not run the loop if the condition evaluates to false.

On the other hand, do while loops check the condition after the loop has already been executed. The loop will always run at least once even if the condition evaluates to false. The do while loop syntax is split into two parts: the ‘do‘ part and the ‘while‘ part. The ‘do‘ part tells the loop what code to run and the ‘while‘ part specifies the condition that will be tested. The ‘while‘ part comes after the ‘do‘ part. Do while loops do not have an in-built counter but you can include a counter in the loop.

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

Sample PHP code:

1
2
3
4
5
6
7
8
<?php
 $counter = 0;
 do{
 echo $counter , "</br>";
 $counter++;
 }
 while($counter < 10);
?>

PHP Manual references:

Looping through arrays (and strings)

By now you should be familiar with both arrays and for loops. In this tutorial we are going to use both of these coding concepts. We can easily use a for loop to loop through each element in an array.

Watch the video below and then scroll down the page to access the code which you can use yourself.

In the sample code below, we will loop through every member of the Simpsons family and print each family member on a new line. Each family member is an element in simpsonsArray and the arrayLength variable stores the length of the simpsonsArray (the number of elements in the array) as a number value. There are five elements in the array so there will be five iterations of this for loop.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - For Loops</title>
 <script type="text/javascript">
 
 // This example shows how to loop through an array
 var simpsonsArray = ["Homer","Marge","Bart","Lisa","Maggie"]; // this is the array
 var arrayLength = simpsonsArray.length; // this variable stores length of the array (no. of elements in array)
 for (i = 0; i < arrayLength; i++) {
 document.write(simpsonsArray[i],"</br>"); // this will show each family member on a new line
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

We can also loop through every character in a string variable too. The code below loops through every letter in the word variable and displays each letter on a new line.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - For Loops</title>
 <script type="text/javascript">
 
 // This example shows how to loop through each character in a string
 var word = "Hello"; // this is the string variable
 var wordLength = word.length; // we use the length method to store the length of the word string in a variable
 for (i = 0; i < wordLength; i++) {
 document.write(word[i],"</br>"); // this will show each letter of the word on a new line
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Objects, properties and methods

Do..while Loops

Unlike the regular while loop, a do..while loop will run once first and then check the condition before it runs again. The loop will always run at least once, even if the condition evaluates to false. This is an example of a post-test loop structure. On the other hand, a regular while loop that only runs while a condition evaluates to true is an example of a pre-test loop structure. Watch the video below, then scroll down the page to see the sample code explained.

Have  a look at the sample code below for the do..while loop (post-test loop structure).

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Do While Loops</title>
 <script type="text/javascript">
 
 // Unlike the regular WHILE loop, a DO WHILE loop will run once first and then check the condition
 // before it runs again. The loop will always run at least once, even if the condition evaluates to false.
 // This is an example of a post-test loop structure.
 
 var counter=1;
 
 do{
 document.write("This is line "+counter+"<br/>");
 counter++; //increase counter value by 1
 }while(counter<=10);
 
 // Change the counter to 11 and run the program again. What happens?
 // One line will still print because it runs the loop once before checking the condition.
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: For loops