click here for complete presentation on LOOPS

3 loops in Java

  1. while loops
    • Used when you do not know how many times you are going to need to repeat
  2. for loops
    • Used when you do know how many times you are going to repeat
  3. do-while loops - not covered on AP Exam!!
    • Used rarely - Used whenever you need to be guaranteed the loop runs at least once

While Loops

  • The simplest loop in Java is the while loop
  • It looks similar to an if statement
  • The difference is when you get to the end of the while loop it jumps back to the top
  • If the condition in the while loop is still true, it executes the body of the loop again

Anatomy of a while Loop

while( condition )
{

statement1;
statement2;
..
statementN;

}

int i = 1;
while( i <= 5 )
{


System.out.println(i);
i++;
}

Output
1
2
3
4
5

Using an if with a while loop

int i = 1;
int myCtr2 = 0;
while( i <= 5 )
{


if (i ==2 || i ==4)

myCtr2++;

i++;
}
System.out.,println(“The counter is ” + myCtr2);
//output The counter is 2

for Loops

  • for loops are great when you know how many times a loop will run
  • They are the most commonly used of all loops
  • They are perfect for any task that needs to run, say, 100 times

A for loop usually has 3 parts in its header:

  1. Initialization
  2. Condition
  3. Increment

Anatomy of a for Loop

for(Initialization; Condition; Increment)
{

statement1;
statement2;
..
statementN;

}

for(int i=1; i < 5; i++)
{


System.out.println(i);
}

Output
1
2
3
4
5

Using an if with a for loop

int ctr=0;
for (int i = 1; i <= 10; i++)
{


if (i==1 || i == 3 || i == 4)

ctr = ctr + 1;

}
System.out.println(ctr); //output 3 ctr=3

Scanner Class

Credit: A Slides are modified with permission from Barry Wittman at Elizabethtown College
This work is licensed under an Attribution-NonCommercial-ShareAlike 3.0 Unsupported License