Page 1 of 1

FOR loops (conditional loops) Rate Topic: -----

#1 Gungnir  Icon User is offline

  • Your Imaginary Friend

Reputation: 152
  • View blog
  • Posts: 527
  • Joined: 21-May 11

Posted 28 September 2011 - 06:23 PM

*
POPULAR

I've seen a lot of people around the C++ section misunderstanding for loops. A travesty for sure!

For loops are as easy as 1, 2, 3! Quite literally.

Unlike in some other languages where for loops always require at least one predefined variable, C++ for loops can be entirely independent!

Before we get into things, I must warn you. I'm not a fan of equals signs (=) by themselves. I think they're ugly, so when I define an integer I'll do so using the Python Syntax of parenthesis. These are still correct in C++ and I prefer them... Let's proceed!

Most common FOR loops :-

Probably the most common for loop you'll come across (and inevitably use) is a conditional loop of the following syntax:
for(int a(0); a <= Number_of_loops; a++)
{
    //...
}



If this code were to be translated into English it would read something along the lines of: "I am a. I am equal to zero. I am going to execute the code "//..." and increase by one in value whilst I am still less than or equal to "Number_of_loops."

... More or less. Conditional loops still always execute their first and last loops.

You WILL use this loop many many many times. So here's a working example to cement the idea in your minds.
#include <iostream>
using namespace std;

for(int a(0); a <= 5; a++)
{
    cout << a;
}



you can probably do this in your heads if I've explained it properly thus far. Just incase, the output should be "012345". We'll come back to this FOR loop later but for now we're moving on.

From here on in, if you understand the concept you can probably leave. Everything that we do with FOR loops is based on that first mathematical condition... FOR the most part. ;)

FOR loops within FOR loops

Why would we put a FOR loop inside of a FOR loop??? To *scan* in another dimension of course, silly!
This is very important when we have lots of values in multiple dimensions and each dimension is significant! First off, let's get into what exactly putting a FOR loop inside of a FOR loop would do.

int D, C, I;
for(D(0); D <= 5; D++)
{
    for(I(0); I <= 5; I++)
    {
        for(C(0); C <= 5; C++)
        {
            //...
        }
    }
}



D can't increase until everything inside of it has executed, likewise with I. Logically, C would have to go through its 5 loops before I could increase, then C would be reset to zero and loop all over again, and so on and so forth until I reaches 5. Only then can D increase.

When C has looped 125 times, I has looped 25 times, and D has looped 5 times, the loop ends.

That's 125 executions in 10 lines of code! Now THAT'S power! The power of looping through multiple dimensions! Add another dimension and you could have 625 conditional executions. Increase the number of loops from 5 to 50 and that's 6,250,000 executions in just 4 dimensions, that's no more than 13 lines of code!

Let's stop playing hypercube and get back to our tri-dimensional conditional statement; A conditional cube, if you will. Now imagine that we can put these FOR statements together to form X, Y, ans Z coordinates on that cube. If we wanted to find the position 0, 1, 2, we would have to go through 8 loops of C. Imagine traversing 3 units down the width of the cube and shooting up two units along the height to get to our Cartesian destination. We'll talk about what to do when we get there in the next segment.

FOR loops and Arrays

Now by now you may have already realized that arrays and FOR loops go together like peanut butter and jelly. DELICIOUSLY!

if we wanted to print all but 5 of the values in an array we could simply substitute our conditional integer into the array, like so.

for(int a(0); a <= (Size_of_Array-5); a++)
{
    std::cout << array[a];
}



FOR loops give us a lot of control over arrays, and whilst I won't go too far into arrays I will bring you back to our conditional cube and tell you what to do there, if you haven't already found out.

FOR loops and Multidimensional Arrays

So we're on our cube of epic proportions and we've traversed the Cartesian planes of X, Y, and Z.

Let's put a multidimensional array in there! (Once again, I'm not going into these, you'll have to look them up yourself)

#include <iostream>

#define WIDTH 5
#define HEIGHT 5
#define DEPTH 5

using namespace std;

int multiarray[HEIGHT][WIDTH][DEPTH];

for(int D(0); D <= (HEIGHT-1); D++)
{
    for(int I(0); I <= (WIDTH-1); I++)
    {
        for(int C(0); C <= (DEPTH-1); C++)
        {
            cout << multiarray[D][I][C];
        }
    }
}


This should roughly print every statement in that tri-dimensional array. By adding another FOR or IF statement we can check the actual value inside of that position and only print values equal to, for example, 5. By now you know that the possibilities are endless!

I use FOR statements to place tiles in a map for tile based games.
Spoiler

I even used them to help me deal with arrays so that I could create my very own virtual bidimensional array class.

They're an incredibly powerful tool in the programmer's arsenal, and I hope that by now you've learned to harness the awesome awesomeness that is the FOR statement.

Is This A Good Question/Topic? 5
  • +

Replies To: FOR loops (conditional loops)

#2 stayscrisp  Icon User is offline

  • フカユ
  • member icon

Reputation: 1009
  • View blog
  • Posts: 4,195
  • Joined: 14-February 08

Posted 07 October 2011 - 01:36 AM

Nice work!
Was This Post Helpful? 0
  • +
  • -

#3 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 857
  • View blog
  • Posts: 2,340
  • Joined: 20-August 07

Posted 08 October 2011 - 10:56 AM

View PostGungnir, on 29 September 2011 - 02:23 AM, said:

for(D(0); D <= 5; D++)
{
    for(I(0); I <= 5; I++)
    {
        for(C(0); C <= 5; C++)
        {
            //...
        }
    }
}



D can't increase until everything inside of it has executed, likewise with I. Logically, C would have to go through its 5 loops before I could increase, then C would be reset to zero and loop all over again, and so on and so forth until I reaches 5. Only then can D increase.

When C has looped 125 times, I has looped 25 times, and D has looped 5 times, the loop ends.
No, your math is all wrong - when you initialise a for-loop variable with zero 0, and your sole loop invariant contains <= N (Where N is a positive integer), then your loop will repeat N+1 times if you increment your loop counter by 1 each time.

The code in your inner-most loop will repeat 216 times; The code in your second inner-loop will repeat 36 times and your outer-most loop will repeat 6 times.

Of course, anyone casually reading the code might think as you have done,which is why a more typical way to write for loops would look like this
for (int i(0); i!=N; ++i) 
(or alternatively using < instead of !=)


Also, you can only use initialisation syntax when you're declaring a variable. Once a variable is declared, you cannot use parenthesis to assign it a value (unless its a type which you've defined and you've overloaded the operator() with assignment semantics).

i.e, the following code is OK
int n(0);

but this will produce a compiler error
int n;
n(0); 

This post has been edited by Bench: 08 October 2011 - 11:04 AM

Was This Post Helpful? 2
  • +
  • -

#4 Gungnir  Icon User is offline

  • Your Imaginary Friend

Reputation: 152
  • View blog
  • Posts: 527
  • Joined: 21-May 11

Posted 13 October 2011 - 09:54 PM

Ahh, good catch, Bench! I totally missed that one! :D

I'll fix it now.

I'd rather use "<" than "!=" because if the compiler makes some freak, isolated mistake and the integer somehow passes the constant it will loop forever. "<" will at least catch these things. It's entirely optional with a good compiler, though.



Not sure how that second comment applies, don't worry, I learnt that one the hard way. ;)

EDIT: Just realized that I can't edit the first post, I'll see if I can't get a moderator or something to do it later on, I just hope everyone reads Bench's post ^^,

This post has been edited by Gungnir: 13 October 2011 - 09:58 PM

Was This Post Helpful? 0
  • +
  • -

#5 Gungnir  Icon User is offline

  • Your Imaginary Friend

Reputation: 152
  • View blog
  • Posts: 527
  • Joined: 21-May 11

Posted 14 October 2011 - 05:51 AM

I just noticed that in the third *code* tag, D, I, and C are all defined without types.

They should be of type int. Sorry about that, everyone! :(

EDIT: Fixed.

This post has been edited by JackOfAllTrades: 28 October 2011 - 01:26 PM

Was This Post Helpful? 0
  • +
  • -

#6 nityatricks  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 17-October 11

Posted 24 October 2011 - 03:30 AM

thanks was helpful and yea i still didnt understood the "How to use For Loop inside a For Loop" . . and if possible help with the similar way of that above you did like "I am a."
Was This Post Helpful? 0
  • +
  • -

#7 flypro  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 07-November 11

Posted 07 November 2011 - 04:12 PM

ahhhh--- the "for loop" my old nemesis -_-.......

I shall learn your wicked ways and strike you down!!!!!

or just learn how to use them properly :D.. lol

flypro.
Was This Post Helpful? 0
  • +
  • -

#8 Vermiculus  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 10
  • View blog
  • Posts: 314
  • Joined: 26-February 09

Posted 10 November 2011 - 12:32 AM

FOR loops really are just macros of WHILE loops. Observe

for(<initializations>; <condition>; <repetitive tasks like counting>) {
    <body statements>
}


is compiled as
<initializations>
while(<condition>) {
    <body statements>
    <repetitive tasks like counting>
}
free(<initializations>);


which is further compiled into IFs and GOTOs, and then into assembler.
Using IFs and GOTOs though is stupid, because there could be more optimization that could be done (like loop unrolling) by the compiler much more efficiently than you could do in a reasonable amount of time.

Depending on your compiler, it is better to use a WHILE loop.

This post has been edited by Vermiculus: 10 November 2011 - 12:36 AM

Was This Post Helpful? 0
  • +
  • -

#9 ishkabible  Icon User is offline

  • spelling expret
  • member icon




Reputation: 1622
  • View blog
  • Posts: 5,709
  • Joined: 03-August 09

Posted 13 November 2011 - 08:23 PM

actually it's more like the following, 'free' has nothing to do with it.

{
    <initializations>
    while(<condition>) {
        <code>
        <common task like counting>
    }
}



this is part of what makes for loops so appealing; they wrap up lots of semantics into a small package yet preform just as efficiently. often compilers will make special optimizations for them like iterating though an array using a register(as a pointer to the array) and increment that rather than actually indexing it every time.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1