Control Structure in Java
Control Structure in Java
int age;
Scanner input = new Scanner(System.in);
• if
• nested if
• if-else
• if-else-if statement/ ladder if statements
• switch statement
Selection Structure
• Within a method, we can alter the flow of
control (the order in which statements are
executed) using either conditionals or loops.
• The conditional statements if, if-else, and switch
allow us to choose which statement will be
executed next.
• Each choice or decision is based on the value of
boolean expression (also called the condition).
Selection Structure -
if
if(condition){
Statement(s);
}
Selection Structure -
if
• The statements gets
executed only when the
given condition is true.
If the condition is false
then the statements
inside if statement body
are completely ignored.
Selection Structure -
if
package typeControlStructures;
if(condition) {
Statement(s);
}
else {
Statement(s);
}
Selection Structure – if -
else
Selection Structure – if -
else
Selection Structure – if-else
package typeControlStructures;
Output:
Case2
Case3
Case4
Default
Selection Structure – break
Output:
Case2
Few point about Switch Case
3. The expression
Valid expression for switch
given inside switch
should result in a switch(1+2+23)
switch(1*2+3%4)
constant value
otherwise it would not Invalid Switch Expression
be valid.
switch(ab+cd)
switch(a+b+c)
Few point about Switch Case
Output:
Iteration number: 1
Iteration number: 2
Iteration number: 3
Repetition Structure – For Loop
Output:
The value of i is: 10
The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2
Repetition Structure While Loop
Syntax:
while (test_expression)
{
// statements
update_expression;
}
Repetition Structure – While Loop
1. Test Expression: In this expression,
we have to test the condition. If the
condition evaluates to true then we will
execute the body of the loop and go to
update expression. Otherwise, we will
exit from the while loop.
Example:
i <= 10
Repetition Structure – While Loop
Example:
i++;
Repetition Structure – While Loop
EVEN NUMBERS: Activity
1. Write a for loop that displays the even numbers between 23
and 42.
GRADES:
2. Get three exam grades from the user and compute the average
of the grades. Output the average of the three exams. Together
with the average, also include a smiley face in the output if the
average is greater than or equal to 60,
otherwise output ☹
• Use Scanner to get input from the user, and System.out to
output the result.
Activity
NUMBER IN WORDS
POWERS
1. Compute the power of a number given the base and
exponent. Do three version of this program using a while
loop, a
do-while loop and a for loop.