C++ Tutorial #6 – For Loops

Facebooktwittergoogle_plusredditpinterestlinkedinmail

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)
{
statement;
}

 

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:

 

 

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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

Facebooktwittergoogle_plusredditpinterestlinkedinmail

About Justin

Computer programmer and owner of kauergames.com.
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *