Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Introducing loops

Teaches you the loops in JavaScript. Each loop has its prototype and a simple example showing you how to use it.

On Tuesday, April 6th 2004 at 07:11 PM
By Andrew Pociu (View Profile)
****-   (Rated 4 with 11 votes)
Contextual Ads
More JavaScript Resources
Advertisement

Loops



You will not believe how important loops are in programming. Loops help a program decide what to do. From the simplest thing that may sound like “While the visitor visits the website between 7AM and 10AM say ’Good morning’” to “If browser is Internet Explorer use x function, if browser is Firefox use y function”.
Now, an example more suitable for JavaScript will be choosing between two different types of scripts, one for Internet Explorer browser and one for Netscape, because of some incompatibility between the two.
No matter where, loops are frequently used in programming. There are several types of loops and you will learn them all by reading the below lessons.


<h1>if</h1>
Probably the most basic loop. The prototype for ‘if’ is:

if (condition)
{
    [do stuff]
}



The above code translated in human language it sounds like this “If the condition is true ‘do stuff’, if not don’t ‘do stuff’”.

Pretty simple… now let’s see a real example:


var x = 0;
if (x == 0)
{
document.write(“X is 0”);
}



If the variable ‘x’ wouldn’t be equal to 0, the if expression would return false, and therefore nothing would be done.
But because x equals to 0, the “if (x=0)” statement returns true, and the code between ‘{‘ and ‘}’ is executed.


<h1>if ... else</h1>
We can choose to execute some other code if the condition returns false. The prototype for if … else is:

if (condition)
{
[do stuff];
}
else
{
[do something else]
}



The above code says “If condition is true, do stuff, if the condition isn’t true, do something else”. We can use this in real life examples, like “If it’s early, I will watch a movie, else, if it’s late, I will go to sleep”.


var x = 0;
if (x == 0)
{
document.write(“X is 0”);
}
else
{
document.write(“X is not 0”);
}



if ... else if


What if you want to check if ‘x’ is 0, 1 or 2?


var x = 1;
if (x == 0)
{
document.write(“X is 0”);
}
else if (x == 1)
{
document.write(“X is 1”);
}
else if (x == 2)
{
document.write(“X is 2”);
}
else
{
document.write(“X has some other value”);
}



If ‘x’ is 0, 1 or 2, there will be a string displaying that, else, there displayed string will be “X has some other value”.
You can see that the first condition is an usual one, “if (x = 0)”. Then it comes an “else if” expression, that acts just like an usual if. The third condition is an “else if” condition too. Till now, if ‘x’ isn’t 0, 1 or 2, we take only one decision, the last one, called ‘else’. If none of the above conditions was true, we have this last “else” condition.
If we declared “var x = 12” at the beginning of the script, the last condition would have been executed, that prints “X has some other value” in the browser. But because we set ‘x’ to 1, the second condition is executed.

for


With this loop, a piece of code can loop as many times as counted by the loop. Below is the prototype for the ‘for’ loop.


for ([initialization]; [condition]; [loop])
{
    [do_stuff];
}



And here is a simple example for you to understand how the ‘for’ loop works:


for (var x = 0; x < 6; ++x)
{
     document.write(x + “ ”);
}



This loop will display all numbers from 0 to 5, separated by a space. Why? First, we directly initialize a variable, “x = 0”. Of course we could initialized it earlier like this:


var x = 0;
for (; x < 6; ++x)



As you saw, we still need to specify the semicolon, even if the element is missing. By the way, all the elements between ‘[‘ and ‘]’ in the prototype are optional, but if you omit them, you must still keep the semicolon, like this:


for (;;)



After the variable was initialized, we verify if the number it holds is smaller than 6, using the ‘<’ operator. If the number is smaller, we increment it by one using “++x”. Then the code starts. It uses the “document.write” to display the value the variable holds. First time, the number displayed is 0. After this, the loop continues and x is incremented by 1, and 0+1 results in 1. In the third loop, the number is again incremented by one, 1+1 turning into 2. This stops at the loop number 6, when variable x holds value 5. At the next loop, when it reaches “x < 6”, the loop returns “false” because x is 6 at that time. Therefore, the loop stops.

You can change the value at which the loop stops to any number you like. Set it to 1000 for example:



for (var x = 0; x < 1000; ++x)



Your computer may lag a bit if you have a weak processor.

while


The “while” loop is somehow similar to the “for” loop. Let’s see how the prototype looks…


while([condition])
{
[do_stuff];
}



And let’s see a short example, and comment it.


var i = 0;
var x = true;
while(x)
{
i++;
document.write(" " + i);
   if
   (i == 20)
   {
      x = false;
   }
}



First we initialize two variables. First, ‘i’ to the integer 0, and second, ‘x’ to the boolean value true.
The while loop is somehow simpler than the ‘for’ loop because it executes only while a condition is true. Here the condition is ‘x’. If x is true, the loop will continue, till ‘x’ will turn out to be false. If x will never change to true, the script will continue to write the current number in the browser to infinite (which is bad). But we set an ‘if’ loop inside the ‘while’ loop. Every time the ‘while’ loop executes, the ‘if’ loop executes also. The ‘if’ loops checks if ‘i’ is equal to 20, and when it reaches this value, it sets the variable ‘x’ to false, therefore stopping the ‘while’ loop. The variable ‘i’ is incremented inside the ‘while’ loop so it can reach 20 and trigger the ‘if’ loop.

In this short lesson, you learned how the ‘while’ loop works, but you also learned how a loop can be used inside another loop.

do... while


The ‘do… while’ loop is identical to the ‘while’ loop with one small exception: it executes at least once. That’s because the condition is verified after the script looped once.


do
{
[do_stuff];
}
while([condition])


Our previous script, with the variable ‘x’ set to false from the beginning, will still execute once, using a “do… while” loop because the condition is verified after the first loop. Therefore, the following script will display “1” in the browser.

var i = 0;
var x = false;
do
{
i++;
document.write(" " + i);
if
(i == 20)
{
x = false;
}
}
while(x);

There are many more to say about loops and lots of examples to give.
Go google
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by aykut on Thursday, June 3rd 2004 at 10:30 PM

in if conditions;

must be like this "if (x==0)" not "if (x=0)"

by Andrei Pociu on Friday, June 4th 2004 at 04:04 AM

Sorry, that was one hell of a common, simple mistake to do.

by kim on Sunday, September 12th 2004 at 08:21 AM

please give me a typical use of a "do-while" loop....... and its significant difference with the "while" loop.

by Andrei Pociu on Sunday, September 12th 2004 at 08:55 AM

The significant difference is, as I stated in the tutorial, that no matter what the condition returns (true or false), it executes at least once, because it checks the condition after.

This loop isn't used very often. Usually do...while loops are used to perform array operations.

One example of typical use of the do...while loop can be found here:

<a href="http://academ.hvcc.edu/~kantopet/javascript/index.php?page=js+iteratives&parent=js+statements&printme=true">http://academ.hvcc.edu/~kantopet/javascript/index.php?page=js+iteratives&parent=js+statements&printme=true</a>

Where it says:

A more practical use for this loop might be to check whether something has a value. For instance, you could walk an array as long as you keep finding values.

var x = 0;
do {
if (aName[x]) {
bName[x] = someProc(aName[x]);
}
x++;
}
while (aName[x]);

In the preceeding example, we take advantage of the fact that non-existent value return false. This example assumes all the array elements are contiguous, since it will stop executing with the first empty array element it finds.

by Imran Khan on Wednesday, December 22nd 2004 at 03:50 AM

try to simplify examples for while nd do while loops. thnkx

by Imran Khan on Wednesday, December 22nd 2004 at 03:53 AM

Although these are simple yet not for the bigners

by AnanthaKumar on Sunday, August 31st 2008 at 09:08 AM

dear friend,I'd like to bring it to ur kind notice, that,
if, if-else, and if-else if
are all not loops, but control structures.
There is no iteration, or continued re-execution of same set of codes here.


for, while, and do-while are loops, coz there's iteration.
kindly correct.

by AnanthaKumar on Sunday, August 31st 2008 at 09:11 AM

Decision making and branching statements are:
if, if-else, if-else if

Decision making and looping statements are:
for, while,

by misbah akram on Friday, March 26th 2010 at 04:17 AM

plz tell the main difference b/w these loops and also tell on which conditions a particular loop is applied


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs JavaScript Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Sponsors
Discover Geekpedia

Other Resources