Professional Documents
Culture Documents
Unit 2 Fun Pro I
Unit 2 Fun Pro I
Introduction to programming
2.1. Introduction
2.2. General concepts
2.3. Data types
2.3.1. Types of primitive data
2.3.2. Variables and constants
2.3.3. Internal data representation
2.3.4. Type conversions
2.3.5. Strings
2.4.Instructions
2.4.1. Assignment instructions
2.4.2. Input/output instructions
2.5.Operators
2.5.1. Arithmetic and assignment operators
2.5.2. Increment and decrement operators
2.5.3. Relational operators
2.5.4. Logical operators
Programming Fundamentals I
Unit 2. Introduction to programming
• Recommended reading
-Muñoz Caro C., Niño A. y Vizcaíno Barceló A. Introducción a la
programación con orientación a objetos. Capítulo 3. Prentice-Hall,
2002. Reimpresión 2007
Programming Fundamentals I
2.1. Introduction
• All programming languages use a series of basic constructors
(the elements that allow basic actions to take place in that
language).
• Lexical components:
• Punctuation marks and delimiters
• Identifiers
• Operator symbols
• Keywords
• Syntactic components:
• Comments
• Expressions
• Statements or instruccions
Programming Fundamentals I 3
2.2. General concepts
• In a programming language, an expression assesses data from a
program and returns a value. They are the basic syntactic components
of the instructions/statements.
Programming Fundamentals I 4
2.2. General concepts
• Syntactic definition of programming languages is a problem solve
from the 60s of the previous century: use of formal grammars
(context-free grammars)
Programming Fundamentals I 5
2.3. Data types
• Every program can be seen as a function applied to several
data.
• Data types:
• Primitive types: simple predefined data types provided by a
language
• Data types defined by the own programmer
Programming Fundamentals I 6
2.3.1 Primitive data types (I)
• Primitive data types
Integer
Numeric
Character
Non-
numeric
In some
Logic languages
Text/String
Programming Fundamentals I 7
2.3.1 Primitive data types (II)
• In Java:
– a) 4 integer types
– b) 2 real types
– c) 1 character type
– d) 1 logical type
• Character type
– ASCII (128, 256 characters)
– UNICODE (65536 characters)
– Name of type in Java: char
– The characters are in alphabetical order, and the code number
increases in the same alphabetical order
– A literal (fixed value) of a character type is denoted with simple
inverted commas, such as, ‘A’, ‘B’
– Different to String
Programming Fundamentals I 9
2.3.1 Primitive data types(IV)
• Logical type
– This primitive type is used to represent the two possible logical
values: true or false
– The name of the type in Java is boolean
– The only two possible values are true or false.
Programming Fundamentals I 10
2.3.2. Variables and constants (I)
• Variables
– A variable is the name that we assign to a position (positions) of
memory used to store a value of a certain type of data. The
variables must be declared (defined) before use.
– The declaration syntax of a variable in Java is:
data_type name_of_the_variable ;
– It is possible to declare various variables in the same statement,
int total, count, sum;
– The variables can be initialised (given an initial value) in the
declaration itself:
int total = 0, count= 20;
float price = 49.32;
Programming Fundamentals I 11
2.3.2. Variables and constants (II)
• Constants
– In programming, a constant is an entity that is similar to a
variable, but with the difference that once it has been assigned
the value that it contains cannot change in the programme.
– Syntax:
final data_type name_of_the_variable ;
– An example would be:
final double E = 2.718281828 ;
– Literals
– Identifiers in Java: they can be constructed with letters, digits,
the character used for underlining (_), and the dollar sign ($). An
identifier cannot begin with a digit, but it can be of any length.
Java distinguishes between upper and lower case letters,
signifying that if a variable called Data is declared, it will be
different from another called data.
Fundamentos de Programación I 12
2.3.2. Variables and constants
(III)
• The reach of variables
– Area of the programme in which it is defined
– Structure of a programme in blocks
– In Java the block is indicated with { }
– In Java the reach of a variable is the block in which it is defined
– If an attempt is made to use the variable outside the block in
which it has been declared, an undeclared variable error occurs.
Programming Fundamentals I
2.3.3. Internal data representation (I)
• Integer type
– The following bits are used
byte 7 bits
short 15 bits
int 31 bits
long 63 bits
Programming Fundamentals I
2.3.3. Internal data representation (II)
• Real type
– General representation
sign * mantissa * 10exponent
– In binary
sign * mantissa * 2exponent
• Logical type
– Only one bit is necessary
– In Java we use a minimum of 32 bits
Programming Fundamentals I
2.3.4. Conversion types (I)
• Conversion types
– Widening or narrowing
Programming Fundamentals I 18
2.3.4. Type conversions (III)
• Conversion mechanisms
a) Assignment conversion
b) Numeric promotion
c) Casting conversion (cast)
• Assignment conversion
– This takes place when a determined value is assigned to another
type of variable. For example, if money is a variable of the type
float and euros is a variable of the type int
money = euros;
Programming Fundamentals I
2.3.4. Type conversions (IV)
• Numeric promotion
– This occurs automatically when an arithmetic operation such as
an addition or a division is carried out.
Programming Fundamentals I
2.3.4. Type conversions (V)
• Casting conversion (cast)
– The transformation is carried out with a specific mechanism .
The cast is the instruction that produces the type conversion.
– It is possible to carry out widening and narrowing conversions.
– In Java, the cast is an operator that is specified as a type name
between brackets to the left of the datum to be converted.
Syntax:
(Type) variable_to_convert
– Example.:
int euros;
double money = 30.2;
euros = (int) money;
Programming Fundamentals I
2.3.5. Strings(I)
• Sets of alpha-numerical characters
• In Java they are String class objects from the java.lang package
Programming Fundamentals I
22
2.3.5. Strings(II)
• Assignment of Strings
chain2=chain1;
• Types of instructions
– Assignment
This unit
– Input/output
– Conditional branching In unit 3
Programming Fundamentals I
2.4.1. Assignment instrucciones
• The assignment instruction(s) serve(s) to give the variables a
value
Programming Fundamentals I
2.4.2. Input/output instructions (I)
• Input/output in Java. Streams
• A stream is an ordered sequence of data of an indeterminate
length. It is an abstraction of sources and external destinations of
data that allow them to be read independently of the exact type of
source or destination.
Data
Fuente de Data
Destino de
datos
source datos
destination
Corriente de Corriente de
entrada (Input salida (Output
stream) stream)
Java
Programa
Java
program
Programming Fundamentals I
2.4.2. Input/output instructions (II)
• There are no input/output statements in Java language. The input
and output are carried out using predefined class libraries. The
majority of input/output operations are defined in the java.io
package of the Java API.
• Standard input and output streams (java.lang package):
Stream Purpose Devide (default)
System.in Reading keyboard
System.out Writing Screen
System.err Errors output Screen
• Standard output:
System.out.print();
System.out.println();
Programming Fundamentals I
2.4.2. Input/output instructions (III)
• Escape sequences (use of \ )
Programming Fundamentals I
2.4.2. Input/output instructions (IV)
class Example {
// Example of the structure of a programa in Java
public static void main(String [] args) {
// Variables definition
double total=0, sum;
total=10.0; Comments:
sum=5.0; 1: //
2: /* */
// Operation
total=total+sum;
System.out.println (“total:”+ total);
Programming Fundamentals I
2.4.2. Input/output instructions (V)
class Writing {
public static void main(String[] args) {
int i,j;
i=1;
j=3;
System.out.print("Without end of line");
System.out.print("i :"+i);
System.out.print("j :"+j);
System.out.println();
System.out.println("With end of line");
System.out.println("i :"+i);
System.out.println("j :"+j);
Programming Fundamentals I
2.4.2. Input/output instructions (VI)
class Example{
public static void main(String [ ] args) {
System.out.println (“He said:\“ Get off \” “);
} // End of method main
} // En of class Example
Programming Fundamentals I
2.4.2. Input/output instructions (VII)
• From version 1.5 of Java with the Scanner class and the printf ( )
method
• Previously with the BufferedReader class
• Reading with the Scanner class (java.util package)
– useLocale (Locale local)
• Locale.US: EEUU
• Locale.ES: Spain
– next( ): Read as a String the first “token” found
– nextLine( ): Read all characters (spaces included) to end
of the line as a String
– nextInt( ): Read an int
– nextDouble( ): Read a double
– nextFloat( ): Read a float
TASK:
– Etc…Discover how BufferedReader is used
in Java
Programming Fundamentals I
2.4.2. Input/output instructions (VIII)
• Writing with printf ( ) method
– %[width][.precission] specifier
– Width: Minimum number of character to be printed. If the number of
characters is lower than this values, then blank spaces are used.
– Precission: Maximum number of characters to be written. For floating point
formats, 'e', 'E', y 'f precission means the number of digits after the decimal
comma (point)
– Specifier :
Programming Fundamentals I
2.4.2. Input/output instructions (IX)
import java.util.*;
class IO {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
sc.useLocale(Locale.US);
Programming Fundamentals I
2.4.2. Input/output instructions (X)
System.out.printf(Locale.US,
“\nThe inserted data String type are:"+
"\ncad1: %s"+
"\ncad1: %20s"+
"\ncad2: %s"+
"\ncad2: %10.5s\n",
cad1, cad1, cad2, cad2);
System.out.printf(Locale.US,
“\nThe inserted doubles are:"+
"\ndouble: %7.4f"+
"\ndouble: %7.3f"+
"\ndouble: %7.2f\n", d,d,d);
System.out.printf(Locale.US,
“\nThe inserted integers are:"+
"\ninteger: %d"+
"\ninteger: %5d", i,i);
Programming Fundamentals I
2.4.2. Input/output instructions (XI)
• Output from previous program
Insert a string: This is an example
Insert a string without backspaces: Example
Insert a double: 123.4567
Insert an integer: 123
Programming Fundamentals I
2.5. Operators (I)
• Programming statements often involve expressions
• Operators
– Unary (monadic)
– Binary
– …
Programming Fundamentals I
2.5. Operators (II)
• In programming languages, operators are generically
(semantically) the same and admit a classification according to
the type of operation that they carry out. Types:
– Arithmetic and assignment operators
– Increment and decrement operators
– Relational operators
– Logical operators
Programming Fundamentals I
2.5.1. Arithmetic and Assignment
Operators (I)
• Arithmetic operators are binary operators that apply the
arithmetic operations
• Operators
Operation carried out Operator
Addition +
Subtraction -
Multiplication *
Division /
Remainder %
Programming Fundamentals I
2.5.1. Arithmetic and Assignment
Operators (II)
• Remainder:
– 13%12=1; 12%13=12; -13%12=-1; 13%-12=1
• Precedence/priority of operators:
– Order
(* , / , %) > (+, -)
– Examples
• 5+4/3
• 5+12/5-10%3
Programming Fundamentals I
2.5.1. Arithmetic and Assignment
Operators (III)
• Various operators combine a basic operation with the
assignment. The idea is to simplify the habitual operation of
carrying out an operation on a variable and to store the result
in the same variable
• Operators:
Operator Example Equivalent
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
Programming Fundamentals I
2.5.2. Increment and decrement
operators (I)
• These operators are unary (monadic) which add (increase) or
subtract (decrease) a unit to a whole or real operand
• Operators
Operation carried out Operator
Increase by a unit ++
Decrease by a unit --
• Examples:
counter++;
value--;
• Equivalent to:
counter = counter+1;
value = value-1;
Programming Fundamentals I
2.5.2. Increament and decrement
operators (II)
• These operators can be used as prefixes or sufixes
Programming Fundamentals I
2.5.3. Relational operators
• These express the different relationships between two
entidades or operands
• Types:
Relation Syntax
Equal ==
Not equal !=
Greater than >
Less than <
Greater than or equal >=
Less than or equal <=
Programming Fundamentals I
2.5.4. Logical operators (I)
• Logical operators are used for propositional logic in order to
admit or refuse propositions ( logical statements, in our case
relations)
Programming Fundamentals I
2.5.4. Logical operators (II)
• Semantics (Truth table). The truth table of a statement is a
table which pesents all the possible interpretations of the
propositional variables of which the statement consists and
the truth value of the statement for each interpretation.
X Y X ˄ Y (X && Y)
T T T
T F F
F T F
F F F
Programming Fundamentals I
2.5.4. Logical operator (III)
– Logical “or” (disjunction)
X Y X ˅ Y (X || Y)
T T T
T F T
F T T
F F F
T F
F T
Programming Fundamentals I
2.5.4. Logical operators (IV)
– Logical exclusive “or” (Exclusive disjunction, XOR)
X Y X ˅ Y (X || Y)
T T F
T F T
F T T
F F F
Programming Fundamentals I