How to use continue in a loop?

072

Using continue in a Loop

The continue statement is a control flow statement used in programming loops, such as for and while loops, to skip the current iteration of the loop and move on to the next one. It is particularly useful when you want to selectively execute certain parts of the loop body based on certain conditions.

Here's how you can use continue in a loop:

Basic Syntax

The basic syntax for using continue in a loop is as follows:

while <condition>:
    # some code
    if <condition>:
        continue
    # more code

or

for <variable> in <sequence>:
    # some code
    if <condition>:
        continue
    # more code

In both cases, if the if condition is true, the continue statement will be executed, and the current iteration of the loop will be skipped, moving on to the next iteration.

Example: Skipping Odd Numbers

Let's say you have a list of numbers and you want to print only the even numbers. You can use the continue statement to skip the odd numbers:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for num in numbers:
    if num % 2 != 0:
        continue
    print(num)

Output:

2
4
6
8
10

In this example, the continue statement is used to skip the odd numbers (where num % 2 != 0 is true) and only print the even numbers.

Example: Skipping Certain Directories

Suppose you have a directory structure with both regular files and directories, and you want to list only the files, skipping the directories. You can use the continue statement to achieve this:

#!/bin/bash

for item in *
do
    if [ -d "$item" ]; then
        continue
    fi
    echo "$item"
done

In this example, the if [ -d "$item" ] condition checks if the current item is a directory. If it is, the continue statement is executed, and the current iteration is skipped, moving on to the next item in the directory.

Visualizing the Concept with a Mermaid Diagram

Here's a Mermaid diagram that illustrates the flow of control when using the continue statement in a loop:

flowchart LR Start --> Loop Loop --> Condition Condition --> True --> Skip_Iteration Condition --> False --> Execute_Code Skip_Iteration --> Next_Iteration Execute_Code --> Next_Iteration Next_Iteration --> Loop

The diagram shows that when the continue statement is executed, the current iteration is skipped, and the loop moves on to the next iteration.

In summary, the continue statement is a powerful tool in programming loops that allows you to selectively execute certain parts of the loop body based on specific conditions. It can help you write more efficient and readable code by avoiding unnecessary computations or actions.

0 Comments

no data
Be the first to share your comment!