5.3 Using while loop

The concept

While loop is much less frequently used than for loop. But you will still find it useful in many scenarios. And it is easy to be understood. Here is the sample code:

Integer i = 0;
Integer sum = 0;
while(i < 10) 
    sum += i;

System.debug('Sum is: ' + sum);

The sum should be 45 (0 + 1 + 2 + … + 9)

A bit explanation

While loop can be viewed as a simplified version of for loop. It doesn’t have initialisation and afterthought, leaving only the escape condition. So when the escape condition is true, it will always be executed.

Should be pretty easy to understand.


Try to calculate 3 + 6 + 9 + … + 99 using while loop

Next Post

5.4 Break and Continue

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *