Welcome back programmers, to another tutorial on C++ programming! Today’s tutorial is going to be a little difficult to learn today, but it’s an important lesson.
The lesson is about For Loops today. It is one of the three loops I will be teaching. Loops are an important part of programming, and you will be using them a lot when you’re programming your game. Some examples are player controls, and moving bad guys and bullets on the screen.
For Loops are a lot like If Statements. IF you remember the If Statement Tutorial THEN For Loops will be easier to understand (That never gets old :D). Like If Statements, For Loops have their own syntax:
for (initialization; condition; increase)
In a For Loop you begin with initializing a variable inside the parenthesis; separated with a semicolon, you write your condition; separated with another semicolon, you write the increase.
Let me show you how it’s all done by using this code:
using namespace std;
for(int x = 0; x < 21; x++)
cout << x << endl;
In our program we initialized a variable INSIDE the for loop. Then we wrote our condition: x < 1. For our increase we put x++, which basically means increase the value by 1. Sound confusing?
Let me explain:
The for loop starts with x = 0; then the program checks the condition; if the condition false the program runs the statement inside the for loop. After the statement runs, the value increases by the number you set in the for loop. In this case, it’s ++ (also called increase operators) meaning it’s increasing by 1. This loop will continue to increase and execute the statement until the condition is true (x < 21). Meaning that our program will end up looking like this.
The reason why the program did not print 21 is because that condition is true. That’s where the loop ends.
This is pretty much all there is to for loops. Here are few things I want to add before I end this tutorial:
- You can also use decrease operators in your for loop with two minuses (–)
- You can increase or decrease values by more than one number using += or -=
example 1: x+=5; // increase value by 5
example 2: x-=3; // decrease value by 3