<<

CS-121 Programming I

Dr. Nagia M. Ghanem [email protected]

Topics

• Algorithms & Design • Tracing • Identifiers • Variables • Primitive Date Types • Literals • Named Constants

2 Algorithms and Design • If we want to write a program for solving a given problem, this involves 2 basic steps: 1. Write an algorithm for solving the problem (write recipe). 2. Write code for implementing the algorithm (carry out recipe).

• We cannot skip first step and go directly to second step.

3 Algorithm • An algorithm, named after the ninth century scholar Abu Jafar Al-Khowarizmi, is defined as follows: – An algorithm is a set of rules for carrying out calculation either by hand or on a machine (like a recipe).

• Two ways to write algorithms: – Pseudo-code – Flowcharts

4 Algorithm - Pseudocode • Pseudocode is an artificial and informal language that helps programmers develop algorithms. Pseudocode is very similar to everyday English.

• Operations involved in an algorithm – Output ( print “Hello Worlds!”) – Input (input height, input width) – Compute value of a given variable (set rectangleArea  height*width) – Conditions (if height = 0 then set rectangleArea  0 ) – Loops (while count <=100 ………)

5

Pseudocode & Algorithm

• Example 1: Write an algorithm to determine a student’s final grade and indicate whether it is passing or failing. The final grade is calculated as the average of four marks.

6 Pseudocode & Algorithm

Pseudocode: • Input a set of 4 marks • Calculate their average by summing and dividing by 4 • if average is below 50 Print “FAIL” else Print “PASS”

7 Pseudocode & Algorithm

• Detailed Algorithm • Step 1: Input M1,M2,M3,M4 Step 2: GRADE  (M1+M2+M3+M4)/4 Step 3: if (GRADE < 50) then Print “FAIL” else Print “PASS” endif

8 The Flowchart

• A graphical representation that shows the flow of control in a program.

• Flow of Control: – Order of which program statements are executed.

• Different symbols are used to draw each type of flowchart.

9 Flowchart Symbols

Name Symbol BasicUse in Flowchart

Oval Denotes the beginning or end of the program

Parallelogram Denotes an input operation

Rectangle Denotes a process to be carried out e.g. addition, subtraction, division etc.

Diamond Denotes a decision (or branch) to be made. The program should continue along one of two routes. (e.g. IF/THEN/ELSE)

Hybrid Denotes an output operation

Flow line Denotes the direction of logic flow in the program

10 Example

START Step 1: Input M1,M2,M3,M4 Step 2: GRADE  (M1+M2+M3+M4)/4 Input M1,M2,M3,M4 Step 3: if (GRADE <50) then Print “FAIL” else  GRADE (M1+M2+M3+M4)/4 Print “PASS” endif

N IS Y GRADE<50

PRINT PRINT “PASS” “FAIL”

STOP

11 Tracing (Analysis)

• Step through an algorithm (program) line by line and carefully record everything that happens.

• Build Tracing table : one column for every variable and one column for output

Set num to 2 num count Output Set count to 1 2 1 While count < 5 set count  count*num 2 Hello if (count/2) < 2 The count is 2. print “Hello” else 4 set count count+1 5 The count is 5. endif print “The count is” + count+”.”

12 Variables and Types

• A variable is a location in memory where values can be stored and referenced.

• Variables are associated with types, which have particular data sizes and a restricted set of valid operations that can be performed on them.

• Variable declarations assign an identifier, a type, and may declare an initial value. Many types have a default value. For example, an uninitialized integer defaults to 0.

• All program variables must be declared before using them

Variable (a memory location) a value (a default value)

address a type

a name (identifier)

Declaration Rules Must be declared with name and type Value is optional Cannot have two variables with same name and different type

Identifiers • Names in programs are called identifiers.

• An identifier is the name of something (e.g. a variable, object, or method) used in a Java program.

• Syntax rules for identifiers tell what names are allowed.

• Naming conventions are not required by the compiler but are good practice.

15 Syntax Rules for Identifiers • Always start with a letter.

• Can include, digits, , characters 'a' through 'z', 'A' through 'Z', '0' through '9', ‘_’ and '$'.

• Cannot be reserved words / keywords (e.g. “if,” “for”, public, static, class, and void, )

• Cannot have a digit for the first character.

16 Syntax Rules for Identifiers • Cannot have spaces or dots.

• have no official length limit (there is always a finite limit, but it is very large and big enough for reasonable names)

• Must be unique within its scope

• are case sensitive! – hope, Hope and HOPE are three valid and different identifiers, so be sure to be careful in your typing!

17 Naming Conventions • Choose meaningful and descriptive names.

• Variables and method names: – Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computeArea.

• Class names: – Capitalize the first letter of each word in the name. For example, the class name ComputeArea.

• Constants: – Capitalize all letters in constants. For example, the constant PI.

Java Data Types • Java Data Types – Boolean – Character – Integer – Floating point

19 Boolean Data Type

• Boolean variables can only take the values true or false.

• They are often used to test for conditions in a program.

• Memory space: 1 bit

• Examples: – boolean status = true; – boolean isNegative = false;

20 Characters • Character variables can store one character.

• A character value is a character surrounded by single quotes – char pLetter = 'P‘

• Characters are actually stored as integers according to a special code – each printable character (letter, number, punctuation mark, space, and tab) is assigned a different integer code – the codes are different for upper and lower case – for example 97 may be the integer value for ‘a’ and 65 for ‘A’

• ASCII and Unicode are common character codes

21 Characters

• Unicode includes all the ASCII codes plus additional ones for languages with an alphabet other than English

• Java uses Unicode

• All characters are represented by 16-bit Unicode.

• '\u' followed by four digits represent 16 bit Unicode character. char x = '\u1234‘

22 Integers • An integer is any whole number, negative or positive, including 0. • In Java, we can have integers of different sizes – long (8 ) can store values from -263 to 263 -1 – int: (4 bytes) can store values from -231 to 231 -1 – short: (2 bytes) can store values from -215 to 215 -1 – : (1 byte) can store values from -128 to 127 • When using integers, we usually use int • Examples: – byte b = 127; – short s = -32768; – int i = 4;

23 Floating Point Numbers • Floating-point numbers are used to represent reals, i.e. numbers that may have fractional parts, e.g. – 123.4, 55., .99

• The Java floating-point types are: – float: 32 bits – double: 64 bits

• A float literal ends with 'f'.

• Examples: – float f = 123.4f – float f2 = .99f

• A floating-point literal is by default of type double

24 Java Primitive Types

25 Declaring Variables int x; // Declare x to be an // integer variable; double radius; // Declare radius to // be a double variable; char a; // Declare a to be a // character variable; Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a;

Declaring and Initializing in One Step

• int x = 1; • double = 1.4; • float f = 1.4; Is this statement correct? Literals • A literal is a constant value that appears directly in the program. – 10 a literal that specifies an integer – 3.14 specifies a floating point value – true specifies a Boolean value – 'X' specifies a character constant – "Hello" specifies a string

• For example, 34, 1,000,000, and 5.0 are literals in the following statements: int i = 34; long l = 1000000; double d = 5.0;

Integer Literals

• An integer literal can be assigned to an integer variable as long as it can fit into the variable.

• A compilation error would occur if the literal were too large for the variable to hold. For example, the statement byte b = 1000 would cause a compilation error, because 1000 cannot be stored in a variable of the byte type.

• An integer literal is assumed to be of the int type, whose value is between -231 (-2147483648) to 231–1 (2147483647).

• To denote an integer literal of the long type, append it with the letter L or l. L is preferred because l (lowercase L) can easily be confused with 1 (the digit one).

• What about and hexadecimal literals?

Floating-Point Literals

• Floating-point literals are written with a decimal point.

• By default, a floating-point literal is treated as a double type value. For example, 5.0 is considered a double value, not a float value.

• You can make a number a float by appending the letter f or F, and make a number a double by appending the letter d or D. • For example, – 100.2f or 100.2F for a float number – and 100.2d or 100.2D for a double number. Scientific Notation

• Floating-point literals can also be specified in scientific notation.

• for example: – 1.23456e+2, same as 1.23456e2, is equivalent to 123.456 – 1.23456e-2 is equivalent to 0.0123456.

• E (or e) represents an exponent and it can be either in lowercase or uppercase. Named Constants

• Useful when you want a variable whose value never changes

• Use the modifier final in its declaration

• Example 1: final int US_Population = 278058881;

• Example 2: – Hard-coded constants (Literals)

double celsius= (5.0/9.0) * (fah- 32.0);

– Named Constants

final double FREEZING_POINT = 32.0; final double CONVERSION_FACTOR = 5.0/9.0; double Fah=50; double celsius= CONVERSION_FACTOR * (fah- FREEZING_POINT);

33 Helping Material

• Java 2, the Complete Reference, 7th edition, Herbert Schildt, 2007, ISBN: 0-07- 222420-7 – Chapter 3 till page 41

• Next time.. – Expressions and Operators – Expression Evaluation & Operator Precedence – Type Casting

34