Tag Archives: for

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

For loops in C#

In this tutorial you will learn how to use the for loop to repeat sections of code in the C# language. For loops are useful for when you want to repeat code a certain number of times. They are also very useful for efficiently working through all the elements in an array or going through each character in a string. For loops have a built in counter, condition, and increment. Watch the video below and then scroll down for the sample code.

Sample code

Example 1 – using for loop as simple simple counted loop

using System;

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

}

Example 2 – using for loop to go through each character in string

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      string word = "dog";
      for (int i = 0; i < word.Length; i++)
      {
        if (word[i] == 'a')
        {
          Console.WriteLine("This word contains the letter a");
        }
      }
      Console.ReadLine();
    }
  }

}

Next tutorial: Do while loops in C#

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");
      }
    }
  }
}

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>";
  }
?>

For loops in PHP

This video tutorial explains how to use for loops to repeat code using a counter. For loops have many uses such as processing arrays and strings but in this tutorial we will just look at how to use a for loop as a counted loop.

A for loop is made up of three parts:

  • counter – which is initialised
  • condition – a condition that must evaluate to true for the loop to run its code, and is tested in each iteration of the loop
  • increment – how much the counter increases by in each iteration of the loop

For example, a for loop may contain a counter which starts at 0, and the condition in the loop is for the loop to repeat for as long as the counter is less than 50, and the increment is 1. For loops are very useful for repeating code a specified number of times, going through all the characters in a string or elements in an array and using the loop counter to check the characters in a string or elements in an array, one by one – this can be achieved by using the counter in each iteration of the loop to represent the index of the character in a string or element in an array being accessed in each iteration of the loop.

This example would look like:

for($i = 0; $i < 50; $i++){
  // code inside the loop goes here
}

In the example above a counter called $i is used. It is quite common for these loops to use a counter called i but you can call the counter whatever you like (following the same rules as any other variable). You can place for loops within for loops. If you do that, make sure you give each loop a different name for its counter. The example above also increments the counter by 1 ($i++) in each iteration of the loop.

The video below shows the steps involved in creating and using a for loop. Watch the video below and then scroll down for the sample code.

Sample PHP code:

<?php
 for($i=10;$i > 5;$i--){
 echo("This is iteration #" . $i . "</br>");
 }
?>

PHP Manual references:

Loops (iteration) in C#

There are two main types of loops you can use in C# to repeat sections of code. These are called the while loop and for loop.

while loop

The while loop is the easiest type of loop to use for repetition of code. The basic syntax is as follows:

while(<condition>)
{
// do something
}

It looks very similar to an if statement. However, an if statement only runs the code it contains once. A while loop will run the code that it contains over and over again until the specified condition evaluates to false. Any code inside the { and } brackets will run inside the loop.

Here is an example of a while loop in the C# language:

int count = 0;
 
while(count <10)
{
 count++;
}
print(count);

In the example above, the count variable is initially set to 0. The loop will check if the count variable is less than 10. If it is not less than 10, it will add 1 to the count variable. This will keep repeating until the condition evaluates to false when the count variable’s value is no longer less than 10. When this occurs, the loop will end and the value of the count variable will be displayed (on the last line of the code which is outside of the loop).

It is important that a condition be specified that will allow the loop to end, otherwise the loop will never end! This is known as an infinite loop.

for loop

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.

for(int i=0; i <10; i++)
{
 print(i);
 // the value of i will be displayed for each iteration of the loop
}

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

For Loops

A for loop is a loop that can run a set number of times. For example, you could use a for loop with a counter to repeat a set of instructions 10 times. Or you could use a for loop to cycle through every letter in a string or every element in an array (see the next tutorial). Every repetition of the loop is called an iteration.

Watch the video below and then scroll down to view the code.

Take a look at the sample code below which shows how to use a counter in a for loop.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - For Loops</title>
 <script type="text/javascript">
 
 // A FOR loop has three parameters separated by a semi-colon
 // The first parameter tells JavaScript where to start counting (eg. 0)
 // The second parameter is when to end the loop (eg. when the counter is no longer less than 10)
 // The last parameter is how much to increment the counter by (eg. i++ would increment by 1 and i=i+3 would increment by 3)
 
 for(i=0;i<10;i++){
 // in this example, the counter i starts at 0 and finishes at 10
 // the counter goes up by 1 for every iteration of the loop
 // While the counter is less than 10, the following line of code inside the loop will run:
 document.write("This is line "+i+"<br/>"); 
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Looping through arrays (and strings)