Friday, 30 October 2015

Difference between For loop, While loop and Repeat-until loop

Technically its very important to know when to use for, while and repeat-until loop while we are coding based on the requirement. Since all the 3 loops are used to perform incremental task. Developers must be properly knowing when to use For loop, while loop and repeat-until loop.

So, the major reason between these three loops is:

1. For loop:

For loop is used if we know the number of times the statement needs to be executed.

FOR var := 1 TO 5 DO

BEGIN
 //statement
END;

output:

//statement
//statement
//statement
//statement
//statement

In this case the statement is executed 5 times.

2. While loop:

While loop will not execute if the condition is false.

var := 0;

WHILE var <> 0 DO BEGIN
  var := var - 1;
 //statement
END;

output:

In this case the condition is failed. So while loop never gets executed.


3. Repeat-Until loop:

var := 0;

REPEAT
  var := var - 1;
  //statement
UNTIL var <> 0;

Output:

//statement

In this case as you see whether the condition is true/false but the statement is executed at least once.




No comments:

Post a Comment