Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 201 Lecture 2: Elementary Programming Tarik Booker CS 201 California State University, Los Angeles.

Similar presentations


Presentation on theme: "CS 201 Lecture 2: Elementary Programming Tarik Booker CS 201 California State University, Los Angeles."— Presentation transcript:

1 CS 201 Lecture 2: Elementary Programming Tarik Booker CS 201 California State University, Los Angeles

2 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

3 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

4 Simple Program (2) Ex: ◦ Create an algorithm for calculating the area of a circle  You need:  Radius  Pi  Formula  What is the answer?

5 Simple Program (3) Ex: ◦ Compute Circle Area:  Get the radius of the circle  Compute the area of the circle  Area = radius 2 * pi  (or radius * radius * pi)  Display the output

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

7 Simple Program (5) We need to do three things to complete our program ◦ Get the radius value in ◦ Compute the radius ◦ Display the radius

8 Simple Program (6) Get radius value in ◦ Console Input Compute Area ◦ Computation, Variables, etc. Display the Result ◦ Console Output  You know how

9 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

10 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

11 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

12 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

13 Identifiers (2) Which are legal?  helloworld  aadzxvcna343546390  HappyHappy  34joy56  $ke$ha  static  Strings  #love  Why / Why not?

14 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;

15 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);

16 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?

17 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;

18 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

19 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

20 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

21 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  byte8-bit  short16-bit  int32-bit  long64-bit  All are signed (can include negative sign)

22 Numeric Data Types (3) Integer Range ◦ Depends on bit size (n)  (2 n / 2) -1  Note: Equivalent to 2 (n-1) - 1  (Take the whole range, divide by 2, account for zero)  Byte range (8-bit)?  -2 7 to 2 7 - 1  Int range (32-bit)?

23 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

24 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

25 Numeric Operators Java includes standard arithmetic operators  Addition+  Subtraction-  Multiplication*  Division/

26 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

27 Exponent Operations Use the Math.pow(a,b) method ◦ Returns a b ◦ (Don’t use karet ^) ◦ Ex:  System.out.println(Math.pow(2,3));

28 Numeric Literals Literal – Constant values that appear in a program ◦ Ex:int numberOfYears = 34; ◦ Or:double weight = 0.305  34 and 0.305 are literals ◦ Different types of literals  Integer  Floating-Point

29 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

30 Numeric Literals (3) Can also use binary integer literals  Start with 0B or 0b (zero b)  Ex: 0B1111results in 15 Also can use octal (base 8) and hexadecimal (base 16) integer literals  Octal: Start with 0  Ex: 07777results in 4095  Hex: Start with 0x or 0X (zero x)  Ex: 0XFFFFresults in 65535

31 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.2345E2results in 1.2345 x 10 2 r

32 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__67  No! No! No!

33 Evaluating Expressions / Operator Precedence

34 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

35 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

36 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;

37 Increment / Decrement Operators Shorthands for incrementing and decrementing variables; ◦ ++, - - ◦ Adds (++) or Subtracts (--) by one  Ex: int i = 3;  i++;  Result?  Ex:int z = 4;  z--; ◦ Can put before (++i) or after variable (z--)

38 Increment / Decrement Operators (2) If used alone (i++, or --z) direction doesn’t matter. ◦ Ex:++j; ◦ or:j++;// Doesn’t matter If used within an expression (or statement), direction does matter

39 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?

40 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?

41 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”

42 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)

43 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

44 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 = radius 2 * 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!

45 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

46 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

47 Console Input (3) Can read in other types: ◦ nextByte() ◦ nextShort() ◦ nextInt() ◦ nextLong() ◦ nextFloat() ◦ nextDouble()

48 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();

49 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

50 Return to Simple Program (2) Objective ◦ Compute Circle Area:  Get the radius of the circle  Compute the area of the circle  Area = radius 2 * 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

51 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

52 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;

53 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

54 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); }

55 Simple Programming Let’s cover more examples!


Download ppt "CS 201 Lecture 2: Elementary Programming Tarik Booker CS 201 California State University, Los Angeles."

Similar presentations


Ads by Google