Download CS 201 Lecture 2: Elementary Programming - csns

Document related concepts
no text concepts found
Transcript
CS 201 Lecture 2: Elementary
Programming
Tarik Booker
CS 201
California State University, Los Angeles
What we will cover…











Review
A Simple Program
Console Input
Identifiers
Variables
Assignment Statements and Operators
Named Constants
Numeric Literals
Evaluating Expressions
Increment/Decrement Operators
Type Conversions
Simple Programming
Solve a Problem
 Use programming language

◦ Algorithm – describes how the problem is
solved
 Natural language or pseudocode
 Language mixed with programming code
◦ Coding – Translate algorithm into program
Simple Program (2)

Ex:
◦ Create an algorithm for calculating the area of
a circle
 You need:
 Radius
 Pi
 Formula
 What is the answer?
Simple Program (3)

Ex:
◦ Compute Circle Area:
 Get the radius of the circle
 Compute the area of the circle
 Area = radius2 * pi
 (or radius * radius * pi)
 Display the output
Simple Program (4)

Java code format:
public class ComputeArea{
public static void main(String[] args){
// Read in radius
// Compute area
// Display area
}
}

We have translated algorithm into Java
code
 (Not finished yet!)
 We will come back to this!
Simple Program (5)

We need to do three things to complete
our program
◦ Get the radius value in
◦ Compute the radius
◦ Display the radius
Simple Program (6)

Get radius value in
◦ Console Input

Compute Area
◦ Computation, Variables, etc.

Display the Result
◦ Console Output
 You know how
Variables

Can store values to be used (later) in a
program
◦ Values can be changed
◦ Remember algebra:
 x + y = 34
y=5
 x =?
◦ Similar Concept in Programming
Variables (2)

You must declare a variable in a program
before you use it
◦ Format:
 datatype variableName;
 A variable can be of any name
 Follow identifier rules (later…)
 Descriptive names are best
 Our simple program:
 area
 radius
 pi
Variables (3)

Datatype variableName;
 Datatype variableName1, variableName2,
…,variableName3;

Datatype




Specific classification of variables
Different types / different memory sizes
int, double
(main ones)
Byte, short, long, float, char, boolean
 Discuss later
Identifiers

To name variables, classes, methods
◦ Called identifiers
 Should obey rules:
 Consists of letters, digits, underscores (_), dollar
signs ($)
 Must start with letter, underscore, or dollar sign
 Must NOT start with a digit!!!
 Cannot be a reserved word (class, public, main,
etc.)
 Cannot be true, false, null
 Can be any length
Identifiers (2)

Which are legal?









helloworld
aadzxvcna343546390
HappyHappy
34joy56
$ke$ha
static
Strings
#love
Why / Why not?
Assignment Statements/Expressions

After declaring a variable, you must assign
it a value.
◦ Use the assignment operator (=)




int myNumber;
myNumber = 1;
Assigns the value 1 to variable myNumber
Note:You can assign a value to a variable in the
variable declaration statement!!!
 Ex:
 int myNumber = 1;
 double volume = 3.0;
Assignment Statements/Expressions
(2)

Assigning a value to a variable results in
an assignment statement
◦ double volume = 5.0;

You can also assign the results of an
expression to a variable
◦ double volume = 5.0 * 3.0;
◦ int x = 5 * (3 / 2);
Assignment Statements/Expressions
(3)

You can use other variables inside of
expressions!
◦ Can also use the same variable!
◦ int x = 1;
◦ x = x + 1;
 Executes Right-Hand Side (RHS) first, then assigns
the result to the Left-Hand Side (LHS)
 What is x after the code?
Constants
Variable values can change during a
program
 (Named) Constants are permanent
(throughout the life of the program)

◦ You can define constants
◦ Use the final keyword
 final datatype constantname = value;
 Ex:
 final double PI = 3.14159;
Naming Conventions

There are established conventions for
naming various things in Java
◦ Variables and methods
 Use lowercase
 If a name has multiple words, combine them into
one, make the first word lowercase, then capitalize
the first letter of each other word




properVariableName
correctMethodName
radius
volume
Naming Conventions (2)

Classes
◦ Capitalize the first letter of each word
 GoodClass
 ComputeArea
 System

Constants
◦ Capitalize every letter, and use underscores
between each word
 PI
 MAX_VALUE
Numeric Data Types

(Numeric) Data Types represent different
ways to store numeric values in a variable
◦ Variables are stored in (primary) memory
◦ Different data types take up different spaces
in memory
Numeric Data Types (2)

Integer Data Types
◦ Used to store integers
 …, -10, -9, …, -3, -2, -1, 0, 1, 2, 3, …, 9, 10, …
 Java has 4 different integer types




byte
short
int
long
8-bit
16-bit
32-bit
64-bit
 All are signed (can include negative sign)
Numeric Data Types (3)

Integer Range
◦ Depends on bit size (n)
 (2n / 2) -1
 Note: Equivalent to 2(n-1) - 1
 (Take the whole range, divide by 2, account for
zero)
 Byte range (8-bit)?
 -27 to 27 - 1
 Int range (32-bit)?
Numeric Data Types (4)

Floating-Point Data Types
◦ Written in Scientific Notation
 Mantissa Exponent
◦ Two types of floating-point numbers
 float
 floating point (single precision)
 double
 Double precision
 Twice as big as float
Numeric Data Types (5)

Floating Point Range
◦ Float
 Negative range:
 -3.402823E+38 to -1.4E -45
 Positive range:
 1.4E-45 to 3.402823e+38
◦ Double
 Negative range:
 -1.7976931348623157e+308 to -4.9e-324
 Positive range:
 4.9e-324 to 1.7976931348623157e+308
Numeric Operators

Java includes standard arithmetic
operators




Addition
Subtraction
Multiplication
Division
+
*
/
Numeric Operators (2)

Also has modulus (%)
 Also called the remainder operator
 Gives the remainder after division







6%2 (Say 6 “mod” 2)
What is 6%2?
3%1
1%3
10%5
Any even number % 2?
Any odd number % 2?
 Can use this to check evens or odds
Exponent Operations

Use the Math.pow(a,b) method
◦ Returns ab
◦ (Don’t use karet ^)
◦ Ex:
 System.out.println(Math.pow(2,3));
Numeric Literals

Literal – Constant values that appear in a
program
◦ Ex:
◦ Or:
int numberOfYears = 34;
double weight = 0.305
 34 and 0.305 are literals
◦ Different types of literals
 Integer
 Floating-Point
Numeric Literals (2)

Integer Literals:
◦ Can be assigned to an integer variable
◦ Works so long as it is within the range of the
variable type
◦ Assumed to be type int (32-bit range)
◦ For type long, append the letter L to it
 Ex: 2145063967L
Numeric Literals (3)

Can also use binary integer literals
 Start with 0B or 0b (zero b)
 Ex: 0B1111

results in 15
Also can use octal (base 8) and
hexadecimal (base 16) integer literals
 Octal: Start with 0
 Ex: 07777
results in 4095
 Hex: Start with 0x or 0X (zero x)
 Ex: 0XFFFF
results in 65535
Numeric Literals (4)

Floating-Point Literals
◦ Written with a decimal point
 Ex: 5.0
◦ Default is double
 Make literal float by adding an f
 Ex: 100.2f
 Note: double has more significant digits (15-18)than
float (7-8)
◦ Can also write in scientific notation
 1.2345E2
results in 1.2345 x 102r
Numeric Literals (5)

You can also use underscores between
two digits in a numeric literal
◦ Helpful in separating out digits
 For specific formats
 Ex: long ssn = 123_45_6789;
 Results in ssn = 123456789
 Stored as a plain number, but easier to input
 Note: Do not use underscores next to a single
digit!
 WRONG:
23_
 No! No! No!
_67
Evaluating Expressions / Operator
Precedence
You can take any mathematical expression
and translated into code
 Make sure you use parentheses whenever
appropriate

◦ Ex:
z=
3+4𝑥
10
+
10(𝑦−3)
7
−
4
9( )
𝑥
◦ Result:
 z = (3+4*x)/ 10 + 10 * (y-3) / 7 – 9*(4 / x);
Order of Operations

What’s the order of operations?
◦ PEMDAS
◦ Please Excuse my Dear Aunt Sally
◦ Parentheses, Exponent, Multiplication, Division,
Addition, Subtraction
◦ Equal operators (M, D, and A,S) go from left to
right
Augmented Assignment Operators

You can combine arithmetic operators
and the assignment operator to perform
augmented operators!!
 Ex: x = x + 1;
 1 is added to x, and the result is put back into itself
 Will happen often (later)
 Can shorten this to:
 x += 1;
 This is translated as x = x + 1;
 Works for other operators
Augmented Assignment Operators
(2)

Addition
◦ x += 1;
 Result:

x = x + 1;
Subtraction
◦ x -= 5;
 Result:

x = x – 5;
Multiplication
◦ y *= 3;
 Result:

y = y * 3;
Division
◦ volume /= 7;
 Result:

volume = volume / 7;
Remainder
◦ i %= 5;
 Result:
i = i % 5;
Increment / Decrement Operators

Shorthands for incrementing and
decrementing variables;
◦ ++, - ◦ Adds (++) or Subtracts (--) by one
 Ex: int i = 3;
 i++;
 Result?
 Ex:
 z--;
int z = 4;
◦ Can put before (++i) or after variable (z--)
Increment / Decrement Operators
(2)

If used alone (i++, or --z) direction
doesn’t matter.
◦ Ex:
◦ or:

++j;
j++;
// Doesn’t matter
If used within an expression (or
statement), direction does matter
Increment / Decrement Operators
(3)

Preincrement / Predecrement
◦ Ex:
++var
--count
◦ If used within an expression, the variable is
incremented (or decremented) first, then used
in the statement
◦ Ex:
int j = ++i;
 If i is 2, what is j?
◦ Ex:
System.out.println(5 * --i);
 What is printed if i is 6?
Increment / Decrement Operators
(4)

Postincrement / Postdecrement
◦ Ex:
var++
count-◦ If used within an expression, the variable is
used in the statement first, then incremented
(or decremented) afterward
◦ Ex:
int j = i++;
 If i is 2, what is j?
◦ Ex:
System.out.println(5 * i--);
 What is printed if i is 6?
Numeric Type Conversions

You can have expressions with multiple
variables of different data types
◦ There are different rules when converting types
 For floating-point and integer, Java will convert the
integer into a floating-point value
 Ex: 3 * 4.5 converts to 3.0 * 4.5

You can also assign a variable value to a
variable that has a larger range
◦ Assign a long to a float
◦ Called “widening a type”
Numeric Type Conversions (2)

You cannot assign a variable of a
larger type to a variable of a smaller
type without performing a special
operation!
◦ Called casting
◦ Smaller range to higher range
 Widening a type (automatic in Java)
◦ Larger range to smaller range
 Narrowing a type (explicit in Java)
Numeric Type Conversions (3)

Casting:
◦ Determine the type you want
◦ Write the desired datatype within
parentheses.
◦ Put that next to the value you want to cast
 Ex:
System.out.println((int)1.7));
 Note, this converts a floating point to an integer.
 This will truncate the decimal value (resulting in 1)
 Ex:
System.out.println((double)1/2));
 Will cast this to a double, and result in 0.5
 Without it, this results in integer division and return 0
 Decimal truncated
Return to Simple Program

Now we have more tools:
◦ Compute Circle Area:
 Get the radius of the circle
 Compute the area of the circle
 Area = radius2 * pi
 (or radius * radius * pi)
 Display the output
We now know how to use variables and
operations to get a numerical result.
 We know how to display output
 Now we need to get that radius!

Console Input

So far, if you wanted a specific value (for
radius, etc) you had to re-compile it
◦ Not very convenient
◦ We need a way to get information from the
console
 Can already print info out to the console
 System.out.println()
 Java doesn’t directly support console input
 System.in. Not for us…
 Instead use Scanner class with console input
Console Input (2)

Easy to use
◦ Scanner input = new Scanner(System.in);
◦ Creates a new Scanner object.
 Scans System.in (console input) for information
 Input becomes an object
 Can use methods that come with the Scanner class
 nextDouble()
 Double radius = input.nextDouble();
 Reads in a double from console input and assigns the value
to the double radius
Console Input (3)

Can read in other types:
◦
◦
◦
◦
◦
◦
nextByte()
nextShort()
nextInt()
nextLong()
nextFloat()
nextDouble()
Console Input (4)

Ex:
Scanner input = new Scanner(System.in);
System.out.print(“Enter a byte value: “);
byte byteValue = input.nextByte();
Scanner input = new Scanner(System.in);
System.out.print(“Enter an int value: “);
int intValue = input.nextInt();
Console Input (4)

To use:
◦ Make sure you import the Scanner class
 import java.util.Scanner;
 The class is part of the java.util package
 Not standard
 Put this at the top of the program
◦ You can import all packages in java.util
 Iimport java.util.*;
 * = wildcard
 All / Any
◦ Specific Import / Wildcard import
Return to Simple Program (2)

Objective
◦ Compute Circle Area:
 Get the radius of the circle
 Compute the area of the circle
 Area = radius2 * pi
 (or radius * radius * pi)
 Display the output

Java code format:
public class ComputeArea{
public static void main(String[] args){
// Read in radius
// Compute area
// Display area
}
}

Now we can create program
Return to Simple Program (3)

//Read in Radius
◦ How do we do that?
◦ Use Scanner class
Scanner input = new Scanner(System.in);
System.out.print(“Enter a number for radius: ”);
double radius = input.nextDouble();
◦ This reads a double in from the console and
puts it into the radius variable
Return to Simple Program (4)

// Compute Area
◦ How? We now have radius
◦ Let’s make PI a constant!
final double PI = 3.14159;
◦ Let’s compute
double area = radius * radius * PI;
Return to Simple Program (5)

// Display Area
◦ We already know how to do that:
System.out.println(“The area for the circle of radius “ + radius + “is
” + area);
◦ Now let’s put all of this in one program
Return to Simple Program (6)

Final Program:
public class ComputeArea{
public static void main(String[] args){
final double PI = 3.14159;
// Read in radius
Scanner input = new Scanner(System.in);
System.out.print(“Enter a number for radius: ”);
double radius = input.nextDouble();
// Compute area
double area = radius * radius * PI;
// Display area
System.out.println(“The area for the circle of radius “ + radius + “is ” + area);
}
}
Simple Programming

Let’s cover more examples!