Lesson 6: While, For, and Do LoopsOKAY! This is probably going to be the all-time shortest lesson!
You need it though.
Trust me!
Loops are very important in many different programs. Your games you play use loops to display your inventory, fight enemies, and many more things. If you are reading this tutorial, then you obviously wish to learn about them. So, without further ado, let's get started.
:::While:::While loops are used to iterate a certain portion of code, until a certain condition is met.
Ex:
- Code:
-
#include <iostream>
using namespace std;
int main()
{
int x = 0;
while (x < 9)
{
cout << "This will display 10 times." << endl;
++x;
}
return 0;
}
The above code will display the single cout statement and then stop. As you can see the while statement is saying: While the variable 'x' is less than the value of '9', display the following text. Once x >= 9 then stop the loop. You can set the parameter to other things. I suggest just playing around with it. It can actually get quite fun. :P
:::FOR:::The for loop is another iteration loop. I used it as an example in another lesson. Now you get to learn what it means. YEAH!!!!
- Code:
-
#include <iostream>
using namespace std;
int main()
{
for (int x = 0; x < 9; ++x)
}
cout << "This will display 10 times." << endl;
++x;
}
return 0;
}
This loop says the same thing as the while loop. The first part of the loop is the declaration of the variables used in the loop. The second part is the parameter by which the code below will be iterated. The last part increments the value up or down. SIMPLE!! Now you're thinking: "DOH! I can't believe I couldn't figure that out!"
:::Do-While:::The Do-While Loop does the same exact thing as the previous two loops. Iterating statements. Ex:
- Code:
-
#include <iostream>
using namespace std;
int main()
{
int x = 0;
do {
cout << "This will display 10 times." << endl;
++x;
} while (x < 9)
return 0;
}
This is saying: Do the following code while x < 9.
Told you the lesson would be the shortest EVAR!
Yet, I have this strange feeling of doubt that I forgot to tell you everything about these loops.
Watch the video here:
[You must be registered and logged in to see this link.]