Wednesday, 29 August 2012

Loops - Apex Language Fundamentals

To repeatedly execute a block of code while a given condition holds true, use a loop. Apex supports do-while, while, and for loops.

While Loops

A do-while loop repeatedly executes a block of code as long as a Boolean condition specified in the while statement remains true. Execute the following code:
Integer count = 1;
do {
    System.debug(count);
    count++;
} while (count < 11);
The previous example executes the statements included within the do-while block 10 times and writes the numbers 1 through 10 to the debug output.

Output of the do-while loop 
The while loop repeatedly executes a block of code as long as a Boolean condition specified at the beginning remains true. Execute the following code, which also outputs the numbers 1 - 10.
Integer count = 1;
while (count < 11) {
    System.debug(count);
    count++;
}

For Loops

There are three types of for loops. The first type of for loop is a traditional loop that iterates by setting a variable to a value, checking a condition, and performing some action on the variable. Execute the following code to write the numbers 1 through 10 to the output:
for (Integer i = 1; i <= 10; i++){
    System.debug(i);
}
A second type of for loop is available for iterating over a list or a set. Execute the following code:
Integer[] myInts = new Integer[]{10,20,30,40,50,60,70,80,90,100};
for (Integer i: myInts) {
 System.debug(i);
}
The previous example iterates over every integer in the list and writes it to the output.

Output of a for loop that iterates over a list of integers 

1 comment: