When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop.
Syntax:
for(statement 1;statement 2;statement 3)
{
//
//
//
}
Statement 1 :is executed (one time) before the execution of the code block.
Statement 2 :defines the condition for executing the code block.
Statement 3: is executed (every time) after the code block has been executed.
Example:
for( int i=0; i<5; i++)
{
System.out.println(i);
}
Example program:
public class For
{
public static void main(String[] args)
{
int box = 6012374;
int total = 0;
int count = 0;
//while(box>0)
for (box=6012374; box>0; count++) //for loop
{
System.out.println("Hi");
int rem = box%10;
total = total + rem; //4 3 2 1
box=box/10;
//count++;
}
System.out.println("Count of Digits " + count);
System.out.println("Sum of Digits " + total);
}
}
Output:
