‹‹ Previous
Next ››
Java 'For' Loop
- 'For' loop is used to repeat a set of instructions.
- It has a initial condition for staring of loop.
- It has a testing condition for stopping the loop.
- It has an increment condition for incrementing the initial value.
Example
Program: summation of numbers ( 1 to 10) i.e. 1+2+3+4+5+6+7+8+9+10
class CountProg {
public static void main(String args[])
{
int i, sum=0;
for(i=0; i<=10;i++)
{
sum = sum + i;
}
System.out.println("Summation of numbers (1 to 10) is"+sum);
}
}
Explanation of the program
- 'For' loop has initial condition i=0. Repetition starts with value of i=0.
- 'For' loop has termination condition i<=10. Repetition in the loop terminates when value of i reaches to 10.
- 'For' loop has increment condition i++ (i.e. i=i+1). This condition increments value of i by 1.
- When 'For' loop has value of i=10, repetition in the loop stops.
Output of the program
Summation of numbers (1 to 10) is 55
‹‹ Previous
Next ››