Can someone please explain

Pages: 12
closed account (iAk3T05o)
Can someone please explain for loops.
Dem7w2 perfectly explained do loops for me but no one seems to answer my other questions in that thread.
I haven't learnt anything after loops in the pdf tutorial of this site.

Please don't add arrays in your code examples. I only know the #include <iostream>, <string> and <sstream>. I don't know void only int.
Don't tell how to use the things i said i don't know how to use above, i'll like to learn them myself and if i encounter difficulties, then i'll ask.
Please show me example programs using for loops and explain :).
Thanks a lot:).
For loops are similar to do/while loops. They designed to make it easier to loop a fixed number of times.

For example:

1
2
3
4
for(int i = 0; i < 10; ++i)
{
    std::cout << "This will print 10 times" << std::endl;
}


The syntax is arranged like so:

1
2
3
4
for( (initialization); (condition); (iteration) )
{
    (body)
}


When the loop starts:
1) the initialization is performed.
2) the condition is checked. If it's true, proceed to step 3, otherwise, exit the loop.
3) perform the loop body
4) once the loop body is complete, perform the iteration
5) go to step 2

So basically... the for loop given above run keeps a counter 'i' that is keeping track of how many times the loop body has run. Once it reaches 10, the loop stops.
closed account (iAk3T05o)
That is very similar to the pdf tutorial example and i don't understand it.
Can show a q&a program using for loops
Thanks.
OK, for loops can kind of be thought of as until loops.

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

What this is saying is, set I to zero, and loop adding one to I with each loop until I is greater than 10.

Another way to write it would be:

1
2
3
4
5
6
int i = 0;
  while(i < 10)
  {
    i++;
    <do something>
  }


Is that any clearer?



1
2
3
4
for(int i = 0; i < 3; ++i)
{
    std::cout << "This will print 3 times" << std::endl;
}



The short explanation:

'i' is a counter that counts up every time the loop body is performed. Once the counter reaches the specified value (in this example: that value is 3) the loop exits. So this for loop basically says "run this body 3 times".


The detailed explanation of what's actually happening:

- The initialization step is performed: i = 0. This sets our counter to zero.

- The condition is checked: i < 3. Since i=0, the condition is true, so the loop continues.

- Loop body is performed (text printed)

- The iteration step is prformed: ++i. Our loop counter 'i' is incremented. Now, i=1

- Condition is checked again. Since i=1, it is still true, so the loop continues

- Body perfomed again... text is printed a second time.

- Iteration performed again. Now i=2

- Condition checked again. i=2, which is still less than 3. So it's true. So loop continues.

- Body performed again... text is printed a 3rd time.

- Iteration performed again. Now i=3

- Condition checked again. i=3, which is NOT less than 3... so the condition is FALSE and the loop exits.
Last edited on
closed account (iAk3T05o)
I've spent almost 2hrs trying to implement for loops in my program and got no progress. Can someone please show a q&a program using for loops.
The program will ask the user for the answer to a question twice and if the answer is still incorrect, it'll end.
Please help
This is some off the cuff code, it might not compile so fixing it can be an exercise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>;
#include <string>;

int main(int argc, char* argv[])
{
    string answer = "";
    string correct_answer = "42";
    for ( int i = 0; i < 2; i++)
    {
        cout << "What is the answer to life, the universe and everything?" << endl;
        cin.ignore();
        getline(cin, answer);
        if (answer == correct_answer)
        {
            cout << "That is correct" << endl;
            break;
        }else{
            cout << "That is not correct" << endl;
        }
    }
}

http://www.cplusplus.com/forum/beginner/120231/
There's a pretty good explanation posted here at the end of this other thread, that even a beginner should be able to grasp.
Last edited on
closed account (iAk3T05o)
@vallius: thanks for the code. It helped a lot but i'll need more practice.

I got it to work (but i removed the things below)
The code does have problems and thanks because it prevents copy and paste. (I removed these) Why do you put ; in the #include part (i've never done that).
I don't know what that cin.ignore does or why you put those things in the int main brackets. (still learning so...).
Can you show me a similar example using while loops.

Thanks a lottt.
Yeah, the ; 'include is me having got about 5 hours sleep a night for the past 3 weeks... never have children.

cin.ignore() basically throws away everything that's waiting in the buffer so that when you fetch input you know it's fresh... well, that's a simplified version of what it does. Go look it up.

Anyways, here's the same with a while loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>

int main (int argc, char* argv[])
{
    string answer="";
    string correct_answer="42";
    int loops = 0; // set loops to 0, this is intialise

    while(loops < 2) // only loop while loops is less than 2, this is loop condition
    {
        cout << "What is the answer to life, the universe and everything?" << endl;
        cin.ignore();
        getline(cin, answer);
        if(answer == correct_answer)
        {
            cout << "That is correct" << endl;
            break; // exit this loop immediately.
        }else{
           cout << "This is not correct" << endl;
        }
        loops ++; // increment our count, this is loop control
    }
    return 0; // I forget this last time.
}


so a for loop is made up by for (<initialise>;<loop condition>; <loop control>)

I hope this helps,
Dax.
Last edited on
closed account (iAk3T05o)
Thank you dax and acolyte. I now understand it (i'll keep practicing till i do it without looking at your examples).
Destroy computer feeling diminishing . . . (hope my looping problems are gone. Whew!)
Oh, the things in the main brackets are boilerplate for accepting command line arguments.

argc is how many arguments there are and argv[] is the arguments themselves placed into a handy array.

So if I called myCode -v -h -g hello

I'd have argc=4 and argv={"-v", "-h", "-g", "hello"}.

This is a classic example of where for loops are great.

I hope that helped...
Dax
closed account (iAk3T05o)
Nope, i don't understand the argvc stuff. I hope it's in the pdf tut so when i get there and i have problems, i'll ask.
For some reason, please could you show that example using do loops
Thanks.
do loops are just while loops that must always run once... but sure.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>

int main (int argc, char* argv[])
{
    string answer="";
    string correct_answer="42";
    int loops = 0; // set loops to 0, this is intialise

    do 
    {
        cout << "What is the answer to life, the universe and everything?" << endl;
        cin.ignore();
        getline(cin, answer);
        if(answer == correct_answer)
        {
            cout << "That is correct" << endl;
            break; // exit this loop immediately.
        }else{
           cout << "This is not correct" << endl;
        }
        loops ++; // increment our count, this is loop control
    }while(loops < 2);// only loop while loops is less than 2, this is loop condition
    return 0; // I forget this last time.
}
Last edited on
closed account (iAk3T05o)
Thanks Dax:)
closed account (iAk3T05o)
One last thing. Why do we have all these loops if from your example, they all do the same thing (i may be wrong).
They *can* do the same thing. And in many cases will compile into very similar code.

while is useful when you don't know how many times you need to loop but you know when you need to stop.

do while is useful if you know you need to do something at least once and like while you'll know when to stop.

for is great if you know in advance how many times you need to loop.

For instance, if you know how big your array is in advance you can use a for loop to iterate over it, the compiler might even be able to optimise that quite a bit.

If you have the time and don't already know them then you should look up the
continue; and the break; keywords... they're very useful.

Cheers,
Dax.

So if I called myCode -v -h -g hello

I'd have argc=4 and argv={"-v", "-h", "-g", "hello"}.


That's incorrect.

argc is always at least one, and argv[0] is the name of the executable.
closed account (iAk3T05o)
@dax: Looks like for loop does the function of do and while loops with one bracket but for the fact that 'for' is used, it'll take a while to get used to. I learnt how to use the break statement yersterday by just looking at it. Continue comes after that and thanks to you, acolyte and dem7w2, i can finally move on to other topics (whew!).
I hope i never need that argvc stuff because it looks more complicated than loops or i hope i'm wrong.
argc is always at least one, and argv[0] is the name of the executable.


<technicality>

argv[0] is the command used to invoke the executable. This may or may not be the actual name of the executable file depending on how the program was launched.

</technicality>
Pages: 12