Iteration Statements

Java has got 4 main types of iterative statements.

  1. FOR LOOP
  2. ENHANCED FOR LOOP
  3. WHILE LOOP
  4. DO-WHILE LOOP

For Loop

  • Keywords : for, break, continue

Example :

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

System.out.println(i);

}

Enhanced For Loop

  • Keywords : for, break, continue
  • This is used when interacting with arrays

Example :

String sizes[] = {1,2,3,4,5};

for ( int newSize : sizes ) {

System.out.println ( “Size :” + newSize);

}

While Loop

int x = 10;

while ( x > 0 ) {

System.out.println ( x );

x–;

}

Do-While Loop

int y = 0;

do {

System.out.println ( y);

y++;

} while ( x <= 10)

  • The main difference between While and Do-While statements is that Do-While statements always runs the body once.

The use of break and continue is optional.

Where to use break and continue ?

Break is used whenever we want to end the loop.  Sometimes we need to end the loop if we find out what we exactly want.

Continue is used when  there is a requirement to skip a part of the code inside loop under some conditions.

Using break :

int x = 5;

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

if ( i > x) {

System.out.println ( “The number is : ” + i );

break;

}

}

 

Using continue :

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

if ( ( i % 2 ) == 0 ) {

continue;

}

System.out.println ( i );

}

hint : i % 2 => this is the modulo function which gives the remainder after the division.

We will discuss about returning and labeling in the next tutorial.

Thank you.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s