0% found this document useful (0 votes)
5 views48 pages

Chapter 3

Uploaded by

6w6j8swbpt
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)
5 views48 pages

Chapter 3

Uploaded by

6w6j8swbpt
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/ 48

College of Computing

Department of Computer Science and


Artificial Intelligence

CS1211: Computer Programming

2nd Trimester : 2023/24

Lecture 3
Arithmetic Operations, and Console
Input/Output

Original Slides: Dr.Abdulbaset Gaddah


Modified by Dr. Malak AlJabri and Dr. Areej Althobiti 1
Revision

✔ Describe the Java data types used for simple


data
✔ Write Java statements to declare variables,
define named constants
✔ Write assignment statements

2
Revision: Basic Java Program Structure
•There are 5 components that we usually include in a Java
program, which are:

[ Documentation Statement(s) ]
[ Package Statement ]
[ Import Statement(s) ]
public class className {
public static void main(String[] args) {

[ Body of Main Function ]


}
}

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 3
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Objectives
• Write Arithmetic operations, expressions
containing variables and constants
• Write Java statements that accomplish
keyboard input,
screen output

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 4
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Arithmetic
Operations

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 5
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Arithmetic Operators

• Arithmetic expressions can be formed using the +, -, *, and /


operators together with variables or numbers referred to as
operands.

• When both operands are of the same type, the result is of that
type.

• Example: If num1 is an int to which the value 10 has been


assigned, and num2 is a int to which 15 has been assigned then
num1 + num2

is a int with a value of 25.

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 6
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Arithmetic Operators

• When one of the operands is a floating-point type and the other is


an integer, the result is a floating-point type.

• Example
• If hoursWorked is an int to which the value 40 has been
assigned, and payRate is a double to which 8.25 has been
assigned then
hoursWorked * payRate

is a double with a value of 500.0.

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 7
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Primitive Datatype and Common
Operations

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 8
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
The Division Operator

• The division operator (/) behaves as expected if


one of the operands is a floating-point type.

• When both operands are integer types, the result


is truncated, not rounded.
•The fraction after the decimal point is simply lost.
•Example: 99/100 has a value of 0.

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 9
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
The mod Operator

• The mod (%) operator is used with operators of integer type to


obtain the remainder after integer division.

• Example: 14 divided by 4 is 3 with a remainder of 2.


• Hence, 14 % 4 is equal to 2.

• The mod operator has many uses, including


• determining if an integer is odd or even
• determining if one integer is evenly divisible by another
integer.

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 10
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Arithmetic Expression

•An arithmetic expression combines operands, operators,


and parentheses

•Expressions with two or more operators can be viewed as a


series of steps, each involving only two operands.
•The result of one step produces one of the operands to
be used in the next step.

•Example
balance + (balance * rate)

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 11
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Arithmetic Expression

•If at least one of the operands is a floating-point


type and the rest are integers, the result will be a
floating_point type.

•The result is the rightmost type from the following


list that occurs in the expression.
byte --> short --> int --> long --> float --> double

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 12
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Parentheses and Precedence
• Parentheses can be used to make the code clearer.
balance + (interestRate * balance)

• Parentheses specify the order in which arithmetic operations are


performed

• Examples:
(cost + tax) * discount
(cost + (tax * discount))

• Without parentheses, an expressions is evaluated according to the


rules of precedence.
JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 13
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Precedence Rules
Operator Operation Precedence (order of evaluation)

* Multiplication Evaluated first. If there are several operators of this type,


they're evaluated from left to right.
/ Division
% Remainder
+ Addition Evaluated next. If there are several operators of
this type, they're evaluated from left to right.
– Subtraction

= Assignment Evaluated last.

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 14
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Precedence Rules

• If more than one operator of equal precedence could be


evaluated, evaluation occurs left to right.

• When unary operators have equal precedence, the operator on


the right acts before the operation(s) on the left.

• Spaces do not dictate precedence.


balance + interestRate*balance

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 15
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Precedence of Arithmetic Operators -
Examples
• What is the order of evaluation in the following
expressions?

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 16
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Sample of Arithmetic Expressions in
Java

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 17
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Shorthand Assignment Operator
• Assignment operators can be combined with arithmetic operators (including
-, *, /, and %, discussed later).
• The combination of an operator with the = used for assignment form is
called a shorthand assignment operator

• Example
amount = amount + 5;
can be written as
amount += 5;
yielding the same results.

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 18
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Increment and Decrement Operators
• Used to increase (or decrease) the value of a variable by 1
• They cannot be applied to constants! Why?

• Easy to use, important to recognize

• The increment operator ++


• ++ variable; //prefix form
• Variable++; //postfix form
• Example
count++ or ++count
• The decrement operator --
count-- or --count
JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 19
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Increment and Decrement Operators
•Equivalent operations
count++;
++count;
count = count + 1;

count--;
--count;
count = count - 1;

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 20
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Increment and Decrement Operators in
Expressions
•after executing
int m = 4;
int result = 3 * (++m)
result has a value of 15 and m has a value of 5

•after executing
int m = 4;
int result = 3 * (m++)
result has a value of 12 and m has a value of 5

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 21
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Keyboard and
Screen I/O

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 22
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Scanner Class

• Scanner is a class that provides methods for inputting words,


numbers, and other data.

• Scanner is provided by java.util, which is a package that contains


various “utility classes”.

• Before we could use Scanner , we have to import it (just


before public class ClassName) like this:
import java.util.Scanner;

This statement tells the compiler which Scanner class we are referring
to because there might be another class named Scanner

23
Scanner Class
• To initialize the Scanner class, we have to declare/define a Scanner
variable/object named keyboard and creates a Scanner that reads
input from System.in:

• Syntax:
Scanner keyboard= new Scanner (System.in);

Note:
• The new operator return a reference to the variable keyboard in the
memory
• you may name the Scanner variable any name you wish such as: in,
src, source, etc

24
Some Scanner Class Methods

25
Some Scanner Class Methods

26
Keyboard Input Demonstration

27
Keyboard Input Demonstration

Sample
screen
output

28
nextLine()Method Caution
• The nextLine() method reads
• The remainder of the current line,
• Even if it is empty.

• Example
int n;
String s1, s2;
Scanner keyboard = new Scanner (System.in);

n = keyboard.nextInt();
s1 = keyboard.nextLine();
s2 = keyboard.nextLine();

System.out.println ("n: " + n);


System.out.println ("s1: " + s1);
System.out.println ("s2: " + s2);

29
nextLine()Method Caution
• Why when we read a String followed by an int, everything works just fine.
But when we read an int followed by a String, something strange happens?

• Scanner doesn’t see input as multiple lines as we do; but as a stream of


characters!
42 \n a n d d o n ' t y o u \n

• nextInt returns the value 42. The program then waits for the user to enter
s1 and runs nextLine, which reads characters until it gets to a newline.

• But since the next character is already a newline, nextLine returns the
empty string "".

30
nextLine()Method Caution
• How can we solve this problem?
• We need an extra nextLine after nextInt :
int n;
String s1, s2;
Scanner keyboard = new Scanner (System.in);

n = keyboard.nextInt();
keyboard.nextLine(); //// read the newline
s1 = keyboard.nextLine();
s2 = keyboard.nextLine();

System.out.println ("n: " + n);


System.out.println ("s1: " + s1);
System.out.println ("s2: " + s2);

31
Keyboard Input Demonstration

32
Keyboard Input Demonstration

Sample
Screen
Output

33
Screen Output
•We've seen several examples of screen output already.
•Example:
System.out.println("Enter a whole number from 1
to 99.");

System.out.println(quarters + "quarters");

•Where:
• System is a standard class
• System.out is an object that is part of Java.
• println() is one of the methods available to the

34
Screen Output

• Syntax to use println


System.out.println (Output_1 + Output_2 + … +
Output_Last);

• The concatenation operator (+) is useful when everything does


not fit on one line.
System.out.println("Lucky number = " + 13
+"Secret number = " + number);
the output will be
Note, for readability, you
Lucky number = 13Secret number = 7 should break the line
before or
after a + operator, and you
should indent
the continuation line. 35
Screen Output

• You can also use the println method to display the value of a
String variable

• Example:
String greeting = "Hello Programmers!";
System.out.println(greeting);

This will cause the following to be written on the screen:


Hello Programmers!

36
Screen Output
•Every invocation of println ends a line of output I.e. it
inserts a new line!

•Alternatively, use print()


System.out.print("One, two,");
System.out.print(" buckle my shoe.");
System.out.println(" Three, four,");
System.out.println(" shut the door.");

produces the following output:


One, two, buckle my shoe. Three, four,
shut the door.

37
Escape Characters

•How would you print "Java" refers to a


language.?

•The compiler needs to be told that the quotation marks (")


do not signal the start or end of a string, but instead are to
be printed.

•We use \ before an escape character


System.out.println("\"Java\" refers to a language.");

38
Escape Characters

•Each escape sequence is a single character even though it is


written with two symbols.

39
Printing Escape Characters Examples

System.out.println("abc\\def"); abc\def

new
System.out.println("new\nline");
line

char singleQuote = '\'';


'
System.out.println
(singleQuote);

40
Formatted Output with printf ( )
• printf works like the print method except it allows you to add
formatting instructions that specify things such as the number of
digits to include after a decimal point.
• Example,
double price = 19.5;
System.out.println("Price using println:" + price);
System.out.printf("Price using printf formatting:%6.2f", price);

This code outputs the following lines: The format specifier %6.2f
says to output a floating-point
Price using println:19.5 number in a field (number of
Price using printf formatting: 19.50 spaces) of width six (room for
six characters) and to show
exactly two digits after the
decimal point. So, 19.5 is
expressed as "19.50" in a
field of width six.
41
Common Format Specifiers

42
Common Format Specifiers Example
double price = 19.5;
int quantity = 2;
String item = "Widgets";

System.out.printf("%10s sold:%4d at $%5.2f. Total =


$%1.2f", item, quantity, price, quantity * price);

the output is:


Widgets sold:2 at $19.50. Total = $39.00

43
Q/Show the exact output produced by the following
println methods:

int counter = 5;
System.out.println("counter = " + counter++);

//counter = 5
System.out.println("counter = " + counter%2);

// counter = 0

44
Q/Show the exact output produced by the following
println methods:

System.out.println("hello "+"programmers!");

A. "hello " + "programmers!"


B. hello programmers!
C. Nothing!

Q/The main difference between print and println


methods is:
A. println adds new line
B. They spelled differently!
C. No difference!

45
Summary
• You have learned about assignment
statements and expressions.
• You have learned about simple keyboard
input and screen output.

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 46
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Reading

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 47
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved
Questions?

JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch 48
ISBN 0134462033 © 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved

You might also like