Tutorials Navigation

Tutorials :: New :: Popular :: Top Rated

Tutorials: 18,326 Categories: 12

Total Tutorial Views: 41,306,687

C++ Beginners Tutorial: Advanced Loops.

Tutorial Name: C++ Beginners Tutorial: Advanced Loops.  

Category: PC Tutorials

Submitted By: Nissan

Date Added:

Comments: 0

Views: 4,927

Related Forum: PC Building Forum

Share:

C++ Beginners Tutorial: Advanced Loops.


Weve already come across the 3 C++ loops; the while loop, which loops until a condition is satisfied, the for loop, which loops for a given number of iterations, and the do while loop, which runs a while loop but checks to see if the condition is satisfied at the end of each loop, not at the start. There is a lot more to loops that we havent yet studied however.

In C++ it is legal to have a loop with no body (no code inside the curly brackets). We already know this, as:


while(a < b)
{
}


is perfectly valid code. You may not realise this yet, but a loop with no body can be very useful. So useful in fact, C++ lets us take shortcuts:


// This is allowed
while(a < b);
 
// And so is this
for(i = 0; i < b; ++i);


But other than infinite loops or over-engineered incrementing what are loops without bodies actually useful for? Well, C++ also lets us place statements inside loop conditionals. In fact, you can do this with normal conditionals too. How does this work? Consider this:


int a = 0;
 
while(cin >> a);


If you were to put this into a program and then run it, you would see that the user could enter anything they liked, over and over again, as long as it was a number (or nothing). If they entered something other than a number (something that can't be interpreted as an int) then the loop terminates. Heres a more practical example:


int a[100] = { 0 };
int i = 0;
 
while(cin >> a[i++] && i < 100);


This piece of code will read up to 100 integers from the user and store them in an array. With a loop body, it would look like this:


int a[100] = { 0 };
int i = 0;
 
while(i < 100);
{
    cin >> a[i++];
}


The first is no harder to read, (I even find it quicker to understand) and has saved 3 lines of code, as well as a level of indentation. If it was placed in an if statement or two then the levels of indentation would look like a mess. As Linus Torvalds said, If you need more than 3 levels of indentation, youre screwed anyway, and should fix your program.**

It is also possible to make assignments in loops (and ordinary conditionals) but then you must make sure you put brackets in the right place so the compiler doesnt get confused:


// Is a being set to b and then compared to 10, or is a being set to
// whether or not b < 10 is true or not?
while(a = b < 10);
 
// Much better
while((a = b) < 10);


Thats enough of empty-bodied loops, lets look a little more at the loop. When writing a for loop you do not need to specify each condition, some (or all) can be left out. For example, you can leave out the initial assignment:


int i = 3;
 
for(; i < 10; ++i)
{
    cout << i << endl;
}


With no assignment the loop will begin with the value of i before the loop started (in this case 3) instead of resetting to whatever value you specify. This would be useful if, say, the program asks for a starting number, and then runs a loop from that starting number to some end one. Previously we would need to store the input and then assign that to our loop variable in the loop condition, using two variables for one loop. Now though, we can just set our loop variable to the input directly and then not reinitialise it in the loop. (I suppose you could also set it to itself, but thats a pretty horrible way of doing things!) You probably wont use this feature that much, but its good to know.

Likewise, you can also leave out the other parts of the loop, just keeping the semicolons. Leave out the incrementing part and the loop variable will not change from one iteration to another (unless you change it in the loop body)*, or leave out the end condition and let the loop run forever (or again, until you forcibly terminate it)

Up until now we have only been able to define termination conditions for loops in the first line of the loop itself (after the while or after the for), but it is impractical to define many exit conditions. As a rather contrived example, how would we write a for loop that outputs every number from 1 to 100, but stops if the user enters the letter q? We could easily do it with a while loop, and use what we learnt above to make it quite small, but lets do it in a for loop:


int i = 0;
char input = ' ';
 
for(i = 1; i <= 100; ++i)
{
    if((cin >> input) == 'a')
    {
        break;
    }
}


Here weve introduced another word, break. This does exactly what is says, and breaks the flow of the loop, stopping it and letting the program continue from after the loop body. There is a counterpart to break, called continue, which stops the current iteration of the loop and jumps straight back to the beginning without executing whatever what was after it. In a while loop this just cuts off some code, but in a for loop it increments the loop variable too.

Finally, theres a little quirk of syntax that we can exploit with loops (or if statements, for that matter). If there is only one statement in a loop body, we can skip out the curly bracers altogether, and get something like this:


for(int i = 0; i < 100; ++i)
    cout << i;


Here Ive also used the fact that we can write statements inside of conditionals to declare and define the variable i inside the loop itself. This saves some code, and also restricts the life of i to be only within the loop; after the loop the variable ceases to exist.

Ratings

Current rating: 6.57 by 14 users
Please take one second and rate this tutorial...

Not a Chance
1
2
3
4
5
6
7
8
9
10
Absolutely

Comments

"C++ Beginners Tutorial: Advanced Loops." :: Login/Create an Account :: 0 comments

If you would like to post a comment please signin to your account or register for an account.