Lecture -4
Lecture -4
Faculty of Technology
Department of Electrical and Computer
Engineering
statement
statement
statement
statement
statement statement
What are Control Structures?
• Control structures alter the flow of the
program, the sequence of statements that
are executed in a program.
if (expression) { yes
statement1;
} execute
statement
rest_of_program
execute
rest_of_program
If-Else Statement
if (expression) {
statement1;
}
else{
statement2;
}
next_statement;
if (grade == 'A')
System.out.println("You got an A.");
else if (grade == 'B')
System.out.println("You got a B.");
else if (grade == 'C')
System.out.println("You got a C.");
else
System.out.println("You got an F.");
Switch Statements
• The switch statement enables you to test several cases
generated by a given expression.
• For example:
switch (expression) {
case value1:
statement1;
case value2:
statement2;
default:
default_statement;
}
Every statement after the true case is executed
Do default action
Continue the
program
Break Statements in Switch Statements
• The break statement tells the computer to exit
the switch statement
• For example:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
default:
default_statement;
break;
}
switch (expression){ expression y
case value1: equals Do value1 thing break
// Do value1 thing value1?
break;
case value2: n
// Do value2 thing
break;
expression y
... equals Do value2 thing break
default: value2?
// Do default action
break;
} n
// Continue the program
do default action
Continue the
break
program
Remember the Chained If-Else . . .
if (grade == 'A')
System.out.println("You got an A.");
else if (grade == 'B')
System.out.println("You got a B.");
else if (grade == 'C')
System.out.println("You got a C.");
else
System.out.println("You got an F.");
• This is how it is accomplished with a switch:
switch (grade) {
case 'A':
System.out.println("You got an A.");
break;
case 'B':
System.out.println("You got a B.");
break;
case 'C':
System.out.println("You got a C.");
break;
default:
System.out.println("You got an F.");
}
int sum = 0;
int i = 1;
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
The for Loop
for (init_expr; loop_condition; increment_expr) {
statement;
}
int sum = 0;
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
• Example 3:
int n = 0;
for(; n <= 100;) {
System.out.println(++n);
}
The for loop
Initialize count
The while loop
n n
Test condition Test condition
is true? is true?
y
y
Execute loop
statement(?) Execute loop
statement(s)
Increment
Next statement count
New statement
The continue Statement
• The continue statement causes the program
to jump to the next iteration of the loop.
/**
* prints out "5689"
*/
for(int m = 5; m < 10; m++) {
if(m == 7) {
continue;
}
System.out.print(m);
}
• Another continue example:
int sum = 0;
for(int i = 1; i <= 10; i++){
if(i % 3 == 0) {
continue;
}
sum += i;
}