/* related posts with thumb nails */

Looping structures:

Looping structures include Iterative control structures. They are called loops because the statements in those structures will be repeatedly executed as long as the condition is true i.e. till the condition becomes false.

Iterative control structure:

a) for loop:










syntax:

for ( expression1 ; condition; expression2)

{

Statements

}

explanation:

Statements get executed as long as the condition is true. Generally expression1 includes initializing statements and expression2 includes statements that use increment, decrement, and assignment operators.

Example:

for( i=1 ; i<=10 ; i++)

System.out.println(“hello”);

/* prints hello 10 times */

b) while loop:








syntax:

while ( condition )

{

Statements

}

Explanation:

Statements get executed as long as the condition is true. It checks the condition first and executes the statements later. It is also called entry control loop.

Example:

i=0;

while( i<10 )

{

System.out.println(“hello”);

i=i+1;

} /* prints hello 10 times */

c) do while loop:

Syntax:

do

{

Statements

}while(condition);










c) for each (enhanced for) loop

Syntax:

for (variable : expression)

{

Statements

}

Explanation:

The enhanced for loop is called as for each loop. It is introduced in J2SE 5.0. This is more used with arrays and enumerations. Generally to access the array elements, we use indexes. But, using for-each, we can directly have access to each element of the array without indexes.

Example:

int x[]= {10,20,30};

for (int k : x)

System.out.print(k+” “);

The above code prints: 10 20 30

e) Switch:








Syntax:

switch(variable)

{

case constant1: statment1

break;

case constant2: statement2

break;

.

.

default: statements

break;

}

Explanation:

switch is similar to if else if. Statement 1 gets executed when the variable is equal to constant1 and so on. Control comes to “default” portion when all the cases (constants), which have been mentioned do not match with the value of the variable. Here break and default are optional. When there is no break for a case it continues till it encounters break or the end of the switch loop.

Example:

k=x-y;

switch(k)

{

case 0: System.out.println( “ x and y are equal”);

break;

default: System.out.println( “ x and y are not equal”);

break;

}


Related Topics:

0 comments:

Post a Comment