Friday, January 25, 2013

Break-ing and Continue-ing


The break and continue keywords disrupts program flow inside loops, whether the for-loop or while-loop.
while(condition) {
    statement 1;
    statement 2;
    break;
    statement 3;
    statement 4;
}

statement 5;
statement n;
The break statement causes the program flow inside a block to forcibly exit (whether for-loop or while-loop). In example code above, as soon as the break statement is encountered, the program control will ignore statement 3 and 4. The while loop will go out of scope and program control will be transferred to the first executable statement immediately after the while block -- in this case, statement 5.
You normally will not use the break statement in this fashion because it doesn't make sense. This statement is usually deployed with more logic finesse. Let me show you an example.
while(condition) {
    statement 1;
    statement 2;
    
    if(someCondition) {
        break;
    }   

    statement 3;
    statement 4;
}

statement 5;
statement n;
This is a more likely use of the break statement. I should warn you though that this is a frowned upon practice. A truly structured programming should have only one entry point and one exit point. Because of the introduction the break statement, our control structure now has one entry point and two exit points.
While this code is innocent enough right now, it could get very hairy and complicated. You will appreciate following the 1-entry-1-exit rule when you have had your fair share of debugging someone else's code and you are wading through a maze of nested structures with lots of breaks peppered into the source code.
Next is the continue keyword. Here is how it behaves.
while(condition) {
    statement 1;
    statement 2;
    continue;
    statement 3;
    statement 4;
}

statement 5;
statement n;
When the continue statement is encountered, statements 3 and 4 will be ignored (just like how it was with the break). Unlike the case in break though, the loop will not go out of scope and will not be immediately terminated.
What the continue statement will do is to go back to the beginning of the loop and forcibly re-evaluate condition. If the condition is still true, then the loop continues normally.


Call me and you will get the knowledge and skills you need instantly.
For inquiries contact me on my mobile number or email me at inquiry@eglobiotraining.com. View my multiply site http://erwinglobio.multiply.com
 
 
Prof. Erwin M. Globio, MSIT
Senior IT Lecturer
Far Eastern University
Email Address: inquiry@eglobiotraining.com
Skype: erwinglobio
 
 
Call Now:
 
SMART: 09393741359
SUN: 09323956678



No comments:

Post a Comment