22/01/2008


Last class we studied about the for loop. Its syntax is


for (initialization; condition; iterator ) body;


When using this version of the for statement, keep in mind that:

* The initialization expression initializes the loop; it's executed once, as the loop begins.

* When the condition evaluates to false, the loop terminates.

* The iterator expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.


There are 2 more kinds of loop.


1) while loop

2) do – while loop



1) while loop

It is similar to for loop.Its syntax is


while (condition) body;


Here the condition is a boolean expression. If the condition is false before the execution of the loop, then body will not be executed. Else body will be executed until the condition turns false.



2 new unary operators ( ++(increment),--(decrement))


Y++ ; (post increment)

++Y ; (pre increment)


5++ ; (y+1)++; (y++)++ ; etc.. are wrong usages and will give compile time errors.


Y--; (post decrement)

--Y; (pre decrement)


Y++ + ++Y such expressions have more than 1 side effects. And the order of execution is defined by the associativity of the java language.


The usages like z=y++; y=y++; are bad programming practices.




Eg ) Now we will look into a program to find the integer square root of an integer X.


One way is like


for (y=0; y*y<=x; y++) ; y = y-1;

Note the ‘;’ at the end of the ’for loop’. When the ‘for loop’ is executed till the condition holds. When y*y > x , it will come out. So the required answer is (current value of y) – 1; That is the reason for y = y-1;


But the above algorithm is not efficient. So a faster algorithm is


The code below takes x = 25.

int low, high, mid;

int x = 25;

low = 0;

high = x;

while(low<high){

    mid = (low + high)/2;

    if(mid*high<x) low = mid;

    else high = mid;

}

The code above tries to reduce the interval by half, in each iteration.

However, the above code contains a bug.