Although for and while are both loops, there are few differences in the syntax and the usage.
The major differences between
for
and
while
are:
for
loop is used when we know the number of iterations we have to perform i.e. we know how many times we need to execute a loop.
while
is used when you are not sure about the iterations but you know what the condition is and then you can loop that block until the condition is false
.
- Although
for
and while
are different, every for
loop can be rewritten using while
and every while
can be rewritten using for
.
Below are few examples which are written using
while
and
for
.
Print numbers till given input using for
int input = 5;
for(int i = 1; i <= input; i++ )
{
System.out.println(i);
}
The same program using
while
.
int input = 5;
int i = 1;
while(i <= input)
{
System.out.println(i);
i++;
}
Print numbers from given number till the next multiple of 10. e.g., if input is 5 it should print 5, 6, 7, 8, 9, 10 or if input is 27 it should print 27, 28, 29, 30 or if input is 40 then it should print 40.
This program written using
for
.
int input = 5;
for(int i = input; ( i == input || ((i - 1) % 10 != 0)); i++ )
{
System.out.println(i);
}
Same program written using
while
.
int input = 5;
int i = input;
while(i == input || ((i - 1) % 10 != 0))
{
System.out.println(i);
i++;
}
Same program written using
do-while
.
int input = 5;
int i = input;
do
{
System.out.println(i);
i++;
}while(((i - 1)% 10 != 0));