Objective-C:do while loop

Do while loop

This loop executes once even if the condition is false. Firstly, the statements inside the do block are executed and then condition is checked, if the condition is satisfied the counter moves back to the statements in the do block, otherwise loop is terminated.

Syntax:-

do{

……. Statements;

}while ( condition);

Program using do while loop.

Here, condition: 1>5 is false but, the statement inside the loop are executed once because, the condition is checked after executing the statements.

Difference between for, while and do while loop

In for loop, initialization, condition and update counter are all kept together in for statement and the order is also same. Whereas in While loop, only condition is kept under the while statement and the order is same. In both for and while, condition is checked first and then statements execute and if condition is false the loop terminates. But in case of do while loop, condition is checked at last when the statements execute once.

Creating infinite loop

A for loop will execute infinitely if no statement is passed inside for statement as shown below:

for (;;)

{

NSLog(@”this is an infinite loop”);

}

The program will be manually terminated by the user.

For in loop

It is an extension to for loop which does not requires counter. It is quite similar to that of foreach loop in C# that is, used for traversing of arrays, for example,

for (NSnumber *counter in anarray)

{

…….

……. Statements;

…….

}