For Loops For Beginners

Programming HOW TOs and in-depth guides for programmers of all levels. Programming is an essential skill for hackers, so start learning today!
Post Reply
User avatar
Aiden
Administrator
Posts: 1080
Joined: Tue Oct 31, 2006 11:11 pm
Location: /usr/bin/perl

For Loops For Beginners

Post by Aiden » Sat Oct 03, 2009 10:45 pm

This is a tutorial I wrote for a friend that missed this day in class. However, I would really like to expand upon it in the future, and ideally write a whole book teaching a language. For now though, here is an introduction to using for loops.

For Loops

Note: The example code I use below is Java. However, the only part that is Java is the commands inside the for loop. The actual format of the for loop can be expanded to many other languages where it is the same, such as C#, C++, C, Perl, and PHP.

For loops are used to perform a task a set amount of times. Commonly, this number of times is based off the number of elements in an array, or just anything you need to do over and over for multiple pieces of data.

The syntax for a for loop is:

Code: Select all

for (int counter = 1; counter <= 10; counter++) {
	Console.WriteLine(counter);
}
The first line in the above code is really the only important part when it comes to explaining for loops. If you look at the text inside the parentheses, you can see three instructions separated by semicolons:

Code: Select all

	int counter = 1;
	counter <= 10;
	counter++;
The first line is essentially no different than if you were creating a variable anywhere else in the program. The difference here is that the variable we create, in this case counter, will only exist inside the for loop. As soon as we exit the for loop, the variable is destroyed. This is only the case when the variable is created by declaring it there. If you were to use a pre-declared variable in the loop, it would not be destroyed at the end of the loop.
For example:

Code: Select all

int counter;  
for (counter = 1; counter <= 10; counter++) {
	Console.WriteLine(counter);
}
Console.WriteLine(“Exited the for loop.  counter = “ + counter);
counter would exist outside of the for loop, and the WriteLine statement would print out "Exited the for loop. counter = 11."

The second part of the for loop is the conditional statement. In our example, it is “counter <= 10;” which basically tells the loop to repeat itself as long as counter is less than or equal to ten. Because we start at 1 (we know this because the first part of the loop sets counter to 1), this loop will first go through where counter is equal to 1, and then reach the end of the loop and see that it is indeed less than or equal to 10, and go through again.

The last part of the for loop is what prevents the loop from running forever, which is commonly called an infinite loop. In our example, the last part is “counter++”. The ++ on the end of a variable is shorthand for “counter = counter + 1”. This statement is run every time the end of the loop is reached.

So now that you know how a for loop functions, lets go through an example run of the above loop, just to make sure everything clicks in place.

Code: Select all

for (int counter = 1; counter <= 10; counter++) {
	Console.WriteLine(counter);
}
Console.WriteLine(“Out of for loop!”);
When the program reaches the for loop, it begins by running the first part of the for loop’s 3 pieces of code. An integer variable named counter is created and given the value of 1.

Now, the program looks at the second of the three pieces of code in the for loop to check if it evaluates to true. Because counter (with a value of 1) is less than or equal to 10, the program enters the actual content of the for loop.

The line Console.WriteLine(counter) simply writes the value of counter to the screen. Right now, it prints out a 1.

Now, the program continues to the next line, which is the ending brace, }. This tells the program to head back to the beginning of the for loop and execute the last of the three parts of the for loop. counter++ increases the value of counter by 1, which means it now has a value of 2.

The program is now back at the start of the for loop, so it checks the middle statement again. 2 is less than or equal to 10, so it enters the loop again, where Console.WriteLine(counter) prints 2.

The second (conditional) part of the for loop (counter <= 10) always evaluates when the program is at the beginning of the for loop. The last piece of code in the for loop (counter++) always evaluates at the end of the for loop, before returning back to the top to check the conditional statement.

This process continues until Console.WriteLine(counter) prints out a 10. Afterwards, the program sees the ending brace again ()) and increments counter by 1, making it equal to 11.

Now, the program goes back to the top of the for loop and checks the conditional statement again. Because 11 is not less than or equal to 10, the program does not go back into the for loop again. Instead, it skips all the code until it gets to the ending brace } and continues to the rest of the program from there.

At this time, the program outputs, “Out of for loop!”

------

For loops in the most common languages:

C# / C++ / Java

Code: Select all

for (int i = 0; i < 10; i++) {
  // Do stuff
}
Perl

Code: Select all

for (my $i = 0; $i < 10; $i++) {
  // Do stuff
}
PHP

Code: Select all

for ($i = 0; $i < 10; $i++) {
  // Do stuff
}
Ruby

Code: Select all

for i in 0..10
  # Do stuff
end
Python

Code: Select all

for x in range (0, 10)
    # Do stuff
"When it takes forever to learn all the rules, no time is left for breaking them."

User avatar
IceDane
Because I Can
Posts: 2652
Joined: Wed May 12, 2004 9:25 am

Re: For Loops For Beginners

Post by IceDane » Sun Oct 04, 2009 6:56 am

NIce dude. I know I had trouble understanding for loops the first time around.

I might actually get myself together and contribute something to this forum myself.

Dark Nova
Hacker in Training
Posts: 91
Joined: Mon Feb 28, 2005 8:27 pm

Re: For Loops For Beginners

Post by Dark Nova » Tue Oct 06, 2009 11:04 am

Nice... I never knew you could get so much out of for loops, but hey there it is, I especially like the listing of forloops in multiple languages, I think that's a beneficial thing if you write tuts on concept rather than language secifics, kinda caters for the masses

NOVA

User avatar
foldingstock
htd0rg lieutenant
Posts: 300
Joined: Sat Aug 16, 2008 10:38 pm

Re: For Loops For Beginners

Post by foldingstock » Tue Oct 06, 2009 3:22 pm

Dark Nova wrote:Nice... I never knew you could get so much out of for loops
Loops, and in particular for loops, are one of the cornerstones of basic programming.

Dark Nova
Hacker in Training
Posts: 91
Joined: Mon Feb 28, 2005 8:27 pm

Re: For Loops For Beginners

Post by Dark Nova » Tue Oct 06, 2009 4:00 pm

What I meant was I couldn't have written that much to explain them :mrgreen: Guess my English is a tad concise

NOVA

horze
Hacker in Training
Posts: 53
Joined: Wed Aug 26, 2009 8:33 am

Re: For Loops For Beginners

Post by horze » Thu Nov 19, 2009 12:26 pm

This is the best explanation I have read about for loops.
Great work :D

guidj0s
Hacker in Training
Posts: 74
Joined: Sat Oct 10, 2009 11:29 pm
Contact:

Re: For Loops For Beginners

Post by guidj0s » Fri Nov 20, 2009 5:02 pm

Nice writing there, drusepth. I'd just like to add another valid for loop variant in Perl:

Code: Select all

for my $count (1..100)
{
   print "$count\n";
}
This is equivalent to:

Code: Select all

for (my $count = 1; $count <= 100; $count++)
{
    print "$count\n";
}
Remember the second way also works. It's just the C way of doing stuff. Beware, old and experienced Perl programmers will frown upon you if you don't go for the Perl way. I've seen people getting mad because of simple things like adding ()s when calling subroutines like:

Code: Select all

 close(filehandle);
 
instead of

Code: Select all

 close filehandle;
 
and

Code: Select all

 exit();
 
as opposed to

Code: Select all

 exit;
 

If you're starting out, though, you shouldn't worry about this. However, if you're really into perl coding and wanna know what practices are good and what mistakes you should look out for, I recommend reading the Perl Underground e-zines.

Post Reply