For loop

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.

  1. Initiate the value
  2. Check the condition.
  3. If the condition is true the body statements run.
  4. Then the loop is execute.
  5. 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);
	}

}

Leave a Reply

Create your own website, free on WordPress.com.Create your own website.
Start free