function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Abhishek Sharma 527Abhishek Sharma 527 

apex time limit exceeded error

Hello I'm running this program in execute anonymous window in dev console and it's giving apex time limit exceeded error.
my code - 

Integer count = 5;
Integer i = 0;
Integer sum=0;

while(i<count){
    sum = sum +i;
}
i++;
system.debug(sum);

I'm unable to figure out the issue, Please help.
Best Answer chosen by Abhishek Sharma 527
Sashank Villa 4Sashank Villa 4
You are incrementing the loop variable(i) outside of while loop so each time it checks for i<count it will always be less than count.
modify the code as below

Integer count = 5;
Integer i = 0;
Integer sum=0;

while(i<count){
    sum = sum +i;
    i++;
}

system.debug(sum);

All Answers

Sai PraveenSai Praveen (Salesforce Developers) 
Hi Abhishek,

Ideally i++ should be inside the While Loop I guess. as below.
Integer count = 5;
Integer i = 0;
Integer sum=0;

while(i<count){
    sum = sum +i;
    i++;
}
system.debug('value of count'+sum);

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,

 
Sashank Villa 4Sashank Villa 4
You are incrementing the loop variable(i) outside of while loop so each time it checks for i<count it will always be less than count.
modify the code as below

Integer count = 5;
Integer i = 0;
Integer sum=0;

while(i<count){
    sum = sum +i;
    i++;
}

system.debug(sum);
This was selected as the best answer