A “For” Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a “While” loop.

- Initiate the value
- Check the condition.
- If the condition is true the body statements run.
- Then the loop is execute.
- If the condition is fail the loop does not execute.
Change while loop to For loop:-
public class Factorial{
public static void main(String[] args)
{
int bag = 0;
int day = 1;
int rice =1;
while(day<=30)
{
bag = bag+rice;
rice = rice*2;
day++;
}
System.out.println(bag);
}
}
For loop:-
public class Factorial {
public static void main(String[] args)
{
int bag=0;
int rice =1;
int day=1;
for(day=1;day<=30;day++)
{
bag= bag+rice;
rice=rice*2;
}
System.out.println(bag);
}
}