ICSE Class 9 Computer Applications
8. Iterative Constructs in java
​
01 Defination
Iterative statements allow a set of instructions to be performed repeatedly until a certain condition is fulfilled. The iterative statements are also called as loops or looping statements.
​
Java loop statement has 4 parts:
-
Initialization sets a loop control variable to an initial value.
-
Condition/test expression is a Boolean expression that tests the loop control variable. If condition is true, the loop continues to iterate. If condition is false, the loop terminates.
-
Update expression determines how the loop control variable is changed each time the loop iterates.
-
Body of the Loop The statements executed repeatedly whenever the condition is true.
​
02 Types of looping statement
​
entry controlled ( for , while ) – the condition is checked before entering the loop.
exit controlled ( do while ) – the condition is checked before exiting the loop
Note : do while loop is removed for this exam
​
​
03 Syntax of each loop
Syntax of for loop
for (initialization; testExpression; update)
{
// statements inside loop's body
}
​
Syntax of while loop
while (testExpression)
{
// statements inside loop's body
}
​
​
​
04 Programs
​
/* Program to display numbers 1 to 10 using for loop */
​class forEg
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{
System.out.println(i);
}
}
}
/* Program to display numbers 1 to 10 using while loop */
​class whileEg
{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
​
05 jump statements
​
While working with loops, it is sometimes desirable to skip some statements inside the loop or terminate the loop immediately without checking the test expression.
​
In such cases, break and continue statements are used.
​
The break statement in Java terminates the loop immediately, and the control of the program moves to the next statement following the loop.
​
The continue statement in Java skips the current iteration of a loop (for, while, do...while, etc) and the control of the program moves to the end of the loop. And, the test expression of a loop is evaluated.
​
/* Program for break statement */
class breakEg
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
if(i==1)
break;
System.out.println(i);
}
}
}
​
/* Program for continue statement */
class continueEg
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
if(i==2)
continue;
System.out.println(i);
}
}
}
​
06 Need of loops​
​
Thus the need of loops is to repeat the same, or similar, code a number of times.