Iteration Constructs IN JAVA - 23 - 10 - 23
Iteration Constructs IN JAVA - 23 - 10 - 23
Iteration statements
The iteration statements allow a set of instructions to be performed repeatedly
until a certain condition is fulfilled. Java provide three kinds of loops:
for loop (entry controlled loop)
while loop (entry controlled loop)
do-while loop (exit controlled loop) Parts of a loop
4. The body of the loop - The statements that are executed repeatedly
form the body of the loop.
for( ; ; )
System.out.println(“Endless for loop”);
b. Empty loop or Null loop or Delay loop
If a loop doesnot contain any statement in its loop- body, it is said
to be an empty loop.
Example: for(i=1;i<=100;i++);
Int i,s=1;
System.out.println(s);
c. Declaration of variables inside loops and if
A variable declared within an if or for/while/do-while statement
cannot be accessed after the statement is over.
Initialization;
while(test expression)
{
Loop body
Update expression
}
Nested loop
A loop that contains another loop in its body is called nested loop. The
inner loop must terminate before the outer loop.
Comparison of Loops
The for loop is appropriate when you know in advance how many times
the loop will be executed.
The while loop is preferred when you don’t know in advance how many
times the loop will be executed.
do while loop should be preferred when you are sure to execute the loop
body at least once.
Jump statements
Java has three statements that perform an unconditional branch
•return
•break
•continue
System.exit() is used to come out of a program.
The return statement is used to return from a function.
Difference between break and continue
Assignments:
Identify all errors in the following iterative statements.
(i) for (int i=5; i>0; i++)
{
System.out.println(“Java”);
}
Give the output of the code given below:
1. for (int i = 1; i <= 5; i++)
{
System.out.print(i + " ");
}
5. int sum = 0;
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) {
sum += i;
}
}
System.out.println(sum);
Solution 12: 6