for looping statement
for statement is used to execute a statement or a group of statements repeatedly for a known number of times. The general form is
for(variable=initial value;test condition;increment or decrement)
{
Body of the loop;
}
next statement;
|
When the for statement is executed the value of the control variable is initialized and tested with the condition. If the value of the test condition is true, the body of the loop will be executed and the control is transferred to the for statement. Then the value of the control variable is incremented or decremented. When the test condition becomes the control is transferred to next statement.
The body of the loop executed repeatedly as long as the test value is true.
Flow Diagram
Example
Class Test
{
public static void main(String args[])
{
int i,sum;
sum=0;
for(i=1;i<=100;i++)
{
Sum=sum+I;
}
System.out.println(“Sum=”+sum);
}
}
On seeing the for statement the computer takes the initial value 1 to the control variable i and is checked with the test condition i<=100. If its value is true the body of the loop sum=sum+i is executed and the control is transferred to the for statement. Then the value of the control variable is incremented because of i++ and the value is checked with test condition i<=100. If true the body of the loop is executed. This process continues till the test condition i<=100 becomes false. When it becomes false the control is transferred to next statement following the for statement. In our case the value of the sum is printed.
No comments:
Post a Comment