All Products
Search
Document Center

Loop structure

Last Updated: Sep 09, 2021

Overview

Cava allows you to use a for loop to perform an operation multiple times. Cava does not support while loops or do while loops.

for loop

Syntax:

for (initialization; condition; increment) {
    // The loop body, which represents the operation to be performed.
}

Notes:

  • The initialization part is executed first. This step allows you to declare and initialize loop control variables. The initialization part is optional. However, the semicolon (;) must be passed in even if the initialization part is not specified.

  • Next, the condition is evaluated. If the condition is met, the loop body is executed. If the condition is not met, the loop body is not executed, and the for loop ends.

  • Each time after the loop body is executed, the increment statement updates the loop control variables and then checks whether the condition is met.

  • In the loop body, you can use "continue" to terminate a single execution of the loop body in advance.

  • In the loop body, you can use "break" to terminate the entire for loop in advance.

  • Nested for loops are supported.

Sample code:

class Example {
    static int main() {
        int a = 0;
        for (int i = 0; i < 10; ++i) {
            if (i == 1) {
                continue;
            }
            if (a > 10) {
                break;
            }
            a += i;
        }
        int j = 0;
        for ( ; i < 10; ++j) {
            a += j;
        }
        return a;
    }    
}