For Loops

Firstly I’d say I didn’t know I had to press Ctrl C to stop a program running. When I saw my first, second and third infinite loop I pooped my pants… and clicking the x in the corner closes everything, very annoying!

So here’s how a For Loop is set up, followed by an example.

I always learn more playing with examples and figuring out myself.


for (variable initialization; condition; variable update)

{

/* Do some awesome thing while the condition is true.

}

Example of a For Loop:


for ( int x=0; x<10; x++)

{

cout << x ;// code runs, adds 1 to x each time, stops when x=10.

}

Outputs:


0123456789

Advertisements

2 thoughts on “For Loops

  1. Infinite loops are awesome 😉

    Whats the difference between your for loop and

    int x = 0;
    while (x < 10){
    your statement;
    x++;
    }
    

    Nothing? Or a performance difference maybe?

    • Yeah this would work the same. I’m going to do my next blog on while loops. But I’m not expert yet! ^^

      I think for simple examples like this it won’t make much of a difference, except your’re using five lines and in a for loop it would only be three.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s