Java loops

  • Post author:
Download PDF
Advertisement

Java loops

A type of control structure that repeats a statement or set of statements is known as loops.

In Java programming language there are three basic iteration statements which are for, while and do-while. These three statements generally called loops. A loop repeatedly executes the same procedures which write into the loop body until a termination condition is met. A loop used when a programmer needs to execute a large iteration process, and he wants to save your time writing one code repeatedly. Every programming language has loops concepts, without this concept languages are not efficient for programmer persons. For example, a programmer is going to write a code for 10,000 students to store their name only. If a programmer not used loops then there is much complex to initialize the 10,000 variables and the program will use more memory space to store the code. Because the number of code lines will increase. Without loops, we can store names in variables individually one by one. But this technique is more complex for the programmer to initialize the values of the variables. In this complex situation loops is the best option for programmers. The programmer used loops syntax which is very short and can initialize the 10,000 or more variables in a few seconds. Each loop has three main parts.

  • Initialization / Declaration part
  • Condition part
  • Increasing / Decreasing

 

Initialization / Declaration:

In this part, one variable initializes or declare for looping purpose. This variable is used to initialize the starting point of the loops. It generally initializes or declares the start of the loops.

Condition:

This part of the loop is more important for any loops. This part is mandatory for terminate the loops. If this part is not written then loops work for infinity time which will not terminate. This error called logical error. This part holds a minimum of two variables one used to terminate the loop and second used for comparison. This second variable gradually increases or decreases. When condition part matches the given condition values or true then loops will terminate. If the programmer leave empty the condition part then loops will work for infinity time and will not terminate. All loops depend on conditions. Therefore condition part is important for any loops.

Increasing / Decreasing:

Increasing / Decreasing part of the loops is also important. Because this part works for moving the loops repeatedly in increasing or decreasing manners.

  • While Loop

Java’s most fundamental looping statement is while loop. It works until when its controlling expression is true. In while loop conditions check first if the condition is true then the body of the loop executes, if condition is false then the body of the loop is not executed. While is Java built-in keyword which used to initialize the while loop. This loop is useful when the number of iterations not known in advance.

The general syntax of while loop:

   while(condition part)
   {
      // body of loop or statements
   }

Note:   The curly braces are unnecessary when any loop has a single statement. If the loop has multiple statements then braces are necessary.

Flowchart of while loop:

while loops flowchart

Example program of while loop:

Here is a sample program which shows to five (05) times on console using a while loop.

   class Whileloop
   {
      public static void main(String args[])
      {
        int var = 5;
        while(var > 0)
        {
          System.out.println("zitoc " + var);
          var--;
        }
        System.out.println(“loop terminate:”);
      }
   }

Output:

zitoc 5

zitoc 4

zitoc 3

zitoc 2

zitoc 1

loop terminates:

 

Here is a sample program that gets an integer value and shows its factorial using while loop in java language.

   import java.util.Scanner; // import scanner class

   class facPro
   {
      public static void main(String args[])
      {
        long i, j, k;
        i = 1;
        j = 1;
        System.out.println(“Enter an integer number for factorial:”);
        Scanner input = new Scanner (System.in);
        k = input.nextLong();
        while (i <= k)
        {
          j = j * i;
          i = i + 1;
        }

        System.out.println(“Factorial of ” + k + “ is ” + j);
      }
   }

Output:

Enter an integer number for factorial:

8

Factorial of 8 is 40320

  • Do-while Loop

The do-while loop is an iterative control in Java programming language. It works until when its controlling expression is true. This loop executes one or more statements while the given condition is true. This loop is also useful when the number of iterations not known in advance. In a while loop when conditional expression initially false then not executed body of the loop at all. However, sometimes we want to execute a while loop body at least once time, even if the condition is false. In this situation, java language provides the do-while loop which execute the body of the loop at least once time even conditional expression is true or false. Because do-while

Advertisement
loop conditional expression checked at the end of the loop. Do-while loop general syntax.

   do
   {
     // body of loop
   } while (condition);
Do It is the java reserved keyword which used to indicate the do-while.
Loop body It is the second part of the do-while loop. Which contents lie inside the curly braces called loop body. It can be a single line or multiples lines. Each statement that writes inside the loop body is a part of the body.
Condition It is the third or last part of the loop. The condition is given as a relational expression. If the condition is true then the body of the loop will be executed. If the condition is false then the body of the loop will not executed.
Flowchart of the do-while loop:

do while loops flowchart

First of all loop body is executed if the condition is true or false. Because control of the program starts from upper to lower level. Therefore the body of the loop execute first because of its position at the first level. Then second, the condition will be checked if the condition is true then control of the program again enter the body of the loop and will again execute all statements of the loop body. This process continues as long as the condition remains true. The do-while loop terminates when the condition false. Therefore the do-while loop executed at least one time if the condition is false or true.

Example program of the do-while loop:

   class DoWhileLoop
   {
      public static void main(String args[])
      {
         int var = 5;
         do
         {
            System.out.println("zitoc " + var);
            var--;
         } while(var > 0);
	    System.out.println(“loop terminate:”);
      }
   }

Output:

zitoc 5

zitoc 4

zitoc 3

zitoc 2

zitoc 1

loop terminates:

Difference between Do-while and while loop:
While loop Do-while loop
In a while loop, the condition will check before the body of the loop. In the do-while loop, the condition will check after the body of the loop.
While the loop never executed if the condition is false in the beginning. If the condition is true or false, the do-while loop body will be executed at least one time.
It also called the pretest loop. It also called the post-test loop.

 

  • For Loop

For the specified number of times for loop executes one or more statements. It is the simplest loop structure. It is also called the counter-controlled loop. This loop used frequently by programmers. It is a versatile and powerful construct.

The general syntax of for loop:

   for(initialization; condition; increment/decrement)
   {
	//Body of the loop
   }
Initialization In this part, one variable initialize or declare for looping purpose. This variable is used to initialize the starting point of the loops. It generally initializes or declare the start of the loops.
Condition This part of the loop is more important for any loop. This part is mandatory for terminate the loop.
Increment /

Decrement

This part is used for changes in counter variables after each execution of the loop.
Loop Body Statements that enclosed curly braces {} called loop body.
Parts of the for loop

for loops parts

Flowchart of for loop:

for loops flowchart

The initialization part of the loop depends on the number of the iterations. First of all, initialize the variables and then control go for condition part of the loop. If condition false then the body of the loop will not be executed. When control entered the initialization part then the initialization part executed only for one time and then control go next. In the end, control goes into increment or decrement part and change the value of the variable and then again go to condition part and check the next value expression. When the condition goes false then control goes to outside the body of the loop and the loop will terminate.

Example program of for loop:

   class DoWhileLoop
   {
      public static void main(String args[])
      {
         for (int var=5; var>0; var--)
         {
            System.out.println("zitoc " + var);
         }
	    System.out.println(“loop terminate:”);
      }
   }

Output:

zitoc 5

zitoc 4

zitoc 3

zitoc 2

zitoc 1

loop terminates:

Here is another sample program:

Write a program that inputs table number and length of the table and then displays the table using for loop.

   import java.util.Scanner; // import scanner class

   class tableZitoc
   {
      public static void main(String args[])
      {
         long tab, len, c;
         System.out.println(“Enter an integer number for table:”);
         Scanner input = new Scanner (System.in);
         tab = input.nextLong();
         System.out.println(“Enter an integer number for table length:”);
         Len = input.nextLong();
         for(c=1; c<=len; c++)
         {
	   System.out.println(tab + “ * ” + c + “ = ” + tab*c);
         }
      }
   }

Output:

 

Enter an integer number for table:

3

Enter an integer number for table length:

10

3 * 1 = 3

3 * 2 = 6

3 * 3 = 9

3 * 4 = 12

3 * 5 = 15

3 * 6 = 18

3 * 7 = 21

3 * 8 = 24

3 * 9 = 27

3 * 10 = 30

 

If-else Statement in java

Advertisement