Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Similar documents
Eng. Mohammed S. Abdualal

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

CEN 414 Java Programming

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

Introduction to Computers. Laboratory Manual. Experiment #3. Elementary Programming, II

Chapter 2. Elementary Programming

Chapter 2 Elementary Programming

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

In this lab, you will learn more about selection statements. You will get familiar to

Computer Programming, I. Laboratory Manual. Final Exam Solution

Chapter 2 ELEMENTARY PROGRAMMING

Programming with Java

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Elementary Programming

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Computer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters

Selection Statements. Pseudocode

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

Chapter 3. Selections

These are reserved words of the C language. For example int, float, if, else, for, while etc.

CS313D: ADVANCED PROGRAMMING LANGUAGE

Chapter 3 Selection Statements

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

CS1150 Principles of Computer Science Boolean, Selection Statements

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Date: Dr. Essam Halim

Computer System and programming in C

Introduction to Java Applications

CONDITIONAL EXECUTION: PART 2

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Lecture 3 Tao Wang 1

Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

Condi(onals and Loops

Getting started with Java

3. Java - Language Constructs I

Full file at

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS 106 Introduction to Computer Science I

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Selections. CSE 114, Computer Science 1 Stony Brook University

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

Chapter 4: Control Structures I

Programming Logic and Design Sixth Edition

Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool

Computer Programming: C++

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Following is the general form of a typical decision making structure found in most of the programming languages:

Java Notes. 10th ICSE. Saravanan Ganesh

Zheng-Liang Lu Java Programming 45 / 79

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

FRAC: Language Reference Manual

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Values in 2 s Complement

Values and Variables 1 / 30

Important Java terminology

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Arrays. Arrays (8.1) Arrays. One variable that can store a group of values of the same type. Storing a number of related values.

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Chapter 2: Using Data

Computer Programming : C++

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

Midterm Examination (MTA)

A Beginner s Guide to Programming Logic, Introductory. Chapter 6 Arrays

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Programming for Engineers Iteration

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. and Java. Chapter 2 Primitive Data Types and Operations

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Arithmetic Compound Assignment Operators

CS111: PROGRAMMING LANGUAGE II

Program Control Flow

Program Control Flow

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Values, Variables, Types & Arithmetic Expressions. Agenda

COMP6700/2140 Data and Types

Chapter 2 Primitive Data Types and Operations. Objectives

Chapter 2: Data and Expressions

1.3b Type Conversion

ECE 122 Engineering Problem Solving with Java

IEEE Floating-Point Representation 1

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Computer Programming: C++

Introduction to Programming Using Java (98-388)

CS302: Self Check Quiz 2

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

Java is an objet-oriented programming language providing features that support

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Transcription:

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

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). 2

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 3

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) { 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. 4

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) { 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? 5

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. 6

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; case value2: statement(s)2;... case valuen: statement(s)n; 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 switchexpression. 7

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: System.out.print("Enter your birth month, ex 5 : "); int month = input.nextint(); String monthstring; switch (month) { case 1: monthstring = "January"; case 2: monthstring = "February"; case 3: monthstring = "March"; case 4: monthstring = "April"; case 5: monthstring = "May"; case 6: monthstring = "June"; case 7: monthstring = "July"; case 8: monthstring = "August"; case 9: monthstring = "September"; case 10: monthstring = "October"; case 11: monthstring = "November"; case 12: monthstring = "December"; default: monthstring = "Invalid month"; System.out.println(monthString); 8

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: 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. 9

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. 1 st Solution: 10

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"); 2 nd Solution: 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: 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: 11

// 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: d 1d 2d 3d 4d 5d 6d 7d 8d 9d 10. The last digit, d 10, is a checksum, which is calculated from the other nine digits using the following formula: (d 1 * 1 + d 2 * 2 + d 3 * 3 + d 4 * 4 + d 5 * 5 + d 6 * 6 + d 7 * 7 + d 8 * 8 + d 9 * 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 12

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 13