C++ continue vs break

Spread the love

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

if ( i % 2 )

continue; // next point of execution is the for ( …


The continue statement above will not allow the program to execute any of the code below which is inside the same for loop. The next instruction to be executed will be the test for i < 5 in order to ascertain whether the code should continue running or not.
The code below shows the use of the continue syntax.

// Example program
#include <iostream>

int main()
{
    for ( short int i = 0; i<9 ; i++){
        
        if ( i % 2 )
            continue;
            
        std::cout << "i = " << i << std::endl; 
    }
}



Do you understand why the i % 2 produced this output ?

When i is 3 or an odd number, the i mod 2 test produces a remainder of one. When testing for a 0 or 1, is a 1 true or false?
Have a look at the test results again and let us know in the comments if you understand this code and why it created the output shown above.

What should the break; code below produce ?


// Example program
#include <iostream>

int main()
{
    for ( short int i = 0; i<9 ; i++){
        
        if ( i % 2 )   // 0 = false, 1 = true
            break;
            
        std::cout << "i = " << i << std::endl; 
    }
}


This break code produces a 1 or 0?

Would it surprise you if we said it produced a 1 and that’s all she wrote? ha ha.
  • Home Work
  • Write a c++ program from memory that demonstrates the break command
  • Remember the % is the mod command and returns a remainder or 0

Top