Sunday, December 25, 2011

JAVA Programming : For Loop

JAVA For Loop


For loop in java is one of the most common type of loop. There are two types of for loop:
  1. Basic For loop 
  2. For Each loop  (Introduced in Java 5)
Basic For loop:
For loop declaration has there parts : initialization, termination condition, iteration expression. These parts are separated by semicolons.

Syntax of for loop:-


   for(initialization; condition; iteration){ 
      //set of statements
   }



Initialization part: The initialization part of for loop is executed only for the first when the loop begins. It lets you declare and initialize one or more variables of the same types. One thing to note when the declaring a variable in for loop is the scope of variable. If the variable is declared in the for loop the variable's scope is limited to the for loop.

Condition part: The condition part must be an Boolean expression. In condition part there cannot be multiple test condition but we can use logical operators to make a logical expression that evaluates into a Boolean result. The body of the for loop is executed only if the condition is true else the loop is terminated.

Iteration part: After every iteration of  for loop's body, the iteration part is executed. This is the part where you can set the change in loop control variable. The given example will give a better understanding of working of for loop.

Example of for loop:- This is a very simple example of for loop which will take an integer input form user and print the table of that number.

import java.util.Scanner;
public class ForLoop {
  public static void main(String[] args) {
    System.out.println("Enter a number");
    Scanner scan = new Scanner(System.in);
    int userInput= scan.nextInt();
    int result=0;
    System.out.println("Table of "+userInput);
    System.out.println("--------------");
    for (int num = 1; num <= 10; num++) {
      result=userInput*num;
      System.out.println(userInput+" * "+num+" = "+result);
    }
  }
}

In this program, a Scanner class is used to take input from user. Next, is a for loop which is declare to run10 times. This for loop starts with initialization int num=1, and executes the body part  till the condition num<=10 becomes false, after executing the body of for loop for each and every time num value will be incremented by 1.

Output of Program:-


Different ways of using For Loop:- For Loop can be used in different ways and sometimes it can be very complex. We will discuses this in the examples below. In For loop there is one thing to notice that all three declaration part of for loop can be left blank.


    for ; ; ) {   
       //infinite loop
    }



The code above is will work as an infinite loop or endless loop and it will work same as while(true) loop.

As we now know that all three part of For loop are optional and can be left blank but it is very interesting to know that what kind of code you can write in these parts. The condition part is the only part of for loop declaration for which there is a rule defined that it must be an Boolean expression. In the remaining two, Initialization and Iteration part we can actually write any peace of code.


public class ForLoop {
  public static void main(String[] args) {
    int i = 0;
    for (System.out.println("Initializtion Part"); i<

     System.out.println("Iteration Part") ) {
     

       System.out.println("Body part");
       i++;
    

    }
  }
}



Output of Program:-

Use of comma and logical operators in For loop:- In For loop we can use multiple statements in initialization and iteration parts using comma. In initialization part we can define multiple variables by separating the variables with comma but the variables must be of same type.
As we know, condition part of the for loop must be an boolean expression therefor use of comma is not allowed but we can use logical operators to make a valid boolean  expression.


public class ForLoop {
  public static void main(String[] args) {
    for (int a=1, b=5, c=10; a<b || a<c ; a++,b--,c--) {
      System.out.println("a = "+a+" b = "+b+" c = "+c);
    }
  }
}



Output of the program:-

In the next post we will learn about For each loop or Enhanced For Loop.

4 comments:

  1. Thanks for the auspicious writeup. It in reality used to
    be a leisure account it. Look complex to far delivered agreeable from
    you! By the way, how can we communicate?

    Also visit my page: pay day advance loans

    ReplyDelete
  2. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    microsoft azure training in bangalore
    rpa training in bangalore
    rpa training in pune
    best rpa training in bangalore

    ReplyDelete
  3. Great content thanks for sharing this informative blog which provided me technical information keep posting.
    python Course in Pune
    python Course institute in Chennai
    python Training institute in Bangalore

    ReplyDelete
  4. Wondering where to go in 2021? Things to doo has ranked as the best include a remote, idyllic island, the design capital ...

    ReplyDelete