The differences and similarities between for, while and do…while (AS3)

•27. January, 2009 • 4 Comments

This article is meant for those who attend the class IKT2 at Vågsbygd VGS, yet it is still written in english in case anyone else wants to read this post. I do not claim to be an expert on the subject, yet I will try to describe the differences and similarities between the for-loop, the while-loop and the do…while-loop. I will also comment on the switch-case. Last I’ll briefly go trough break and continue. If anyone has any questions or comments, please write them in english, or they will not be answered.

The first one you learn and the easiest one to use is the while-loop. It is pretty straight forward. It is used to do something (whatever you like) while a statement is true. The syntax of the while-loop is like this:

ActionScript 3 code
1
2
3
4
while(condition)
{
    //Do something
}

The while loop can be used to do something a number of times. For example the next code will trace out every number between 0 and 15 (including 0, not including 15).

ActionScript 3 code
1
2
3
4
5
6
var i:Number = 0;
while(i < 15)
{
    trace(i);
    i++;
}

However, when itterating through something like this it is much more common to use the for-loop. In cases like this, there is no difference except the syntax. This example does exactly the same as the previous one, only it uses the for-loop instead of the while-loop.

ActionScript 3 code
1
2
3
4
for(var i:Number = 0; i < 15; i++)
{
    trace(i);
}

As you can see, this is done with a lot less code, yet the result is exactly the same. The syntax of the for-loop is as following:

ActionScript 3 code
1
2
3
4
for(initilization; condition; incrementation)
{
    //Do something
}

I realize that the name “incrementation” is not correct, yet it’s the best I can come up with. The point is that you do something several times. I usually use the for-loop instead of the while-loop, except when it’s something I can’t count. For example if I’m reading a file, I use a while loop as long as there’s still something left to read. Other than that I use the for-loop.

Occationally you want to make shure something happens at least once. In that case you’ll want to use the do…while-loop. A good example of this is if you wan’t to calculate a random number between 1 and 6, yet you don’t want it to be 5 or 3. I would do that like:

ActionScript 3 code
1
2
3
4
5
6
var rndNum:Number;
do
{
    rndNum = Math.floor(Math.random() * 6) + 1;
}
while(rndNum != 5 && rndNum != 3);

This first creates an empty variable called rndNum, then it keeps generating a new random number until rndNum is not equal to rndNum 5 or 3. Here I use the while-loop because I don’t know how many times I need to recalculate rndNum. It might be none or it might be a hundred.

Last I’d like to give a simple example of the switch-case condition. The switch-case is only used for special cases. I only use the switch-case when I KNOW that the input is going to be one in a range of others. For instance, if I asked you for a number between 1 and 10, and would treat you differently based on your result, I’d use the switch-case. I better example is a simple program where the user is asked to enter a number (a choice) between one and three. This could be used for a menu (press 1 to save, press 2 to load and press 3 to exit). For example like this:

ActionScript 3 code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var input:Number = Number(inputField.text);
switch(input)
{
    case 1:
        //Save
        break;
    case 2:
        //Load
        break;
    case 3:
        //Exit
        break;
    default:
        //Display "incorrect input"
        break;
}

Thats basically it about the switch-case.

Two more things that is needed to be fully able to use loops and switch-case statements is the understanding of break and continue. The break is used to exit a loop. For instance the next loop will only trace out the numbers 0 to 10 (including 10), even though the loop itself looks like it is to trace out 11, 12, 13 and 14 as well.

ActionScript 3 code
1
2
3
4
5
6
7
8
for(var i:Number = 0; i < 15; i++)
{
    trace(i);
    if(i == 10)
    {
        break;
    }
}

There actually isn’t anything more to it. All the break does is exit the loop it’s in. One thing worth mentioning though is that the switch-case is also treated as a loop in that aspect. That’s why we always use break before the next case, to make shure that when it has done what it was meant to, it exits the switch-case.

The last topic is the continue statement. It is used to skip the current loop-run. This next code will trace out every number from 0 to (including) 14 exept the number 5.

ActionScript 3 code
1
2
3
4
5
6
7
8
for(var i:Number = 0; i < 15; i++)
{
    if(i == 5)
    {
        continue;
    }
    trace(i);
}

The continue is hard to explain, and from my experiece rarely used, yet it might be useful to know. However, you should be careful when using it with the while-loop.

That’s about it for this time. If you have any questions, please leave me a comment.

Special thanks to:

  • Eirik Løhaugen Fjærbu
  • Johanne Rasmussen

Kung Fu Panda

•11. September, 2008 • Leave a Comment

I just saw the movie kung fu panda, and I don’t think I’ve ever laughed that much during a movie. Some of the scenes where just amazingly amazing. I just loved it. There where two guys seeing that film with me that day, and all of us was sitting in my bed (i don’t have a couch in my room or anything like that, so I put a lot of pillars in my bed and uses it as a couch) and i think at one moment the whole bed was jumping up and down for several minutes! If you haven’t seen that film you definitely have to go and see it. Really, you have to! If you don’t, it’s really a loss. So now you’re warned. GO SEE THAT MOVIE! AND FOR YOUR OWN SAKE SEE IT IN BETTER QUALITY THAN I DID. (I never should have accepted that bad download a friend of mine found). Anyway. Go see it!

Later.

Blog at alxandr.mydyn.net

•3. September, 2008 • Leave a Comment

Ok, I’ve figured I’ll start creating a blog-like system over at alxandr.mydyn.net. It won’t be just a blog, and I’m not shure how I’ll do it yet, but I’ll figure that out in time. I’ll probably also have a tutorial-section to create tutorials in web-design and programming in several languages. When it’s done I think I’m moving this blog over to that page. Also, I’m thinking about buying a domain once I’m old enough (18). It’s only about a month and a half or so at the writing time. And I also think about switching host, but not shure about that. I’ll let you all know if anything major happens.

 

Later.

Xeoncross like never before

•24. August, 2008 • 1 Comment

Today I’ve found perfectionism. I’ve found the most beautiful ajax navigation-system I’ve ever seen before. I’ve found a page that fades in and out, and scrolls you to all the right places smoother than the skin of a newborn baby. Today I’ve found peace, ’cause I now know that the web is in good hands. If you don’t believe me, go see for yourself. Check out the all new Xeoncross.com. I don’t have any more to say. I’m just stunned. You gott’a do the talking at this one folks.

Later.

JS/XHTML popups like never before!

•9. August, 2008 • Leave a Comment

I’ve just finished creating a popup class for alxandr.mydyn.net and it’s by far the best popup-class I’ve ever made. Each popup is a div that’s assigned to the page, they all have close-buttons, they all are movable, and when you select one of them it comes on top of the other ones. Take a look at this imake:

alxandr.mydyn.net popup

alxandr.mydyn.net popup

The code for this baby looks like this:

window.popups = new Array();
window.availiblePopup = function()
{
	for(var i = 0; i < window.popups.length; i++)
	{
		if(window.popups[i].popUp.get('opacity') == 0)
		{
			return window.popups[i];
		}
	}
	return new popup();
}
window.highestPopup = 1;
window.popup = new Class({
	Implements: Events,
	initialize: function()
	{
		this.popUp = new Element('div', {
			styles: {
				position: 'absolute',
				border: '5px solid #001366',
				padding: 0,
				'background-color': '#000'
			},
			opacity: 0
		});
		var topTable = new Element('table', {
			cellpaddin: 0,
			cellspacing: 0
		});
		this.popUp.grab(topTable);
		var titleRow = $(topTable.insertRow(0));
		var titleCell = $(titleRow.insertCell(0));
		titleCell.set('styles', {
			'text-align': 'left',
			padding: '2px',
			'text-transform': 'uppercase',
			'background-color': '#001366',
			color: '#ff7800'
		});
		var titleTable = new Element('table', {
			styles: {
				width: '100%'
			}
		});
		titleCell.grab(titleTable);
		var titleTable_row = $(titleTable.insertRow(0));
		this.titleView = $(titleTable_row.insertCell(0));
		this.popUp.addEvent('mousedown', function() {
			this.set('styles', {
				'z-index': window.highestPopup++
			});
		});
		var closerCell = $(titleTable_row.insertCell(1));
		closerCell.set('styles', {
			'text-align': 'right'
		});
		var textRow = $(topTable.insertRow(1));
		this.textView = $(textRow.insertCell(0));
		this.textView.set('styles', {
			padding: '20px'
		});
		this.closer = new Element('span', {
			text: 'X',
			styles: {
				color: '#fff',
				cursor: 'pointer'
			},
			events: {
				mouseover: function() {
					this.set('styles', {
						color: "#f00"
					});
				},
				mouseleave: function() {
					this.set('styles', {
						color: "#fff"
					});
				},
				click: function() {
					this.retrieve('popup').hide();
				}
			}
		});
		closerCell.grab(this.closer);
		this.closer.store('popup', this);
		this.drager = new Drag(this.popUp, {
			handle: this.titleView
		});
		this.popUp.inject(document.body);
		window.popups.push(this);
	},
	show: function(text, title)
	{
		this.titleView.set('text', title);
		this.textView.empty();
		this.textView.set('text', text);
		return this.trueShow();
	},
	showHtml: function(html, title)
	{
		this.titleView.set('text', title);
		this.textView.set('html', text);
		return this.trueShow();
	},
	showPredefined: function(title)
	{
		this.titleView.set('text', title);
		return this.trueShow();
	},
	predefine: function(item)
	{
		this.textView.empty();
		this.textView.grab(item);
		return this;
	},
	trueShow: function()
	{
		this.popUp.set('styles', {
			'z-index': window.highestPopup++
		});
		if(this.popUp.get('opacity') == 0)
		{
			this.resetPossition();
			this.popUp.fade(0.85);
		}
		return this;
	},
	close: function()
	{
		this.popUp.fade('out');
		this.exit();
		return this;
	},
	hide: function()
	{
		return this.close();
	},
	flashOut: function()
	{
		this.popUp.tween('border', '5px solid #440', '5px solid #001366');
		this.hide.delay(1000, this);
		return this;
	},
	flash: function(text, title, func, resetPos)
	{
		this.remove();
		this.show(text, title);
		if(resetPos)
		{
			this.resetPossition();
		}
		this.flashOut.delay(800, this);
		if(func && $type(func) == "function")
		{
			func.delay(3000);
		}
		return this;
	},
	resetPossition: function()
	{
		this.popUp.set('styles', {
			top: (window.getSize().y / 2) - (this.popUp.getSize().y / 2) + window.getScroll().y,
			left: (window.getSize().x / 2) - (this.popUp.getSize().x / 2) + window.getScroll().x
		});
		return this;
	},
	remove: function()
	{
		this.popUp.set('opacity', 0);
		this.exit();
		return this;
	},
	exit: function()
	{
		this.onExit();
	},
	onExit: function()
	{
		this.fireEvent('exit');
	}
});

I know, I know. It’s ugly. But I’ll clean up the code a bit later. As of now you who might want to use it; go ahead. It’s getting to late for me to describe anything except that you’ll need mootools in order for this code to work.

Later

The Codeigniter framework realy rocks!

•9. August, 2008 • 1 Comment

I’ve just tried out the codeigniter framework and I’ve just fallen in love with it. Totally fallen in love. It’s just amazing! I can’t figure out how the url works, but it just does, and I don’t care about how anymore. I’ve started using it at my homepage (alxandr.mydyn.net), and I’m going to explore it as much as I can before school starts again. You’ll probably see some action on my homepage over the next week if you pay attention to it. As of now a small “About”-page has been setup. But more is to come, you can be sure about that. After some time I’ll probably also move this blog over to that page. Creating a blog from scratch is not somthing that is done overnight, but it’s something that I want to do. I don’t know when, I don’t even know if I’ll ever be finished, but I have to start somewhere. And I know some guys I might ask for help when I might need that. But I need to get back to my work at my homepage.

Later.

varebilspesialisten.no is finally finished!

•6. August, 2008 • Leave a Comment

So at last I’ve finished varebilspesialisten.no (or at least I think it’s finished, and that’s a start, isn’t it?). I have no idea of how long I’ve been working on this project now. When it’s all up and on line I’ll give y’all the address, but you’ll probably won’t be able to understand any of it anyway ’cause it’s in Norwegian. Anyway, it’s passed midnight here so I think I’ll get to bed as fast as possible. Long day tomorrow. This’ll be the first day in many that I’m in bed before 2am. Anyway, once everything is up and running I’ll get to my homepage. Just need to figure out what I want to do with it first. And maybe I want some free time after varebilspesialisten.no. I’ll see about that later. I’ll keep you posted.

Later

alxandr.mydyn.net is up and running again

•6. August, 2008 • Leave a Comment

My home page alxandr.mydyn.net is somewhat up and running again. As of now the page is only saying “Under constructions…” and I know that isn’t much thrilling at all, but I’ll change that after some time. Though the layout has been made, and I’ve made a couple of classes (php) witch I make use of. The menu has also been javascripted. It’s not much yet, but it’s a start. Before I continue much further I need to figure out what I actually am to do with the page after all. I was wondering if I was to integrate the blog in the page itself, but I’ll see about that later. Feel free to take a look over at alxandr.mydyn.net.

Later

The design of varebilspesialisten.no

•3. August, 2008 • Leave a Comment

As of now Varebilspesialisten.no looks like this:

Varebilspesialisten.no's design

Varebilspesialisten.no's design

The page is more or less compleatly AJAX made and all effects is made with javascript and not with flash. I’ve used the mootools-engine quiet much.

Varebilspesialisten.no is about finished

•3. August, 2008 • Leave a Comment

After a few months working on varebilspeisalisten.no I’m feeling that it’s about finished now. I have a few more things to make sure works as it is supposed to. As of now I’ve made a all javascript and php environment with a simple to use interface and a nice looking design. The page has some nice features with for example the image-uploader. Once things is finished I’ll start publishing peaces of the code for everyone to use as they see fit.