Search code examples
for-loopsalesforceinfinite-loopapex

How can I adjust my program to close the loop and print the expected results?


This is the error I'm getting. I believe this means its caught in an infinite loop:

Line: 2, Column: 1 System.LimitException: Apex CPU time limit exceeded

The code below is what I've tried so far.

for(integer i = 7; i <= 15; i + 2){
    System.debug(i);
}

I expect it to print the following: 7 9 11 13 15

Instead it is getting stuck in an infinite loop.


Solution

  • Your diagnosis is correct; your code is caught in an infinite loop.

    This is the case because of the third clause of your for loop:

    for(integer i = 7; i <= 15; i + 2){
    

    i + 2 is an expression, but it doesn't change the value of i. You want to do i += 2 here. See Apex Operators for the details.