Title: For Loops
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

For Loops

1. Simple for loop:
for (initialization statement(s) ; boolean condition ; end of loop statement(s) )
statement;
2. Examples:

for (int i=0; i < 10; i++)
System.out.println(i);

for (int i=0; i < 10; i++)
{
x = x + 100;
y = 10 * x;
System.out.println( " x="+x + " y=" + y + " i="+i):
}

3. counter declared in for loop versus before for loop

for (int myCount=0; myCount < 10; myCount +=1)
System.out.println(myCount);

System.out.println(myCount); // Probably a compile error
--------------------------------------------------------------------

int myCount;
for (myCount=0; myCount < 10; myCount++)
System.out.println.println(myCount);

System.out.println(myCount); // works this time
4. Leaving one of the 3 entries blank, or all of entries blank

int myCount=0;
for (; myCount < 10; myCount++)
System.out.println.println(myCount);

int myCount2=0;
for (; ; myCount2++)
{
if (myCount < 10) break;
System.out.println.println(myCount2);
}

int myCount3=0;
for (; ; )
{
if (myCount3 < 10) break;
System.out.println.println(myCount3);
myCount3 += 1;
}
5. Using comma to get multiple statements in first or third for loop parameter
for (int i=0, j=100; i +j < 120; i++, j++)
{
System.out.println("i="+i + " j="+j);
}
6. Pitfall with ; being a null statement
for (int i=0; i < 10; i++) ; // Do Nothing loop

while (i < 10);  // infinite loop

Programs created on the video:


  public class ForLoops {

    public static void main(String[] args) {

        int i;
        for (i=0; i < 10; i++)
        {
            System.out.println(i);
        }

        i=0;
        while (i < 10)
        {
            System.out.println(i);
            i+=1;
        }
        System.out.println("***** for loop going down ");
        i =30;

        for ( ; i >=0; i -= 4)
            System.out.println(i);

        System.out.println("***** for loop using empty entries ");
        i =30;
        for ( ; ; i-= 4)
        {
            if (i < 0)
                break;
            System.out.println(i);
        }

        System.out.println("***** Loop declaration issues ");

        int j;
        for ( j=1; j <= 10; j++)
        {
            System.out.println(j);
        }
        System.out.println("j ="+ j);

        for (int k=1; k <= 10; k++)
        {
            System.out.println(k);
        }

        //System.out.println("k="+k);
        System.out.println("***** Multiple initializations and multiple increments ");

        for (int m=1, n=100; m+n < 300; m+=1, n+=50)
            System.out.println("n="+n + " m="+m);


    }

}



Last Modified: July 20, 2013 3:01 PM