computer programming, i laboratory manual experiment #3

13
Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #3 Selections

Upload: others

Post on 29-Jan-2022

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Computer Programming, I Laboratory Manual Experiment #3

Think Twice

Code Once

The Islamic University of Gaza

Engineering Faculty

Department of Computer Engineering

Fall 2017

ECOM 2005

Khaleel I. Shaheen

Computer Programming, I

Laboratory Manual

Experiment #3

Selections

Page 2: Computer Programming, I Laboratory Manual Experiment #3

Experiment #3: Selections

2

Numeric Type Conversions

You can always assign a value to a numeric variable whose type supports a larger range of

values; thus, for instance, you can assign a long value to a float variable. You cannot, however,

assign a value to a variable of a type with a smaller range unless you use type casting. Casting

is an operation that converts a value of one data type into a value of another data type.

Casting a type with a small range to a type with a larger range is known as widening a type.

Casting a type with a large range to a type with a smaller range is known as narrowing a type.

widening is called implicit casting because Java will automatically widen a type, but you must

narrow a type explicitly, so narrowing is called explicit casting.

Widening examples:

double x = 3 * 4.5; // implicit widening, 3 is now 3.0

int i = 5;

double d = i; // implicit widening, d is now 5.0

Narrowing examples:

double d = 10.5;

int i = (int) d; // explicit narrowing, i is now 10

As we saw, when a double value is cast into an int value, the fractional part is truncated.

Casting is necessary if you are assigning a value to a variable of a smaller type range, such as

assigning a double value to an int variable.

byte < short < int < long < float < double

Ex: What is sum after executing the following code:

int sum = 0;

sum += 4.5;

Solution:

sum += 4.5 is equivalent to sum = (int)(sum + 4.5).

Page 3: Computer Programming, I Laboratory Manual Experiment #3

Experiment #3: Selections

3

Boolean Data Type

The boolean data type declares a variable with the value either true or false. A variable that

holds a Boolean value is known as a Boolean variable. The boolean data type is used to declare

Boolean variables. A boolean variable can hold one of the two values: true or false.

boolean isOn = true;

true and false are literals, just like a number such as 10. They are treated as reserved words

and cannot be used as identifiers in the program.

Java provides six relational operators (comparison operators), which can be used to compare

two values and return a boolean value:

Ex: Assuming that x = 1, show the result of the following Boolean expressions:

x > 0

x < 0

x != 0

x >= 0

x != 1

Page 4: Computer Programming, I Laboratory Manual Experiment #3

Experiment #3: Selections

4

if Statements

An if statement is a construct that enables a program to specify alternative paths of execution.

A one-way if statement executes an action if and only if the condition is true.

For example:

public class computeC {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter radius: ");

double radius = input.nextDouble();

if (radius >= 0) {

double c = 2 * 3.14159 * radius;

System.out.println("C is: " + c);

}

}

}

The block braces can be omitted if they enclose a single statement.

Page 5: Computer Programming, I Laboratory Manual Experiment #3

Experiment #3: Selections

5

Two-Way if-else Statements

An if-else statement decides the execution path based on whether the condition is true or false.

If the boolean-expression evaluates to true, the statement(s) for the true case are executed;

otherwise, the statement(s) for the false case are executed. For example:

public class computeC {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter radius: ");

double radius = input.nextDouble();

if (radius >= 0) {

double c = 2 * 3.14159 * radius;

System.out.println("C is: " + c);

} else {

System.out.println("radius cannot be negative");

}

}

}

Ex: What is the output of the code?

Page 6: Computer Programming, I Laboratory Manual Experiment #3

Experiment #3: Selections

6

Nested if and Multi-Way if-else Statements

An if statement can be inside another if statement to form a nested if statement. The nested

if statement can be used to implement multiple alternatives. The statement below prints a letter

grade according to the score, with multiple alternatives.

double score = 85;

if (score >= 90.0)

System.out.print("A");

else if (score >= 80.0)

System.out.print("B");

else if (score >= 70.0)

System.out.print("C");

else if (score >= 60.0)

System.out.print("D");

else

System.out.print("F");

Logical Operators

Sometimes, whether a statement is executed is determined by a combination of several

conditions. You can use logical operators to combine these conditions to form a compound

Boolean expression. Logical operators, also known as Boolean operators, operate on Boolean

values to create a new Boolean value. The logical operators !, &&, ||, and ^ can be used

to create a compound Boolean expression.

Page 7: Computer Programming, I Laboratory Manual Experiment #3

Experiment #3: Selections

7

Ex: Modify the previous example to ensure that the grade is between 0 and 100. If not, then

output error message to the user.

double score = 85;

if (score < 0 || score > 100) {

System.out.println("Score is wrong");

} else {

if (score >= 90.0)

System.out.print("A");

else if (score >= 80.0)

System.out.print("B");

else if (score >= 70.0)

System.out.print("C");

else if (score >= 60.0)

System.out.print("D");

else

System.out.print("F");

}

switch Statements

A switch statement executes statements based on the value of a variable or an expression.

The full syntax for the switch statement is as follows:

switch (switch-expression) {

case value1: statement(s)1;

break;

case value2: statement(s)2;

break;

...

case valueN: statement(s)N;

break;

default: statement(s)-for-default;

}

Notes about switch statement:

• The switch-expression must yield a value of char, byte, short, int, or String type and must

always be enclosed in parentheses.

• The value1, . . ., and valueN must have the same data type as the value of the switch-

expression.

Page 8: Computer Programming, I Laboratory Manual Experiment #3

Experiment #3: Selections

8

• When the value in a case statement matches the value of the switch-expression, the

statements starting from this case are executed until either a break statement or the

end of the switch statement is reached.

• The default case, which is optional, can be used to perform actions when none of the

specified cases matches the switch-expression.

• The keyword break is optional. The break statement immediately ends the switch

statement.

Ex: Write a program that reads the month of birth and prints the name of that month. Solution:

Scanner input = new Scanner(System.in);

System.out.print("Enter your birth month, ex 5 : ");

int month = input.nextInt();

String monthString;

switch (month) {

case 1: monthString = "January";

break;

case 2: monthString = "February";

break;

case 3: monthString = "March";

break;

case 4: monthString = "April";

break;

case 5: monthString = "May";

break;

case 6: monthString = "June";

break;

case 7: monthString = "July";

break;

case 8: monthString = "August";

break;

case 9: monthString = "September";

break;

case 10: monthString = "October";

break;

case 11: monthString = "November";

break;

case 12: monthString = "December";

break;

default: monthString = "Invalid month";

break;

}

System.out.println(monthString);

Page 9: Computer Programming, I Laboratory Manual Experiment #3

Experiment #3: Selections

9

Conditional Expressions

A conditional expression evaluates an expression based on a condition, with no explicit if in the

statement. The syntax is

boolean-expression ? true-expression : false-expression;

For example, the two code snippets are equivalent.

// with if statement

if (x > 0)

y = 1;

else

y = -1;

// with conditional expression

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

Ex: Write a program that reads a number and prints "Even" if the number is even, and "Odd" if

the number is odd.

Solution:

Scanner input = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = input.nextInt();

System.out.println((number % 2 == 0)? "Even": "Odd");

Operator Precedence and Associativity

Operator precedence and associativity determine the order in which operators are evaluated.

Operators are listed in decreasing order of precedence from top to bottom. The logical

operators have lower precedence than the relational operators and the relational operators

have lower precedence than the arithmetic operators. Operators with the same precedence

appear in the same group.

Page 10: Computer Programming, I Laboratory Manual Experiment #3

Experiment #3: Selections

10

All binary operators except assignment operators are left associative.

Assignment operators are right associative.

Lab Work

Ex1: Write a program that prompts the user to enter a decimal number and check if the

fractional part is zero or not.

1st Solution:

Page 11: Computer Programming, I Laboratory Manual Experiment #3

Experiment #3: Selections

11

Scanner input = new Scanner(System.in);

System.out.print("Enter a number: ");

double number = input.nextDouble();

if (number % 1 == 0)

System.out.println("fraction is 0");

else

System.out.println("fraction isn't 0");

2nd Solution:

Scanner input = new Scanner(System.in);

System.out.print("Enter a number: ");

double number = input.nextDouble();

System.out.println((number%1 == 0)? "frac. is 0":"frac. not 0");

Ex2: Write a program that reads three edges for a triangle and computes the perimeter if the

input is valid. Otherwise, display that the input is invalid.

The input is valid if the sum of every pair of two edges is greater than the remaining edge.

Solution:

Scanner input = new Scanner(System.in);

System.out.print("Enter edge1: ");

double edge1 = input.nextDouble();

System.out.print("Enter edge2: ");

double edge2 = input.nextDouble();

System.out.print("Enter edge3: ");

double edge3 = input.nextDouble();

if (edge1 + edge2 > edge3 && edge2 + edge3 > edge1

&& edge1 + edge3 > edge2)

System.out.println("The perimeter is: " + (edge1 + edge2 + edge3));

else System.out.println("Wrong inputs");

Ex3: Write a program that prompts the user to enter a point (x, y) and checks whether the

point is within the circle centered at (0 ,0) with radius 10. For example, (4, 5) is inside the

circle and (9, 9) is outside the circle.

Solution:

Page 12: Computer Programming, I Laboratory Manual Experiment #3

Experiment #3: Selections

12

Scanner input = new Scanner(System.in);

// Enter a point with two double values

System.out.print("Enter a point with two coordinates: ");

double x = input.nextDouble();

double y = input.nextDouble();

// Compute the distance

double distance = Math.sqrt(x * x + y * y);

if (distance <= 10)

System.out.println("Point (" + x + ", " + y +

") is in the circle");

else

System.out.println("Point (" + x + ", " + y +

") is not in the circle");

Homework

1. (3.8) Write a program that prompts the user to enter three integers and display the

integers in increasing order.

2. (3.9) An ISBN-10 (International Standard Book Number) consists of 10 digits:

d1d2d3d4d5d6d7d8d9d10. The last digit, d10, is a checksum, which is calculated from the

other nine digits using the following formula:

(d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11

If the checksum is 10, the last digit is denoted as X according to the ISBN-10

convention. Write a program that prompts the user to enter the first 9 digits and

displays the 10-digit ISBN (including leading zeros). Your program should read the input

as an integer. Here are sample runs:

Enter the first 9 digits of an ISBN as integer: 013601267

The ISBN-10 number is 0136012671

Enter the first 9 digits of an ISBN as integer: 013031997

The ISBN-10 number is 013031997X

Hint: use String.format("%09d", number) to print a number with leading zeros

Page 13: Computer Programming, I Laboratory Manual Experiment #3

Experiment #3: Selections

13

3. (3.26) Write a program that prompts the user to enter an integer and determines

whether it is divisible by 5 and 6, whether it is divisible by 5 or 6, and whether it is

divisible by 5 or 6, but not both. Here is a sample run:

Enter an integer: 10

Is 10 divisible by 5 and 6? false

Is 10 divisible by 5 or 6? true

Is 10 divisible by 5 or 6, but not both? true

4. (3.33) Suppose you shop for rice in two different packages. You would like to write a

program to compare the cost. The program prompts the user to enter the weight and

price of each package and displays the one with the better price. Here is a sample

run:

Enter weight and price for package 1: 50 24.59

Enter weight and price for package 2: 25 11.99

Package 2 has a better price

Good Luck

😊