Course Content‎ > ‎Session 3‎ > ‎

Loops

What is a loop?

In loop, a sequence of statements is executed, until some condition for termination of the loop is satisfied. If you need to repeat an operation a fixed number of times or until a specific goal has been attained or continue until the initial condition has changed, you will need loops. In programming there are two types of loops:

Determinate Loops: If you have to repeat a block of statements a particular number of times then Determinate Loop is implemented. This type of loop is used, when exact number of iterations to be performed, is known beforehand. In designing a Determinate Loop a conditional test is performed.

Indeterminate Loops: These are the loops that keep on repeating an operation depending on the results obtained within the loop. These loops are not executed a fixed number of times and are used where exact number of iterations required is not known in advance.

A loop consists of a control statement and body. Control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop. Depending on the position of the control statement in the loop, a loop structure may be classified as:
Entry-controlled loop: In this loop, control conditions are tested, before the start of the loop execution. If control condition is not satisfied, then the loop will never get executed.

Exit controlled loop: In this kind of loop, control condition is tested at the end of the loop body.  Here, even if the test condition is not satisfied, still the loop gets executed at least once.

A looping process includes four steps:
Setting and initialization of the counter 
  1. Setting and initialization of the counter
  2. Execution of statements in the loop  
  3. Test for specified condition for the execution of the loop  
  4. Incrementing or decrementing the counter

Java language provides the following loop constructs for performing the loop operations: while, do while, and for

while Loop 

Syntax of the while statement is:

  while(test condition)
  {
  body of the loop
  }

while is an entry-controlled and indeterminate loop.  Given below are the steps for executing a while loop:

  1. Test condition is evaluated
  2. If test condition is true, then the body of the loop is executed.
  3. Body of the loop executes repeatedly, till the test condition becomes false
  4. Control is transferred out of the loop

Here is an example illustrating while loop:

class countDisp { public static void main(String args[ ]) throws Exception { /* ans is initialized to y, so that loop body can be executed
at least once */
char ans = ’y’; int count; count = 0; while(ans == ’y’ || ans == ’Y’) { count = count + 1; System.out.println(“count is " + count); System.out.println(" do you wish to continue, press y for yes”); ans = (char)System.in.read(); } } }

throws Exception clause has to be added to the main() method, because System.in.read() method is used in the main() method for accepting input from the user. In the above program, as long as the user inputs y or Y, the while loop continues and count is incremented by 1, with each iteration of the loop.

do while loop 

do statement is used to execute the body of the loop before the condition is tested. do...while is an exit-controlled and indeterminate loop. The test condition is evaluated at the bottom i.e. after the loop body. Even if the condition is false, the loop will get executed at least once.  General form of this statement is:

do { body of the loop } while(test condition);

In this kind of loop, when control reaches do, the program proceeds to evaluate the body of the loop first.  At the end of the loop, test condition in the while statement is evaluated. If condition is true, the program continues to execute the body of the loop once again and continues as long as the condition is true and exits when the condition becomes false. When loop is terminated, control goes to the statement immediately after the while statement. Here is an example of a do...while loop:

do { System.out.println("Employee Name : "+ Emp_Name); System.out.println("Employee Salary : "+ Emp_Sal); System.out.println("Press Y or y if you wish to see the salary of the next employee"); /* to accept the character input from the user */ ans=(char)System.in.read(); } while(ans='y' || ans='Y'); 
/* if the character input by the user is y or Y the next iteration 
takes place */

In the above code, the employee name and salary is displayed. If the user inputs y or Y, the next employee name and employee salary is displayed, otherwise the control exits out of the loop.

for Loop 

Simple for loop is an entry-controlled loop, which provides a more concise loop control structure. General form of for loop is:

for (initialization; testcondition; increment/decrement) { body of the loop }

Here is an example of a for loop:

int arr[] = {12, 34, 56, 1, 43, 65, 2, 57, 24}; int i; i = arr.length; /* to determine the number of elements in the array */ /* this loop will display all the elements of the array arr */ for(i = 0; i < arr.length; i++) { System.out.println(arr[i]); /* for displaying ith array element */ }

In this for loop, count has been initialized to 1, test condition is count <= 10. As long as the test condition is true, the loop body will get executed. After each loop iteration, count is incremented, as a result of which the value of the count changes.  As long as value of the count is less than or equal to 10, the loop body will get executed. The moment count will become 11, the control will move out of the loop.

In the above example, count is the control variable, responsible for execution of for loop. Initialization of control variable is done using assignment statement i.e. count = 1. Value of control variable is tested using test condition. The test condition is a relational expression. In the above example, count <= 10 is the test condition. As long as the test condition is true, the loop body is executed i.e. as long as count is not greater than 10, the loop body will get executed.

When the body of the loop is executed, control is transferred back to the for statement. Control variable is incremented or decremented as the case may be. In the above example the control variable count is incremented i.e. count++. The new value of control variable is tested again to see if it satisfies the test condition. When test condition becomes false, loop is terminated. Control is transferred out of the loop and the statement immediately after the for loop is executed. In the for loop, if the loop body contains only one statement, then braces are optional otherwise for two or more statements, braces are needed.

Additional features of for loop:

1. More than one variable can be initialized at a time in the for statement.  For example, 
  for (a = 10, b = 0; b < 10; b++)

2. Increment section can have more than one variable. For example,
  for (a = 10, b = 0; b < 10; b++, a--)

3. Test condition may have any compound relation and testing need not be limited only to loop control variable. For example,
  for(i = 0; i < 20 && sum < 100; ++i)

In the above example, the loop is executed as long as i is less than 20 and sum is less than 100.

4. Arithmetic expression can also be used in the assignment statements of initialization and increment section. For example,
    for(x = (m + n) / 2; x > 0; x = x / 2)

5.  One or more sections can be omitted in a for loop. For example,  

  m = 5;
  for(; m != 100;)
    {
Format.printf(“%d\n”, m);
m = m + 10;
  }

6.  for loop can also be used to set time delays. For example,

  for(j = 1000; j > 0; j = j - 1)
; /* null statement */

The loop gets executed 1000 times without any display because the body of the loop contains a semicolon i.e. ;  This is called as a null statement.

7.  Nesting of for loops is allowed in Java. Example of nested for loops is given below:

public class MulTable { public static void main(String args[]) { int i, j, prod; /* to print multiplication table of the numbers 1 to 10 */ for(i = 1;i <= 10;i++) { // to print multiplication table of a number from 1 to 10 for(j = 1;j <= 10;j++) { prod = i * j; /* System.out.print( ) is used to print multiplication table for a number in the same line */
System.out.print(prod + "\t"); } /* to print a blank line so that multiplication table forthe next number is printed in the next line */
System.out.println( ); } } }


The example given above, will print the multiplication table for 1 to 10. Given below is another example demonstrating the nesting of for loops:  

int i, j; /* outer loop, used for producing the numbers 1, 2, 3, 4, 5 */ for(i = 1; i < 6; i++) { /* inner loop, used for displaying a number that many number of times */ for(j = 1; j <= i; j++) { System.out.print((i)); /* for displaying the number */ } System.out.println(); /* for moving to the next line */ }

The code given above will display the following output:
    1
    22
    333
    4444
    55555

Comments