4-Control and Looping Constructs-07!08!2023
4-Control and Looping Constructs-07!08!2023
Syntax
if(Boolean_expression 1)
{ // Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{ // Executes when the Boolean expression 2 is true }
}
switch statement
A switch statement allows a variable to be tested for equality
against a list of values.
switch(expression)
{
case value : // Statements
break;
// optional case value : // Statements
break; // You can have any number of case statements.
default : // Optional // Statements
}
The ? : Operator
while loop
• Repeats a statement or group of statements while a given condition
is true. It tests the condition before executing the loop body.
for loop
• Execute a sequence of statements multiple times and abbreviates the
code that manages the loop variable.
do...while loop
• Like a while statement, except that it tests the condition at the end
of the loop body.
While Loop
while(Boolean_expression) { // Statements }
do { // Statements }while(Boolean_expression);
public class Test
{ public static void main(String args[])
Output:
{ int x = 10; value of x : 10
do value of x : 11
value of x : 12
{ value of x : 13
System.out.print("value of x : " + x ); value of x : 14
value of x : 15
x++;
value of x : 16
System.out.print("\n"); value of x : 17
value of x : 18
}while( x < 20 );
value of x : 19
}}
Loop Control Statements
break statement
• Terminates the loop or switch statement and transfers execution to
the statement immediately following the loop or switch.
continue statement
• Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
Enhanced for loop in Java