For Loop

Discussion in 'Java' started by netOwen, Nov 29, 2016.

  1. netOwen


    Nov 28, 2016
    Likes Received:
    I am wonder if someone could explain to me, how this for loop works.

    public class DoWhat
    public static void main(string[] args)
    int x = 0;
    int i;
    for ( i = 1; i <=4; i++)
    x = x + (i*i +3);
    System.out.printf("%4d %4d\n", i,x);
    }// end of loop
    }//end main
    } //end class DoWhat

    i know that the output is

    1 4
    2 11
    3 23
    4 43

    how dose it come to this out put??
    netOwen, Nov 29, 2016
    1. Advertisements

  2. netOwen


    Apr 25, 2017
    Likes Received:
    Enhanced for loop in Java
    As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including arrays.
    Learn Java here:

    Following is the syntax of enhanced for loop −

    for(declaration : expression) {
    // Statements

    • Declaration − The newly declared block variable, is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.

    • Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.
    public class Test {

    public static void main(String args[]) {
    int [] numbers = {10, 20, 30, 40, 50};

    for(int x : numbers ) {
    System.out.print( x );
    String [] names = {"James", "Larry", "Tom", "Lacy"};

    for( String name : names ) {
    System.out.print( name );
    This will produce the following result −

    10, 20, 30, 40, 50,
    James, Larry, Tom, Lacy,
    Nihar, Apr 25, 2017
    1. Advertisements

  3. netOwen

    Vishal Jamdagni

    Feb 6, 2018
    Likes Received:
    The main thing you'll have to remember for here is that the update expression or even called as the loop iteration part takes place after the body of the loop is executed... so, let's take a look at the dry run:
    i is initialized to 1
    next, x is updated as solve the expression within the brackets which gives us (1*1+3) this becomes 4. Hence x gets the value of 4.
    Then comes the standard printing procedure. After this increment and use the value of i which now becomes 2.
    Now, bracket expression becomes (2*2+3) which is 7 now add the value of x to this which is 4, resulting in x becoming 11 and similarly it goes on.
    Hope this helps.
    Vishal Jamdagni, Feb 7, 2018
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.