File Management

Miscellaneous

Newbie Programmerbreak and continue the loops

Newbie Programmer

full book coming soon

by Shubham Ramdeo

break and continue the loops, no need for goto !

Welcome back to the Newbie Programmer Series. We are learning about controlling the flow. In the last part (click here), we have learned about the goto statement that how its useful for jumping in between code for error handling but also that using goto is a bad practice. In this part, we will learn about break and continue statements. These are the statements that can help you to manage the flow of your program without using goto. In some way, break and continue are the alternatives of goto. But they have many other advantages to and we will discuss them here. So if you are new to this series, please go to index (click here) and read out all the previous parts so that you can easily understand what is going down below. Break and continue statements are made to use with loops only. Lets discuss the coding stuffs.

Break

Using break is ultra easy

. . . . . . .
break;
. . . . . . .

And ultra sonic easy to understand !!! In our code, whenever the break statement is encountered, the program comes out of the current loop. That's simple. The loop will be stopped immediately when the break statement is encountered.

But why so ? Don't you see that we have made the for loops for 10 times ? And instead of 10 'hello" we are getting 5 only ! That is so because every time the loop runs, it is checked if x becomes 5. When x becomes 5, the break statement inside the if block is encountered and the loop stops.

For such quitting, we can make a label below the loop and use the goto statement inside the loop to quit the loop. But break is better alternative.

Continue

Similar to use :

. . . . . . .
continue;
. . . . . . .

Just as break stops the loop, continue statement is used to come back to the loop. Break statement makes our program to come out of the loop and continue statement makes the program to get into the loop again and all the other statements are skipped.

Its simple. The loop will go for 10 times. In these 10 loops, it will ask you for a number. If the number is less than 5 then due to the continue statement, the loop will start again and all the statements inside the loop ( like here for saying thanks ) are skipped. It will repeat 10 times in total. In these 10 times, for all the numbers you have entered which are greater than or equal to 5, you will get a thanks otherwise nothing.

We can use a label above the loop and then use the goto statement inside the loop to start it again. But continue is a better alternative for it.

So that's it for today. In the next post, we are doing another interesting stuff. So stay connected.

Please share this post as much as you can so that we can get connected to more geeks who wants to learn programming but have no clue. Thanks for reading :)(c)Shubham Ramdeo, All rights reserved.