Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

Unit 2.

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

- Introduction to Programming in Java (Princeton University).


Chapter 1. Elements of Programming:
http://www.cs.princeton.edu/introcs/10elements/

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.

• There are various types of statements :


a) Specification or declaration: These do not imply a mathematical or
logical operation (they are descriptive), but they are operative,
implying activity in the computer.
b) Executable: These imply a mathematical or logical operation (they
are the instructions).
c) Comment: Informative, ignored by the computer

• A program is usually defined by a sequence of instructions

[Note: In logical programming they are conditional formulas, in functional


programming they are expressions]

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)

• In addition to the syntactic definition, it is necessary to define every


component from the language: definition of the semantics.

• A satisfactory solution to the problem of programming languages’


semantics’ definition.

• There are different semantic approaches:


• Formal semantics: operational semantics, declarative semantics
(models theory, algebraic, denotational, etc.)
• Information semantics: natural language’s use
[Note: We’ll use an information approach to the semantic definition of
programming languages]

Programming Fundamentals I 5
2.3. Data types
• Every program can be seen as a function applied to several
data.

• A data type can be defined as a set of values together with a set


of operators in order to create and manipulate them.

• Languages can be strong or weak with respect to data types.

• 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

Primitive data Real


types

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

• Integer types (Java)


Name Memory used (bits) Minimum value Maximum value
byte 8 -128 127
short 16 -32768 32767
int 32 -2147483648 2147483647
long 64 <-9.22 1018 >9.22 1018
Programming Fundamentals I 8
2.3.1 Primitive data types (III)
• Real types (java)

Name Memory used (bits) Minimum value Maximum value


float 32 ≃1.4 10-45 ≃3.4 1038
double 64 ≃4.9 10-324 ≃1.7 10308

• 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

– IEEE 754 standard


Type sign mantissa exponent
simple (float, 32 bits) 1 bit 23 bits 8 bits
double (double, 64 bits) 1 bit 52 bits 11 bits

– Overflow and underflow


Programming Fundamentals I
2.3.3. Internal data representation
(III)
• Character type
– Use of UNICODE (16 bits)
– Representation like integer without sign
– Since they are stored like numbers, Java allows us to carry out
some arithmetic processes on the characters. For example, as
'A‘ is stored with a Unicode 65 value, the statement
char car = 'A' + 5;
will store the character 'F‘ in the car variable ( Unicode value of
‘F’, 70)

• 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

• Promotion conversions in Java


Origin Destination
byte short, int, long, float, double
short int, long, float, double
char int, long, float, double
int long, float, double
float double
double -------
long double
Programming Fundamentals I 17
2.3.4. Type conversions (II)
• Contraction conversions in Java
Origin Destination
byte char
short byte, char
char byte, short
int byte, short, char
long byte, short, char, int
float byte, short, char, int, long
double byte, short, char, int, long, float

• Booleans cannot be converted to any other type, and vice versa

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;

– This is only permitted in widening conversions.

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.

– Example, if result is a variable of the float type, then sum


is also a variable of the float type, and counter is a
variable of the int type
result = sum / counter;

– The arithmetic promotion is always a widening conversion

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

• Creation of a String, two means:


String cad = new String(“This is an example”);

String cade = ”Esto es un ejemplo”;

• In Java the characters in a String are numbered:


This is an example ß String
012345678901234567 ß Order

• Common operations as follows

Programming Fundamentals I
22
2.3.5. Strings(II)
• Assignment of Strings
chain2=chain1;

• Concatenation (“addition”) of chains


chain3=chain1+chain2;

• Search (to determine whether a character or sub-string are in


the string)

• Extraction of a sub-string from the original string

• Comparison of string (are they the same or not?)

TASK: Discover how these operations are


carried out in Java and in C++
Programming Fundamentals I
2.3.5. Strings(III)
• Class useful for handling text strings
• Methods
• length()
• indexOf (‘character’)
• lastIndexOf(‘character’)
• charAt(n)
• substring(n1, n2)
• toUpperCase()
• toLowerCase()
• equals( String )
• equalsIgnoreCase( String )
• valueOf(n)
• Example:
String cadena1 = “Example”;
int tamanio = cadena1.length();
2.4. Instructions
• A programme is written in a concrete language which indicates
the various actions by using particular instructions. These
instructions are general, although the specific syntax depends
on the language.

• 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

• In Java we use “=” . So we assign the value of 5.0 to a real


variable called total as follows:
total=5.0;
• The sign “=” DOES NOT represent an equality, but rather the
provision of a determined value in the variable.

• The sign ” =” may cause confusion if it is considered as an


equality. For example, the statement :
total=total+1.0;
does not make sense if it is considered as an equality.

• General syntax: name_variable = expression;

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

Escape Secuence Meaning


\t Horizontal tab
\n New line
\’ Single quote
\’’ Double quote
\\ Backslash
\\b Backspace

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

} // End method main


} // End class Example

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

}//End of method main


}//End of class

The output is:

Without end of line i: 1 j: 3


With end of line
i: 1
j: 3

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

The result is:

He said: “Get off”

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 :

Specif. Meaning Example


d Integer with sign 123
e Scientific notation (mantissa/exponent) using the character e 1.234567e+2
E Scientific notation (mantissa/exponent) using the character E 1.234567E+2
f Real numbers using floating point (comma) 123.4567
S String Example
– The symbol % is placed on the position where we want to print the
argument with the indicated format and at the end of the printf the
arguments to be printed are placed.

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

System.out.print("Insert a string: ");


String cad1 = sc.nextLine();

System.out.print("Insert a string without backspaces: ");


String cad2 = sc.next();

System.out.print("Insert a double: ");


double d = sc.nextDouble();

System.out.print("Insert an integer: ");


int i = sc.nextInt();

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

}//End of method main


}//End of class

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

The inserted data String type are:


cad1: This is an example "\ncad1: %s"+
cad1: This is an example "\ncad1: %20s"+
cad2: Example "\ncad2: %s"+
cad2: Examp "\ncad2: %10.5s\n"
The inserted doubles are:
double: 123.4567 "\ndouble: %7.4f"+
double: 123.457 "\ndouble: %7.3f"+
double: 123.46 "\ndouble: %7.2f\n"

The inserted integers are: "\ninteger: %d"+


integer: 123
integer: 123
"\ninteger: %5d"

Programming Fundamentals I
2.5. Operators (I)
• Programming statements often involve expressions

• An expression is a combination of the operators and operands


used to carry out a calculation

• An operator is an entity that represents an operation

• An operand is an entity that undergoes the effect of an


operator.

• 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 %

• Integer division: 13/5=2

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

– Use of brackets to alter precedence/priority


• ((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

• When they act on a single variable, as in the previous example,


the result is the same. Thus:
++counter equivalent to counter++
--value equivalent to value--

• When these operators are used in an expression, the increase


or decrease is made after (sufix) or before (prefix) using the
value of the variable in the expression. Example:
counter = 5;
a) value=counter++; b) value=++counter;
System.out.println(“value: “+value);
System.out.println(“counter: “+counter);

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)

• They imply acting on relations. Types:


Meaning Operator
Logical AND &&
Logical OR ||
Logical NOT !
Logical exclusivo OR (XOR) ^

• Precedence/priority ! > ^ > && > | |

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.

– Logical “and” (conjunction)

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

– Logical “not” (negation)


X ¬X (!X)

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

You might also like