Gw Temp

Menu

Tutorial - 'Comprehensive C++ Tutorial for Beginners - Part 4' by AzureFenrir

An item about Programming Languages posted on

Blurb

The fourth installment of AzureFenrir's C++ tutorials. This time, he discusses loops, their function, and their many varieties.

Body

Comprehensive C++ Tutorial for Beginners - Part 4


Guess what? I'm back with more C++ tutorials!

*AzureFenrir is immediately shot*

Hey, wait, wait. If you kill me, then I can't write any more C++ tutorials! You don't want that, do you?

*AzureFenrir is immediately shot several times with a chain gun*

OK, OK, I'll start the actual tutorial now. Just don't shoot me anymore and put the guns down...that's right, I can't file suit if I'm dead, can I :P?

Anyway, this tutorial shall educate you on the amazing subject of C++ loops. If you've never programmed before, loops allow you to repeat certain commands, with slight modifications, until a certain conditions are met. For example, a loop may cause the program to display "Hello!" 100 times, or slap someone until they type "I surrender" with their nose while raising a white flag...never mind.

Basically, just remember that loops allow you to repeat pieces of code over and over again.


"For" Loops

"For" loops are the first types of loops that we will see. Like all loops, they allow you to repeat a block of code until a condition is met. The syntax of "for" loops (basically, how you use it) is as follows:

for(initialization; condition, increment)
{
    Code that you want to repeat;
}


Whoa! Did you understand what the heck that meant? Well, first of all, you know that loops allow you to repeat code, so the Code that you want to repeat is basically whatever code that you want to repeat. Let's focus our attention on the three parts of the "for" loop, the initialization, condition, and increment statements.

The initialization statement runs at the very begining of the loop, before any repetition of the blocked code occus. In fact, the code in here will run before the code that you want to repeat is executed ONCE! This code is basically used to initialize a variable (like i) to a number so that it could be used in the rest of the loop.

The condition statement will end the repetition if it's false. For example, if the condition is, say, i < 11, then whenever i is larger than or equal to 11 (which would make the statement FALSE), the loop will terminate.

The increment statement will run every time the loop interates, or repeats. So, if the statement contains, say, i++, then every time the code in the loop runs, i increases by one.



Still confused? Don't worry, I'll walk you through this sample for loop step-by-step, using diagrams to show you the actual process of the code. So, for the following sample code, let's assume that the variable i has already been declared:

for(i = 2; i < 5; i++)
{
    cout << "The variable i is currently " << i << '\n';
}
return 0;


Let's walk through this code, using bold to show the code that is currently being run. When we begin, the C++ compiler reads the for statement:

for(i = 2, i < 5; i++)

Because the loop just started, we must run the initialization code first, so:

for(i = 2; i < 5; i++)

Now, i has been initialized to 2. Now, the code goes to the conditional statement and calculates its value:

for(i = 2; i < 5; i++)
i = 2

Since the conditional code (i < 5) has not yet been reached (since i = 2, and 2 is smaller than 5), we must start our first run through the loop, so we run the cout code:

cout << "The variable i is currently " << i << '\n';
i = 2

This writes the words "The variable i is currently 2" to the console. Finally, we encountered the (}) code, which indicates the end of the for block. Because loops repeat code, the program now leaps back to the for code:

for(i = 2, i < 5; i++)
i = 2

Because this is the SECOND time through the loop, the initialization statement (i = 2) doesn't run. Instead, the increment statement runs:

for(i = 2, i < 5, i++)
i = 2

After this code, i will now equal 3. The condition statement will run again:

for(i = 2; i < 5; i++)
i = 3

Now, because three is STILL smaller than 5 (the condition statement is still true), the code inside the for loop runs again:

cout << "The variable i is currently " << i << '\n';
i = 3

This writes the words "The variable i is currently 3" to the console. This code then runs again, in the same way:

for(i = 2, i < 5, i++)
i = 3

for(i = 2; i < 5; i++)
i = 4

cout << "The variable i is currently " << i << '\n';
i = 4

Now, the words "The variable i is currently 4" will be written. Finally, let's run through the final interation of the loop:

for(i = 2, i < 5, i++)
i = 4

This would make i equal to 5. Now, the condition statement is NO LONGER reached:

for(i = 2; i < 5; i++)
i = 5

Obviously, five is not smaller than 5, so the condition statement (i < 5) will return false. This causes the for loop to skip its code block (and thus not run the cout statement) and run the next statement:

return 0;

Now, the program exits, and leaves the following output:

The variable i is currently 2
The variable i is currently 3
The variable i is currently 4


Capiche?



Now that you undestand the basics of for loops, let's look at what else for loops can do. Obviously, the above loop type (which is the most common use for "for" loops) runs the blocked code a finite amount of times depending on the starting and ending values of i.

However, because the "statements" can consist of any code, you can make "for" loops such as:

for(char string[25] = ""; strlen(string) < 15; strcat(string, "a"))

or:

for(int i = 0; abs(i) < 8; i = (i * j) + k - m)

As you can see, you can use other commands (such as int i = 0;) and functions (as well as ANY valid C++ statement) in for loops. In fact, you can even have multiple initial and increment statements:

for(int i = 0, int j = 0; i + j < 10; i++, j++)

As you can see, you can use commas (,) to use multiple commands for a statement. In the above example, the initialization statement initialized BOTH i and j to 0, and the increment statements adds one to BOTH i and j. Thus, two variables were used to evaluate and terminate the "for" loop.

Remember that variables used in the "for" loop are in no way sacred or protected. Therefore, you can change them anywhere in the for loop. In fact, you can even change the variable so that the for loop terminates early:

for(int i = 0; i < 8; i++)
{
    i = 12;
}


This code will cause the for loop to run once and immediately end. After all, on the second time through the for loop:

for(int i = 0; i < 8; i++)

i = 12, which caused the condition statement to return false (0). This causes the for loop to end, even though an external code set the i statement to 12.

You can also eliminate certain parameters of the for loop, like:

for(int i = 0; i < 8; )

Or even:

for( ; ; )

The above statement will create a phenomenon called an infinite loop, which is a loop that will never end because its condition does not exist or never will be met. Infinite loops are usually poor coding practices since they make your program run forever. If you've ever seen windows crash, and nothing seems to be working (not even Ctrl-Alt-Delete) - well, that's probably an infinite loop.

Finally, you can also have multiple conditions for the conditional statement, but the process is a bit different:

for(int i = 0; (i < 3) && (i > -5); i = i * j)

You have to use boolean operators to link the two conditions. After all, C++ doesn't care what code you put in the conditional statement, as long as it gets either a true or a false value. If it gets something else (like a dereferenced string), then it will start raging.

Remember that any C++ statement can be empty, so the for loop doesn't even need to contai any code. For example:

for(int i = 0; i < 10000; i++) ;

These types of code are usually used to delay the program for a moment, although it does have other uses.



While Loops

Phew! That lesson on the "for" loop is certainly very long, isn't it?

Well, you'll be glad to learn that "while" loops are simpler. Its syntax is:

while(condition)
{
    Code that you want to repeat;
}


"While" loops repeat the Code that you want to repeat until the condition statement returns false. So, if condition is i < 6, then the code repeats until i is NO LONGER smaller than 6. Similarily, if the condition contains i == 7, then the loop will repeat until i does equal seve. Basically..."while" loops are essentially the same as for loops with no initialization or increment. In fact, it could easily be written as a for loop, like this:

for( ; condition; )

Here's an example of a "while" loop in action:

while(getch() != '\r')
{
    cout << "You will press enter or else!!!\n";
}


So, what does this program do? Well, obviously, we haven't learned the _getch() function yet, so let's briefly cover that before continuing.

getch is a very unique little function that allows us to read ONE CHARACTER from the console without forcing the user to type "ENTER" (somewhat to "Press Any Key to Continue"). Therefore, this code basically displays "You will press enter or else!!!" until the user actually presses enter. It's quite similar to another function, cin.get(), except cin.get() requires you to press after typing the character.

So...we don't really need to walk through this. The code simply keeps running through the code until it encounters a '\r' character, which indicates that is pressed.

Oh, and you probably have no idea what '\r' is, and why we are not using the newline '\n'. Well...there are two characters returned when is pressed: a carriage return, and a line feed. Normally, in the older days, carriage return ('\r') is supposed to return the cursor to the beginning of the line, and line feed ('\n') is supposed to move it to the next line. We've only used '\n' because DOS will recognize it as a newline character even if it's not accompanied by a '\r'. However, for compatibility purposes, the key will retun BOTH the '\r' and '\n' characters, and since getch() only gets the first character typed in, it will retun '\r' and discard '\n'.

Did you understand that? If not, just remember that will result in both '\r' and '\n', and getch will thus only return '\r'. The cin class, however, will properly handle this \r so you won't have to worry about it.



Do...While Loops

"Do...While" loops are exactly the same as "While" loops...except for one major difference:

do
{
    Code that you want to repeat;
} while(condition);


Did you notice that the "while" is on the very bottom? That's because, unlike "while" loops, "Do...While" loops check the condition at the very bottom of the code, which means that the code inside the loop will be guaranteed to run at least once.

What does this mean? Well, let's look at an example:

int i = 8;

while (i < 5)
{
    cout << "Here is looped code!\n";
}


This code will not do anything (well, actually, it will create a new variable and set it to 8, but it will not PRINT anything). Why is that? Well, when the system reaches the while (i < 5), it checks the condition and finds it to be FALSE (8 is not smaller than 5). Therefore, the loop exits immediately, and the cout code is never run.

But what about this:

int i = 8;

do
{
    cout << "Here is looped code!\n";
} while (i < 5);


In this case, because the while (i < 5) is behind the code, the "cout" code will run once before the compiler realizes that i is not smaller than 5. This makes the code print "Here is looped code!" once.



Exiting Loops Early

There is another way to exit loops, even if the conditions are not met. This is accomplished with the break keyword:

break;

What a simple keyword! It doesn't even need any parameters :). Simple, happy, joyous...ahh...

*snap*

Oh wait, where was I? Right. The break statement unconditionally exits out of the current loop (even if the condition is not met). So:

while(true)
{
    cout << "Here is looped code!\n";
    break;
    cout << "Here is more looped code!\n";
}


This code will only print "Here is looped code!" When the interpretor reaches the break statement, it will immediately exit the loop, even though the loop is infinite (the condition statement is always true, and "while" loops will only end if the condition is false).



Going to the Next Iteration of a Loops Early

What does "iteration" mean? Well, it's basically one "run" of the loop. So, when the code finishes its code and begins to repeat it, it's starting a new iteration.

So, for this infinite loop:

while(true)
{
    cout << "Here is looped code!\n";
}


Every time the "Here is looped code" is displayed, the interpretor returns to the "while" statement, and another iteration is begin. To top it off, continue is used as simply as break:

continue;

Again, what a simple keyword! It doesn't even need any parameters :). So...we need an example to complicate this simple statement:

for(int i = 0; i < 10; i++)
{
    cout << "The number is " << i << '\n';
    if((i % 4) != 0)
    {
        continue;
    }
    cout << "It is not a multiple of 4!\n";
}


This results in:

The number is 1
It is not a multiple of 4!
The number is 2
It is not a multiple of 4!
The number is 3
It is not a multiple of 4!
The number is 4
The number is 5
It is not a multiple of 4!
The number is 6
It is not a multiple of 4!
The number is 7
It is not a multiple of 4!
The number is 8
The number is 9
It is not a multiple of 4!
The number is 10
It is not a multiple of 4!

This code will only print "It is not a multiple of 4!" if i is not a multiple of 4. If i is, then the interpretor will run the "continue" statemeny and immediately go to the next iteration of the loop, completely ignoring the rest of the code (which is the cout << "It is not a multiple of 4!\n"; statement).



A look at ancient C++: Labels and Goto Statements

Dn7 always accuses me of including old C++ statements in my tutorials (which I must admit to - sometimes, I am still nostaglic about certain old C++ material). So, to end this tutorial, I want to give you a taste of one of the most ancient loops available: Labels and GOTO Statements.

GOTO has been widely used in older programming languages, starting (as far as I know) in ALGOR. Presently, it is shunned by many programmers (including me) because of unstability reasons - most programmers believe that jumping around in code makes it disorganized and makes debugging difficult. Although it is generally replaced by loops, it can still be used in your program. No one will know if you used a GOTO statement unless if they look through your entire program in assembly.

You can define a label with a colon, like:

label_name:

And return to a certain label using:

goto label_name;

GOTO will return the interpreter to the label label_name, so:

superlabel:
    cout << "INFINITE LOOP\n";

    goto superlabel;


Will cause an infinite loop. GOTO statements are thus usually used in if statements or other conditional functions.



All right. This tutorial is a good way to end a good Saturday. I am AzureFenrir, and this is a GW Tutorial. Good-bye.

(As you can see, I wrote this conclusion while I was watching the 5:00 news.)