switch, break, and continue

The switch statement is really just a specific type of if/else statement. It's used when you want to compare an integer value to multiple other constant integer values. Here's an example:
int n = 9;
switch(n){
    case 8: //code;
        break;
    case 9: //code;
        break;
    case 10: //code;
        break;
    default: //code
}
This switch statement is comparing n to all of the cases. If the case is satisfied, the following code for that case will execute. Then, the break keyword causes the program to break out of that case. The break keyword is optional, but if you don't have it then the program will continue executing onto the next case. Also, there's a default case that will run in case none of the previous cases are satisfied.

The break keyword can also be used to exit a while, do, or for loop.

The continue keyword will cause the program to jump to the end of the loop body and begin the next iteration of the loop (if the conditions are satisfied).

No comments:

Post a Comment

Searching Algorithms

Linear/Sequential Search A linear/sequential search algorithm looks at each element in the array until it finds what it's looking for. ...