The break and continue statements

Asked By 0 points N/A Posted on -
qa-featured

In C language what is break and continue statements and why we use these in our program?

SHARE
Best Answer by rnyakundi
Answered By 0 points N/A #123112

The break and continue statements

qa-featured

The break and continue statements are used  to decide whether to stay in the loop or to get out of the loop. As soon as the statement which is provided in the loop gets true it will execute either break or continue statement.

As soon as the conditions gets true in case of break statement, it will get out from the loop,it occurs when an unexpected condition is executed.

Now the continue statement whenever it is executed it transfers the control in the beginning of the loop.The continue statement makes the program complex and confusing for the compiler as compared to the normal loop.So it is better not to use continue statement if it's possible.

Best Answer
Best Answer
Answered By 0 points N/A #123113

The break and continue statements

qa-featured

 

Suppose that your program is in the middle of a loop and suddenly it finds its answer. This is where the beauty of the break statement becomes clear. The break will transfer control out of the loop you are in and begin executing the statements following the loop, effectively terminating the loop. This statement is very useful when you need to jump out of a loop depending on the answer of some calculation in the loop. It's also useful in the implementation of infinite loops (loops that can execute indefinitely) where control can transferred out of the loop once a certain condition is met and avoid staying in the loop forever.

On the other hand, When a continue statement is encountered, whatever was being executed at that point will be stopped and execution will be transferred to the start of the next loop pass. This might be useful to avoid a divide by zero.

This example illustrates the use of continue and break statements:

int counter;

for(counter = 0;counter < 5;counter++)

{

            if (counter == 3)

            break;

            printf("in the break loop, counter is now %dn",counter);

}

 

for(counter = 0;counter < 5;counter++)

{

            if (counter == 3)

            continue;

            printf("In the continue loop, counter is the now %dn",counter);

}

In the first "for" there is an if statement that calls a break if counter equals 3. When counter reaches 3, the loop is terminated and the last value printed will be the previous value, namely 2.

The next "for" loop, when the value of counter reaches 3 the continue statement will make the program jump to the end of the loop and continue executing the loop, effectively eliminating the printf statement during the pass through the loop when counter is 3. 

 

Related Questions