Tag Archives: loops

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#

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:

While loops in PHP

In this tutorial you will learn how to use a while loop in PHP. A while loop‘s syntax is slightly different to a for loop. A while loop will test a condition and will repeat a section of code inside the loop while that test condition evaluates to true. A while loop always tests the condition before running the code inside the loop (if the condition evaluates to true).

Unlike for loops, while loops do not have an inbuilt counter but you can include your own counter variable if you want to use one. While loops and for loops can often be used for the same purpose or to achieve the same goal. However, in different situations, one type of loop may be better than the other. For example, a for loop may be more efficient for going through each element in an array and when written may also express the statement in a clearer way.

Watch the video below and then scroll down to see the sample code for a PHP while loop.

Sample PHP code:

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

PHP Manual references:

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
}

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)

While loops

A while loop basically runs a piece of code while a test condition evaluates to true. A while loop can repeat a set of instructions (code) over and over again until the test condition evaluates to false and the loop breaks. The rest of the program will then continue running.

Watch the video below which explains a few different ways that you can use while loops in a program. You can also view it on YouTube by clicking here.

Take a look at the code below. A counter variable is given an initial value of 1. While the counter variable is less than or equal to 10, a new paragraph of text will display on the screen. The counter will increase by 1 for every iteration of the loop. The web page will display ten paragraphs before the loop ends (once the counter reaches the value of 11), and each paragraph will have the counter number value appended to the end of it.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - While Loops</title>
 <script type="text/javascript">
 
 var counter=1;
 
 while(counter<=10){
 document.write("This is paragraph "+counter+"</p>");
 counter++; // this is equivalent to counter = counter+1
 }
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

In the example below, a string is used instead. The loop checks if the password is correct and then displays a message if it is correct. However, there is a problem with the code below…can you spot it? Scroll down to find out what is wrong with the code.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - While Loops</title>
 <script type="text/javascript">
 
 var password = "potato";
 
 while(password == "potato"){
 document.write("You have entered the correct password.");
 // more code can go here...
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

The problem with the snippet of code above is that the condition for the while loop will always evaluate to true, and so the loop will never stop running! This is called an infinite loop. The password variable is set to “potato” and while the password stored is equal to “potato”, the loop will run again and again. But there is no way to enter a different password…unless we allow for user input!

One way of allowing for user input is to use a JavaScript prompt such as the one used below. This time the while loop is set up a little differently.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - While Loops</title>
 <script type="text/javascript">
 
 var password = prompt("Enter a password");
 
 while(password != "potato"){
 password = prompt("You have entered the wrong password. Try again.");
 }
 
 document.write("You have entered the correct password! Welcome!");
 
 </script>
 
</head>
<body>
 
</body>
</html>

Tip: You can also use the break command to end a loop if a condition has evaluated to true. You could use an if statement inside a while a loop and then use the break; command to break the loop.

break;

Next tutorial: Do..While loops