Label: statement (loop or block of code)
Keywords to be used:
- Label: A unique string that is Used to define the name of the block or loop.
- Statement: It can be a loop or block.
- Break: Used to terminate the loop or block of code.
- Continue: Used to terminate or jump from the current iteration of the loop.
Label statement with for loops: In this section, the user will learn to assign a unique label to multiple loops. Also, we will use the break and continue keywords with the multiple loops. The below examples will demonstrate the use of labels using loops.
Example 1: Using the break keyword with labeled loops. Users can terminate the outer loop from the inner loop using the label.
Output: We can see that the outer loop terminates when the sum becomes greater than 12.
sum = 1 sum = 3 sum = 4 sum = 6 sum = 7 sum = 9 sum = 10 sum = 12
Example 2: Using the continue keyword with labeled loops. Users can jump to the outer loop from the inner loop using the label.
Output: When the ‘ a=2 and sum < 12’ condition executes true, it doesn’t print the sum as we are terminating that iteration of the inner loop using the ‘continue’ keyword. When condition inside if statement executes true, it will jump to the outer loop.
sum = 1 a = 1 sum = 4 a = 1 sum = 7 a = 1 sum = 10 a = 1 sum = 12 a = 2
Example 3: Using the label statement with a block of code. Users can terminate the execution of a labeled block using the break keyword.
Output: You can observe that code after the break keyword is not executed
This part will be executed out of the block