Previous | Home | Next |
The initialization step is executed first, and only once. The initialization expression initializes the loop it's executed once, as the loop begins. Next the condition expression evaluates to false, the loop terminates. The increment expression is call after each iteration through the loop, it is perfectly acceptable for this expression to increment or decrement a value.
syntax :
for(initialize; condition; increment/decrement ) { staements ; }
Example :
class For { public static void main(String args[]) { int n,i; n=5; for(i=1;i<=n;i++) { System.out.println(i); } } }
output :
1 2 3 4 5
A while loop is a control structure that allows you to repeat a task a certain number of times. If the condition expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.
syntax :
initialize; while(condition) { statements ; increment/decrement; }
Example :
class While { public static void main(String args[]) { int i,n,fact; n=5; fact=1; i=n; while(i>=1) { fact=fact*i; i--; } System.out.print("factorial is "+fact); } }
output :
120
Previous | Home | Next |