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

Lecture 4 Conditional Statements Java

The document provides an overview of fundamental programming concepts in Java, focusing on relational operators, conditional statements (if, else, switch), and logical operators. It includes examples of how to implement these concepts in code, such as calculating the area of a circle and determining if a number is even or odd. Additionally, it discusses common mistakes and practices for using nested if statements and the ternary operator.

Uploaded by

mwaslam2303
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)
4 views

Lecture 4 Conditional Statements Java

The document provides an overview of fundamental programming concepts in Java, focusing on relational operators, conditional statements (if, else, switch), and logical operators. It includes examples of how to implement these concepts in code, such as calculating the area of a circle and determining if a number is even or odd. Additionally, it discusses common mistakes and practices for using nested if statements and the ternary operator.

Uploaded by

mwaslam2303
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/ 18

6/27/2020

IN2203

Fundamentals of
Programming (Java)

Instructor
Dr. Muhammad Waqar
muhammad.aslam@purescollege.ca

Relational Operators
• How do you compare two values, such as whether a value is greater than 0,
equal to 0, or less than 0? Tests
• Java provides six relational operators (also known as comparison operators),
which can be used to compare two values

1
6/27/2020

Examples of Relational Operators


• The result produced by a relational operator is a boolean value. For example,
the following code fragment is perfectly valid:
Tests

int a = 4;
int b = 1;
boolean c = a < b;

• In this case, the result of a<b (which is false) is stored in c.

boolean d = (a==b)

• This statement checks if a is equal to b? Since it is not true so false is stored


in d.

If Statement
• The if statement is Java’s conditional branch statement. It can be used to
route program execution through two different
Tests paths. Here is the general
form of the if statement:
if (condition) statement1;
else statement2;
• Here, each statement may be a single statement or a compound statement
enclosed in curly braces (that is, a block). The condition is any expression
that returns a boolean value. The else clause is optional.
• The if works like this: If the condition is true, then statement1 is executed.
Otherwise, statement2 (if it exists) is executed. In no case will both
statements be executed.

2
6/27/2020

If Statement Example
int a =5, b=3;
if(a < b) a = 0; Tests
else b = 0;

Here, if checks whether a is less than b, if it was then a would be set to zero.
Otherwise, b would be set to zero. In no case are they both set to zero. Since a
is not less than b so b is set as zero

Common Mistakes

Tests

3
6/27/2020

If for Multiple Statements


Only one statement can appear directly after the if or the else. If you want to
include more statements, you’ll need to create a block, as in this fragment:
Tests
int bytesAvailable;
// ...
if (bytesAvailable > 0) {
ProcessData();
bytesAvailable -= n;
} else
waitForMoreData();
bytesAvailable = n;

A Simple Program
Write a program which calculates area of a circle.

Tests
1- The program must ask user to enter radius of circle.
2- If the radius entered by user is greater than or equal to zero, the program
must calculate its area and print it on screen.
3- If area is less than zero then it should print that “Radius must be greater than
zero “and exit the program.

4
6/27/2020

Code
Scanner input = new Scanner (System.in);
System.out.print("Please enter radius of circle: ");
Tests
int radius = input.nextInt();
double PI = 3.1416;
if (radius > 0) {
double area = radius * radius * PI;
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
else
System.out.println("The radius must be greater than
zero");

10

Another Simple Program


Write a program which checks if a number is even or odd.

Tests
1- The program must ask user to enter an integer.
2- If number is even, program must print, it is an even number.
3- If number is odd, program must print, it is an odd number.

Hint: Use remainder (%) operator to find out if a number is even or odd.
Remainder of an even number is always zero.

10

5
6/27/2020

11

Code
Scanner input = new Scanner (System.in);

Tests
System.out.print("Please enter a number (integer): ");
int number = input.nextInt();
if (number % 2 == 0)
System.out.println("This is an even number");
else
System.out.println("This is an odd number");

11

12

Nested If Statements
• A nested if is an if statement that is the target of another if or else.
• Example of nested if is given below
Tests
int i=10, j=8, k=5;
if (i > k) {
if (j > k)
System.out.println("i and j are greater than
k");
}
else
System.out.println(“i or j is less than or equal to
k");

12

6
6/27/2020

13

Else in Nested If Statements


• When you nest ifs, the main thing to remember is that an else statement
always refers to the nearest if statement that is within the same block as the
else and that is not already associated with an else. Here is an example:
Tests

int i=10, j=15, a=20, b=25, c=30, d=35, k=120;

if(i == 10) {
if(k > 100) a = b; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)

13

14

Writing Nested if else Statements

Tests

14

7
6/27/2020

15

Practice Program
Write a program which tells user which category he/she belongs to

Tests
1- The program must ask user to enter age as integer.
2- If age is less than 20 it must print “You are Teenager”.
3- If age is from 20 to 35 it must print “You are Young”.
4- If age is from 36 to 50 it must print “ You are middle aged”
5- If age is above 50 it must print “You are old”

Hint: Use nested if else statements.

15

16

Code
Scanner input = new Scanner (System.in);
System.out.print("Please enter age: ");
int age = input.nextInt(); Tests

if (age < 20)


System.out.print("You are a Teenager");
else if (age <36)
System.out.print("You are young");
else if (age < 51)
System.out.print("You are middle aged");
else
System.out.print("You are old");

16

8
6/27/2020

17

Common Errors using if

Tests

17

18

Common Errors using if

Tests

18

9
6/27/2020

19

Logical Operators
• Logical operators are used to combine several logical conditions to form a
compound Boolean expression. Logical operators, also known as Boolean
operators, operate on Boolean values to create
Tests a new Boolean value.

19

20

Practice Program
Write a program using logical operators that checks whether a number entered
by the user is between certain values and gives remarks accordingly.
Tests

• 80< number && number <=100 You have got distinction


• 60<= number && number<= 80 You have passed
• 0<= number && number < 60 You have failed.
• Otherwise Invalid Number

(Hint: Use if else and && for checking if both conditions are true).

20

10
6/27/2020

21

Practice Program
• Write a program using logical operators that checks whether a number is
divisible by 2 and 3, by 2 or 3, and by 2 or 3 but not both.
Tests

(Hint: Use && for checking if both conditions are true, use || for checking if one
of the condition is true and use ^ for checking if only one condition is true.

21

22

Code (Part I)
import java.util.Scanner;

Tests
public class TestBooleanOperators {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
if (number % 2 == 0 && number % 3 == 0)
System.out.println(number + " is divisible by 2 and
3.");

22

11
6/27/2020

23

Code (Part II)

if (number % 2 == 0 || number % 3 == 0)
System.out.println(number + "Tests
is divisible by 2 or
3");

if (number % 2 == 0 ^ number % 3 == 0)
System.out.println(number + " is divisible by 2 or 3,
but not both.");
}
}

23

24

Switch Statement

• The switch statement is Java’s multiway branch statement.


Tests
• It provides an easy way to dispatch execution to different parts of your code
based on the value of an expression.
• It often provides a better alternative than a large series of if-else-if
statements.
• The general form of a switch statement is shown on next slide:

24

12
6/27/2020

25

Switch Statement General Form


switch (expression) {
case value1:
// statement sequence Tests
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
Break;
default:
// default statement sequence;
}

25

26

Switch Statement Example


Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt(); Tests
switch (number) {
case 1:
System.out.println(“Please wait for operator");
break;
case 2:
System.out.println(“You are in main menu");
break;
default:
System.out.println(“Thank you for using service.");
break;

26

13
6/27/2020

27

Switch Statement Working


• The expression must be of type byte, short, int, or char
• Each of the values specified in the case statements must be of a type
compatible with the expression and duplicate
Testscase values are not allowed.
• The value of the expression is compared with each of the literal values in the
case statements. If a match is found, the code sequence following that case
statement is executed.
• If none of the constants matches the value of the expression, then the default
statement is executed. However, the default statement is optional. If no case
matches and no default is present, then no further action is taken.
• The break statement is used inside the switch to terminate a statement
sequence.
• When a break statement is encountered, execution branches to the first line
of code that follows the entire switch statement. This has the effect of
“jumping out” of the switch.

27

Switch Statement Example


28

import java.util.Scanner;
public class TestSwitch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter day number: "); Tests
int day = input.nextInt();
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Weekday");
break;
case 0:
case 6: System.out.println("Weekend");
}}}

28

14
6/27/2020

Example using String


29

Scanner input = new Scanner(System.in);


System.out.println("Please enter a character from A-Z");
String str= input.nextLine();
switch (str) {
Tests
case "A":
System.out.println("CaseA");
break;
case "B":
System.out.println("CaseB");
break;
case "C":
System.out.println("CaseC ");
break;
default:
System.out.println("Default ");
}

29

30

Practice Problem
Write a switch statement that displays Sunday, Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday, if day is 0, 1, 2, 3,Tests
4, 5, 6, accordingly. Get Day number
from user as input in the form of an integer.

30

15
6/27/2020

Calculator Using Switch (I)


31

char operator;
double number1, number2, result;

Scanner scanner = new Scanner(System.in);


Tests
System.out.print("Enter operator (either +, -, * or /): ");

operator = scanner.next().charAt(0);

System.out.print(“Please enter number 1: ");


number1 = scanner.nextDouble();
System.out.print(“Please enter number 2: ");
number2 = scanner.nextDouble();

switch (operator) {

case '+':
result = number1 + number2;
System.out.print(number1 + "+" + number2 + " = " + result);
break;

31

Calculator Using Switch (II)


32

case '-':
result = number1 - number2;
System.out.print(number1 + "-" + number2 + " = " + result);
break; Tests
case '*':
result = number1 * number2;
System.out.print(number1 + "*" + number2 + " = " + result);
break;
case '/':
result = number1 / number2;
System.out.print(number1 + "/" + number2 + " = " + result);
break;
default:
System.out.println("Invalid operator!");
break;
}

32

16
6/27/2020

33

The ? Operator
• Java includes a special ternary (three-way) operator that can replace certain types of
if-then-else statements.
• This operator is the ?. It can seem somewhatTests
confusing at first, but the ? can be used
very effectively once mastered.
• The ? has this general form:
expression1 ? expression2 : expression3
• Here, expression1 can be any expression that evaluates to a boolean value. If
expression1 is true, then expression2 is evaluated; otherwise, expression3 is
evaluated.
• The result of the ? operation is that of the expression evaluated. Both expression2
and expression3 are required to return the same type, which can’t be void.
• Here is an example of the way that the ? is employed:
ratio = (denom == 0 ? 0 : num / denom);

33

34

Example of the ? Operator


if (x > 0)
y = 1;
Tests
else
y = -1;

• Alternatively, as in the following example, you can use a conditional


expression to achieve the same result.

y = (x > 0) ? 1 : -1;

• Another Example
System.out.println((num % 2 == 0) ? "num is even" : "num is odd");

34

17
6/27/2020

35

Practice Problem
Please get age from user using Scanner class and get ticket price based on age. If
age is greater than or equal to 16, ticket price is 20 otherwise 10. The if condition
is given below. Tests

if (age >= 16)


ticketPrice = 20;
else
ticketPrice = 10;

Rewrite the following if statements using the conditional ? operator.

35

Thank You

36

18

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy