Tag Archives: while

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#

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

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:

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
}

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

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