do-while loop:
The do-while loop starts with doing a task once. Next, a condition is verified. If the condition is true,
it runs the task again. If it’s false, the loop stops.
The do-while loop is a control flow statement in programming that executes a block of code at least
once and then repeatedly as long as a specified condition is true.
Syntax:
Do {
//run this block of code
} while(condition);
Integer count = 5;
do {
System.debug('Count: ' + count);
count--;
} while (count > 0);
Integer i = 1;
// Do-while loop
do {
// Body of do-while loop
// Print statement
System.debug('Hello World');
// Update expression
i++;
}
// Test expression
while (i < 6);
Integer sum = 0;
Integer testNumber = 1;
do {
sum += testNumber;
testNumber++;
} while (testNumber <= 10);
System.debug('Sum: ' + sum);
For Loops:
The traditional for loop
The list or set iteration for loop
The traditional for loop:
In Java, a for loop is a control flow statement that allows you to execute a block of code repeatedly,
with a specified number of iterations or until a certain condition is met.
for (initialization; Boolean_exit_condition; increment);
for (Integer i = 0; i < 5; i++) {
System.debug('Iteration: ' + i);
}
----------------------------------------
for (Integer i = 1; i <= 15; i++){
System.debug('Hello World');
}
-----------------------------------------
Integer sum = 0;
// for loop begins
// and runs till x <= 20
for (Integer x = 1; x <= 10; x++) {
sum = sum + x;
}
System.debug('Sum: ' + sum);
//multiplication table
Integer n = 17;
for (Integer i = 1; i < 10; i++) {
System.debug(n+' * '+i+' = '+n*i);
}
List<Integer> numbers = new List<Integer>{1, 2, 3, 4, 5};
for (Integer i = 0; i < 5; i++) {
//for (Integer i = 0; i < numbers.size(); i++) {
numbers[i] = numbers[i] * 2;
System.debug('Doubled Number: ' + numbers[i]);
-------------------------
for(Integer i=1; i<=10; i++ ){
if(Math.mod(i, 2) == 0){
System.debug(i + ' Is even number');
}
else{
System.debug(i + ' Is odd number');
}
}
------------------------
//find the sum of even numbers from 1 to 10
Integer totalSum = 0;
List<Integer> listOfNumbers = new List<Integer>();
for (Integer i=1; i<=10; i++){
listOfNumbers.add(i);
}
System.debug('listOfNumbers: ' +listOfNumbers);
for(Integer i=1; i<listOfNumbers.size(); i++ ){
if(Math.mod(listOfNumbers[i], 2) == 0){
totalSum = totalSum + listOfNumbers[i];
System.debug('totalSum value is: ' +totalSum);
}
}
System.debug('Find sum: '+ totalSum);
break:
Branching statements allow you to alter the flow of execution in a program dynamically.
Java supports break statements.
for (Integer i = 0; i < 100; i++) {
if (i == 5) {
System.debug('i is 5');
break; // Exits the loop if i is 5
}
System.debug('i value is = ' + i);
}