Although for and while are both loops, there are few differences in the syntax and the usage.
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 isfalse
.
- Although
for
andwhile
are different, everyfor
loop can be rewritten usingwhile
and everywhile
can be rewritten usingfor
.
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));
The major differences betweenandare:Below are few examples which are written usingandThe same program usingThis program written usingSame program written usingSame program written using
for Loop In Java
do while Loop In Java