for loop
 

// Counting from 10 to 50 in increments (steps) of 5:

int x;

for ( x=10; x<=50; x= x+5 ) //**increment/decrement won't work here.
{ // x = x + 5 is same as x += 5
System.out.println("Loop counter value is " + x );
}

//Counting from 50 to10 backwards in increments of 5:

int x;

for ( x=50; x>=10; x=x-5 ) // x = x - 5 is same as x -=5
{
System.out.println("Loop counter value is " + x);
}

// Declaring and assigning the startExpression within the for loop:

//Counting down from 10 to Blast Off
for ( int i = 10; i>= 1; i-- ) // notice the int
{
System.out.println( i );
}
System.out.println("Blast off!");

// Keeping track of a "total" of values using a for loop:

int total = 0; // must be initialized before the loop (avoid "garbage")

for (int count = 5; count <=10; count++ )
{
total += count;
}
System.out.println("The total is " + total);

// The body of the loop may contain statements that further check on data:

for (int ctr = 1; ctr <= 35; ctr++) // will address 35 children
{
child = Console.readLine("Enter the child's name: ");
age = Console.readInt("Enter the child's age: ");

if ((age >= 6) && (age <=7))
{
System.out.println(child + " has Mr. Escalante for a teacher.");
}
else
{
System.out.println(child + " does not have Mr. Escalante for a teacher.");
}
} // Quits after 35 times.

// User determines length of for loop:

num = Console.readInt("How many stars shall I print?");
System.out.println("OK! Here I go .... ");

for (i = 1; i <= num; i++)
{
System.out.print( * + " ");
}

// Titles and for loops:

//print titles OUTSIDE the loop to prevent multiple copies of the title
//print even numbers from 1 to 20 with title
System.out.println("Even numbers from 1 to 20 "); //title is outside loop

for (int num = 2; num <= 20; num += 2) //notice startExpression
{
System.out.print( num + " ") ; //prints the even numbers
}

(c) Shilpa Sayura Foundation 2006-2017