Thursday, August 16, 2007

while equivalent for loop

Today while doing some programming stuff I found one good thing which I never encountered in the past for programming language loops. I know everyone who has done programming used for and while loop some time or the other.

In this post I am just going to give simple example to convert a for loop into while.

For loop

for(Initialization;Condition;INCREMENT/DECREMENT)
{

statements;
}

While equivalent

Initialization
while(Condition)
{
statements;
INCREMENT/DECREMENT

}


example:
int i =0
for(System.out.println("initialization");i <10;System.out.println("increment/decrement"))
{

System.out.println("Inside loop");
}

equivalent while loop:


int i =0;
System.out.println("initialization");
while(i<10)
{

System.out.println("Inside loop");

System.out.println("increment/decrement"); // this should be the last statement in the loop
}

No comments: