0% found this document useful (0 votes)
31 views

Computer Programing Alnahrain Unversity Lecture-9

The document discusses various Java control structures including switch statements, break statements, continue statements, and logical operators. It provides examples of how to use each structure and operator. Key topics are switch statements, break and continue statements, logical AND, OR, and negation operators, and an example program applying several concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Computer Programing Alnahrain Unversity Lecture-9

The document discusses various Java control structures including switch statements, break statements, continue statements, and logical operators. It provides examples of how to use each structure and operator. Key topics are switch statements, break and continue statements, logical AND, OR, and negation operators, and an example program applying several concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

1

Lecture Nine: Control Structure II - Advance

Programming Fundamentals in
Java

Lecture Nine
II

Subjects:
9.1
9.2
9.3
9.4

switch Statement
break Statement
continue Statement
Logical Operators

9.4.1
9.4.2
9.4.3
9.4.4
9.4.5
9.4.6

Conditional AND (&&) operator


Conditional OR (||) operator
Short-Circuit Evaluation of Complex Conditions
Boolean Logical AND (&) and Boolean Logical OR (|) operators
Boolean Logical Exclusive OR (^)
Logical Negation (!) Operator

9.5 Overall Example


Ihab A. Mohammed
Ihab A. Mohammed

2011

Lecture Nine: Control Structure II - Advance

9.1 Switch Statement


The switch multiple-selection statement performs different actions based on the
possible values of a constant integral expression of type byte, short, int, or char.
switch (expression) {
case value1:
case value2:
.
.
.
case valueN:
default:
}

Example: write a program to read a student grades for one course (each mark is
between 0-100) then count the number of A, B, C, D, and F grades, the summation
and average of grades and display them on screen.
Grade
A
B
C
D
F

Mark range
90-100
80-89
70-79
60-69
0-59

// Program 1
import java.util.Scanner;
public class Switch_Ex
{
public static void main(String[] args)
{
int mark;
int markCo = 0;
int sum = 0;
double avg = 0.0;
int aCo = 0, bCo = 0, cCo = 0, dCo = 0, fCo = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter integer grades in the range
0-100");
System.out.println("Type any negative number to stop");
System.out.print("Enter a mark: ");
mark = in.nextInt();
while(mark >= 0)
{
switch(mark / 10)
{
case 9:
case 10:
Ihab A. Mohammed

2011

Lecture Nine: Control Structure II - Advance


++aCo;
break;
case 8:
++bCo;
break;
case 7:
++cCo;
break;
case 6:
++dCo;
break;
default:
++fCo;
break;
} // end of switch
sum += mark;
++markCo;
System.out.print("Enter a mark: ");
mark = in.nextInt();
} // end of while
if(markCo != 0)
{
System.out.println("Grade Report");
System.out.println("------------");
System.out.println("Number of marks: " + markCo);
System.out.println("Summation of marks: " + sum);
avg = sum * 1.0 / markCo;
System.out.println("Average of marks: " + avg);
System.out.println("A: " + aCo);
System.out.println("B: " + bCo);
System.out.println("C: " + cCo);
System.out.println("D: " + dCo);
System.out.println("F: " + fCo);
}
else
System.out.println("You didnt enter any grades");
} // end of main
} // end of Switch_Ex

9.2 break Statement


The break statement, when executed in a while, for, do while or
switch, causes immediate exit from that statement. Execution continues with the
first statement after the control statement.
Example: the following example uses a loop from 1 to 20 to print numbers from 1 to
20, but the loop terminates when the counter reaches the value 5.

Ihab A. Mohammed

2011

Lecture Nine: Control Structure II - Advance


// Program 2
public class Break_Ex {
public static void main(String[] args) {
int co;
for(co = 1; co <= 20; co++) {
if(co == 5)
break;
System.out.println(co);
}
System.out.println("Loop terminated when co = " + co);
}
}

In the above program, when co is equal to 5, the if condition becomes true and the
break statement executes which terminates and exit the for loop to execute the println
statement.

9.3 continue Statement


The continue statement, when executed in a while, for or do while,
skips the remaining statements in the loop and proceeds with the next iteration of the
loop.
Example: write a program to print the numbers from 1 to 10 except number 7.
// Program 3
public class Continue_Ex {
public static void main(String[] args) {
int co = 1;
while(co <= 10) {
if(co == 7)
continue;
System.out.println(co);
++co;
}
System.out.println("Loop terminated when co = " + co);
}
}

9.4 Logical Operators


Logical operators enable you to form more complex conditions by combining
simple conditions. The logical operators are && (conditional AND), || (conditional
OR), & (boolean logical AND), | (boolean logical inclusive OR), ^ (boolean logical
exclusive OR) and ! (logical NOT).
Note: the &, | and ^ operators are also bitwise operators when theyre applied to
integral operands.
Ihab A. Mohammed

2011

Lecture Nine: Control Structure II - Advance

9.4.1

Conditional AND (&&) operator

Suppose that we want to add 5 marks to a student only and only if his mark is
between 45 and 49, which means that we have two conditions that both must be true:
(mark >=45)
and (mark <= 49)
We can write it without using logical operator As follows:
if(mark >= 45)
if(mark < 50)
mark += 5;

and by using conditional AND operator, the above code can be written as follows:
if(mark >= 45 && mark < 50)
mark += 5;

The conditional AND operator gives true only and only if all conditions are true.
Note: Many programmers prefer to use parentheses for each condition to be more
readable, thus the above code can be written as follows:
if( (mark >= 45) && (mark < 50) )
mark += 5;

The following table summarizes the && operator truth table.


expression1
False
False
True
True

9.4.2

expression2
False
True
False
True

expression1 && expression2


False
False
False
True

Conditional OR (||) operator

Suppose that we want to select a car and we want its color to be either white or gray,
which means that the color is either red or blue (but not both which is impossible) so
we can write it without using logical operators as follows:
if(color == "white")
// Select the car
else if(color == "gray")
// Select the car

now by using conditional OR operator, the above code can be written as follows:
if( (color == "white") || (color == "gray") )
// Select the car

The following table summarizes the || operator truth table.


Ihab A. Mohammed

2011

Lecture Nine: Control Structure II - Advance

expression1
False
False
True
True

9.4.3

expression2
False
True
False
True

expression1 || expression2
False
True
True
True

Short-Circuit Evaluation of Complex Conditions

The parts of an expression containing && or || operators are evaluated only until
it is known whether the condition is true or false. Thus, evaluation of the expression:
(mark >= 45) && (mark < 50)

stops immediately if mark is less than 45 (because the first condition is false, so there
is no need to continue because the entire expression is false) and continues if mark is
greater than or equal to 45 (the first condition is true, so the entire expression could
still be true if the second condition is true also) this is called short-circuit
evaluation.
The evaluation of the expression:
(color == "white") || (color == "gray")

continues to the second condition because even if the first condition is false, the
second may be true which makes the entire expression true.
To understand the need for these operators, take a look at the following expression:
( i != 0 ) && ( 10 / i == 2 )

If i == 0 then evaluation stops immediately because the entire expression is false, but
if the evaluation continues, an error will occur because 10 / 0 is an error. So it is very
useful to use conditional logical operators to handle this kind of expressions without
any errors.

9.4.4

Boolean Logical AND (&) and Boolean Logical OR (|)


Operators

The boolean logical AND (&) and boolean logical inclusive OR (|) operators
work identically to the && (conditional AND) and || (conditional OR) operators, with
one exception: The boolean logical operators always evaluate both of their operands
(i.e., they do not perform short-circuit evaluation). Therefore, the expression:
( carSpeed > 100 ) & ( maxSpeed == 100 )
Ihab A. Mohammed

2011

Lecture Nine: Control Structure II - Advance

Evaluates (maxSpeed == 100) regardless of whether carSpeed is > 100 (the second
condition is evaluated even if carSpeed is <= 100). This is useful if the right operand
of the boolean logical AND or boolean logical inclusive OR operator has a required
side effect modification of a variable's value. For example, the expression
( birthday == true ) | ( ++age >= 65 )

guarantees that the condition ++age >= 65 will be evaluated. Thus, the variable age is
incremented in the preceding expression, regardless of whether the overall expression
is true or false.
Note: For clarity, avoid expressions with side effects in conditions. The side effects
may look clever, but they can make it harder to understand code and can lead to
subtle logic errors.

9.4.5

Boolean Logical Exclusive OR (^)

A simple condition containing the boolean logical exclusive OR (^) operator is


true if and only if one of its operands is True and the other is false. If both operands
are true or both are false, the entire condition is false
The following table summarizes the ^ operator truth table.
expression1
False
False
True
True

9.4.6

expression2
False
True
False
True

expression1 ^ expression2
False
True
True
False

Logical Negation Operator (!)

The ! (logical NOT, also called logical negation or logical complement) operator
enables a programmer to "reverse" the meaning of a condition. Unlike the logical
operators &&, ||, &, | and ^, which are binary operators that combine two conditions,
the logical negation operator is a unary operator that has only a single condition as an
operand. The logical negation operator is placed before a condition to choose a path
of execution if the original condition (without the logical negation operator) is false,
as in the program segment:
if( !(grade < 50))
System.out.println("Passed");

Note: in the above example, the parentheses are needed because it had a high priority
than the less than operator.

Ihab A. Mohammed

2011

Lecture Nine: Control Structure II - Advance

9.5 Overall Example


The following program is the same as program 1 but with using break, continue,
ifelse, and logical operators:
// Program 4
import java.util.Scanner;
public class Complete_Ex
{
public static void main(String[] args)
{
int mark;
int markCo = 0;
int sum = 0;
double avg = 0.0;
int aCo = 0, bCo = 0, cCo = 0, dCo = 0, fCo = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter integer grades in the range
0-100");
System.out.println("Type any negative number to stop");
while(true)
{
System.out.print("Enter a mark: ");
mark = in.nextInt();
if(mark < 0)
break;
else if(mark > 100)
{
System.out.println("Mark is between 0-100,
Please enter a valid mark");
continue;
}
else if( (mark >= 90) && (mark <= 100) )
++aCo;
else if( (mark >= 80) && (mark < 90) )
++bCo;
else if( (mark >= 70) && (mark < 80) )
++cCo;
else if( (mark >= 60) && (mark < 70) )
++dCo;
else
++fCo;
sum += mark;
++markCo;
} // end of while

Ihab A. Mohammed

2011

Lecture Nine: Control Structure II - Advance


if(markCo != 0)
{
System.out.println("Grade Report");
System.out.println("------------");
System.out.println("Number of marks: " + markCo);
System.out.println("Summation of marks: " + sum);
avg = sum * 1.0 / markCo;
System.out.println("Average of marks: " + avg);
System.out.println("A: " + aCo);
System.out.println("B: " + bCo);
System.out.println("C: " + cCo);
System.out.println("D: " + dCo);
System.out.println("F: " + fCo);
}
else
System.out.println("You didnt enter any grades");
} // end of main
} // end of Complete_Ex

Ihab A. Mohammed

2011

You might also like