Java While and for loops
Java While and for loops
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);
-----------------------------------------
Integer sum = 0;
//multiplication table
Integer n = 17;
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.
if (i == 5) {
System.debug('i is 5');
break; // Exits the loop if i is 5
}
System.debug('i value is = ' + i);
}