You are on page 1of 40

Unit 3.

Basic control and data structures


• Scope

3.1. Introduction
3.2. Basic control structures
3.2.1. Sequence
3.2.2. Selection
3.2.3. Iteration
3.3. Representation techniques
3.3.1. Control flow diagrams
3.3.2. Pseudocode
3.4 Data structures (Arrays)

Programming Fundamentals I 1
Tema 3. Basic control and data structures
• Recommended bibliography
• Structured programming
- Muñoz Caro C., Niño A. y Vizcaíno Barceló A. Introducción a la
programación con orientación a objetos. Chapter 4. Prentice-
Hall, 2002. Reimpresión 2007

- Muñoz Caro C., Niño A. y Vizcaíno Barceló A. Introducción a la


programación con orientación a objetos. Chapter 5. Prentice-
Hall, 2002. Reimpresión 2007 (Data structures)

- Introduction to Programming in Java (Princeton University).


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

Programming Fundamentals I 2
3.1. Introduction (I)
• Structured program theorem
– Bohm, C. and Jacopini, G, "Flow Diagrams, Turing Machines
and Languages with Only Two Formation Rules".
Communications of the ACM, 9 (5),366–371 (1966)

– Structured program theorem: Every program with a unique


input point and unique output point, whose statements are
all executed at least once and which has no infinite loops,
can be designed using three basic elements: sequence,
selection and loop.

• Basic elements of a program


– Sequence
– Selection
– Loop

Programming Fundamentals I 3
3.2. Basic control structures
• Next, each control structure shall be studied
– Sequence
– Selection
– Loop

Programming Fundamentals I 4
3.2.1. Sequence
• First basic control structure

int value=0;
value=value+1;
System.out.println(value);

Programming Fundamentals I 5
3.2.2 Selection (I)
• Second basic control structure
– Complete structure:

if (condition) {
---- block of instructions ----
}
else {
---- block of instructions ----
}

– It is possible this form as well:

if (condition) {
---- block of instructions ----
}

• Next an example
Programming Fundamentals I 6
3.2.2 Selection (I)
• Graphic representation of “IF” (flow diagram)

Programming Fundamentals I 7
import java.util.*;
class Condition {
// Example of conditional instruction if-else
public static void main(String[] args) {
int x;
Scanner leer =new Scanner(System.in);

// data reading
System.out.println(“Insert an integer");
x=leer.nextInt();
System.out.println(“Integer written"+x);

// Use of the condition


if (x < 0) {
System.out.println(“The number is negative");
}
else {
System.out.println(“The number is positive");
} // End of else
System.out.println(“End of program");
} // End of method main
} // End of class Condition

Programming Fundamentals I 8
3.2.2 Selection (II)
• In addition to the instruction if in Java a conditional operator
exists, which is a “ternary” operator, becuase uses three
operands. The syntax is:
condition ? expression1 : expression2;

• El operator executes an if-else equivalent to:


if (condition){
expression1;
}
else {
expression2;
}
• Example:
higher = (n1 <n2) ? n2 : n1;

Programming Fundamentals I 9
3.2.2. Selection (III)
• Multiple selection: switch
switch (expression) {
case literal 1:
-- block 1--
break;
case literal 2:
-- block 2 --
break;
...
default:
-- block n --
}

• The expression must be a value of type int, char o String y the


type of the literal value must match with the type of the result of
the expression
Programming Fundamentals I 10
3.2.2 Selection (IV)
• Graphical representation
• of switch (flow diagram)

Programming Fundamentals I 11
import java.util.*;
class Switch {
public static void main(String [] args){
int number ;
Scanner leer = new Scanner (System.in);

// Data reading
System.out.print(“Insert an integer: ");
number = leer.nextInt();

switch (number) {
case 1:
System.out.println(“The number is 1");
break;
case 2:
System.out.println(“The number is 2");
break;
default:
System.out.println(“The number is neither 1 nor 2");

} // End switch

} // End of method main


} // End of class

Programming Fundamentals I 12
3.2.2. Selection (VI)
• Combination of control structures
– Concatenation
– Nesting
• Concatenation

Struct. 1

Struct. 2

Struct. 3

Programming Fundamentals I 13
3.2.2. Selection (V)
• Nesting

Struct. 1

Struct. 2

Struct. 3

Struct. 4

Programming Fundamentals I 14
3.2.2. Selección (VI)
• Example with concatenated ifs
if (price > 10.0) {
price = price*0.9;// Disccount 10%
}
if (quantity > 5) {
quantity ++; // An article free
}

• Example with nested ifs


if (price > 10.0) {
price = price *0.9; // Disccount 10%
if (price > 20.0) {
quantity ++; // An article free
} // End internal if
} // End external if
Programming Fundamentals I 15
3.2.3. Loop (iteration) (I)
• Three (two) types of loops
– Type while
– Type do-while
– Type for (while controlled by a counter)

• Type while. Syntax:


while (condition) {
---- block of instructions ----
}

• Condition at the beginning


• It can be executed zero times

Programming Fundamentals I 16
3.2.3. Loop (iteration) (II)
• Graphical representation of “while” (flow diagram)

Programming Fundamentals I 17
3.2.3. Loop (iteration) (III)
• Example

class Counter {
public static void main (String [] args) {
final int END=3;
int i=0,sum=0;

// Example of loop while controlled by counter

while (i<=END) {
System.out.print("Counter= "+i);
sum=i+2;
System.out.println(“Addition= "+sum);
i=i+1; // Increment of the counter (i)
}
System.out.println("Value of the counter out of loop=“+i);
System.out.println(“Final value of addition= "+sum);
}
}

Programming Fundamentals I 18
3.2.3. Loop (iteration) (IV)
• Type do-while. Syntax:

do {
---- block of actions ----
} while (condition);

• Condition at the end


• It is always executed at least once

Programming Fundamentals I 19
3.2.3. Loop (iteration) (V)
• Graphical representation “do-while” (flow diagram)

Programming Fundamentals I 20
• Example

class Counter{
public static void main (String [] args){
final int END=3;
int i=0, sum=0;

// Example of loop do-while controled by a counter


do {
System.out.print("Counter = "+i);
sum=i+2;
System.out.println(" Addition= "+sum);
i=i+1; // Increment of counter (i)
} while (i<=END);
System.out.println("Value of the counter”
+” out of the loop= "+i);
System.out.println(“final value of ”
+” sum= “ + sum);
} //Fin método main
} // Fin clase Contador
Programming Fundamentals I 21
3.2.3. Loop (iteration) (VII)
• Type for (is a while controled by a counter). Syntax:

for (inicialization; condition; increment) {


----- block of actions -----
}
– The increment is carried out after executing the block of
actions.

• Equivalent to

inicialization;
while (condition) {
---- block of actions -----
increment;
}

Programming Fundamentals I 22
3.2.3. Loop (iteration) (VIII)
• Graphical representation
“for” flow diagram)

Programming Fundamentals I 23
• Example

class Contador {
public static void main (String [] args) {
final int END=3;
int i,sum=0;
// Example of loop for

for(i=0;i<=END;i++) {
System.out.print(“Counter = "+i);
sum=i+2;
System.out.println(“Sum= "+sum);
}

System.out.println(“Value of the counter”


+” out of the loop= "+i);
System.out.println(“Final value of sum= "+sum);

}
}
Programming Fundamentals I 24
3.2.3. Loop (iteration) (X)
• The counter can be defined into the loop for. In this case it
exists only into the loop for.
for(int i=0;i<=END;i++) {
System.out.println(“Value of the counter: "+i);
}

• Possibility of infinite loops (the condition is always true).


Example:
int counter= 1;
final int LIMIT=25;
while (counter <= LIMIT) {
System.out.println(counter);
counter = counter - 1;
}

Programming Fundamentals I 25
3.3. Representation techniques
• They allow working in a higher abstraction level with respect to
code.

• 2 possible techniques:

• Control flow diagrams


• Pseudocode

Programming Fundamentals I 26
3.3.1. Control flow diagram (I)
• Control Flow diagram. Symbols:

Start/End Control flow

Process Connector

Condition Connector in a different


page

Input/Output

Programming Fundamentals I 27
3.3.2. Control Flow diagram(II)

• Example. Program which


adds up the first 10 positive
integers

Programming Fundamentals I 28
3.3.3. Pseudocode (I)
• Pseudocode (lenguage for specifiying algorithms)
– Begin and end
BEGIN, END
– Assignment

– Selection
• If
IF(condition) THEN -- block of actions --
ELSE -- block of actions --
END_IF
• Switch
SWITCH (variable) :
VALUE 1: --- block of actions 1 ---
...
VALUE n: --- block of actions n ---
END_SWITCH
Programming Fundamentals I 29
3.3.3. Pseudocode(II)
• Loop
– while
WHILE (condition)
--block of actions--
END_WHILE
– do-while
DO
--block of actions--
WHILE(condition)
– for
FOR inicial value WHILE condition INCREA/DECREA
-- block of actions --
END_FOR

Programming Fundamentals I 30
3.3.3. Pseudocode (III)
• Example. Addition of the first integers from 1 up to 10:
BEGIN
sum←0
num←1
DO
sum←sum+num
num←num+1
WHILE (num ≤10)
Write sum
END

Programming Fundamentals I 31
3.4. Arrays (I)
• In programming it is usual to find many elements from the
same type to be manipulated.

• Programming languages usually provide a mechanism to


manipuate all of them as a set, with a unique identifier for the
set which allows manilaputing them as a whole

• An array represents a collection of elements of the same type


organized following any criterion

• An array represents an organization defined by one or several


indices. These indices allow pointing to a concrete element.

• Depending on the number of indices, the structure will be mono


or multidimensional.

Programming Fundamentals I 32
3.4. Arrays (II)
• Elements are differenciated by an index:
a0, a1, a2, .... ß monodimensional case

ai j , i=0, n ß bidimensional case


j=0, m

ai j k , i=0, n
j=0, m ß tridimensional case
k=0, l

• In Java numbering of indices of arrays starts at zero. For that


reason, If an array has n element then the indices range is [0, n-1].

• In Java arrays are objects. The stored elements can be from


different types: int, double, etc., even objects, however, all of them
must be of the same type.
Programming Fundamentals I 33
3.4. Arrays (III)
• Definition of a monodimensional array (vector), syntax:
type [ ] array_name = new type [array_length];
array_name represents the memory address (reference) of the object

• It is possible to define a empty reference to an array


type [] name = null;

• Example, definition of a vector with 20 integers:


int [ ] results = new int [20];
By default, java initialize the whole array with zeros
• It is also possible:
type[ ] array_name;
array_name =new tipo [array_length];
• To call a concrete value:
results [3] //Remind that the 1st element starts at 0

Programming Fundamentals I 34
3.4. Arrays (IV). Example
class Matrices_1 {
public static void main(String [ ] args) {
final int LIMITE=5; //vector’s dimension

int [ ] lista = new int [LIMITE];

for (int i=0; i<LIMITE; i++) { // Initialization


lista[i]=10*i;
}

for (int i=0; i<LIMITE; i++) { // Writing the vector


System.out.print (lista[i]+" ");
}

} // End method
} // End class

Programming Fundamentals I 35
3.4. Arrays (V)
• An index cannot point to an element whose index is out of the
bounds of the arrray. In Java the exception
ArrayOutOfBoundsException is thrown.

• Difference between:
– Static dimensioning (in compilation time)
– dynamic dimensioning (in runtime)

• Next an example of dynamic dimensioning is shown. The array


length is read as an argument passed using the keyboard.

Programming Fundamentals I 36
3.4. Arrays (VI). Example
import java.util.*;
class Matrices {
public static void main (String [ ] args) {
int limit;
Scanner scan =new Scanner (System.in);
limit= scan.nextInt(); // Read the length
int [ ] list = new int [limit];

// Initializating and writing within the array


for (int i=0; i<limit; i++) {
list[i]=10*i;
System.out.print(list[i]+" ");
}

} // End method
} // End class
Programming Fundamentals I 37
3.4. Arrays (VII)
• In Java the size of an array can be always read through the
constant variable length:
length = lista.length;

• On other hand, in Java a list of elements can be used to create


and initialize an array. The syntax is:
type [ ] array_name = {list of elements};

• The list is a set of comma-separated elements. For example:

int [ ] values = {22, 56, 1, 39, 88};

Programming Fundamentals I 38
3.4. Arrays (VIII)
• Multidimensionales arrays.
Example: a bidimensional array:
int [ ] [ ] twoD = new int [4][5];

• Multidimensionales arrays are arrays of arrays. An example


initializing with a list and use of the constant length to control
the access to all elements:
int [ ] [ ] tabla ={ {1}, {2,3}, {4,5,6}, {7,8,9,10} };

• Thus we have an array of arrays:


Row
0 1 This row is a1-element array
1 2 3 This row is a 2-element array
2 4 5 6 This row is a 3-element array
3 7 8 9 10 This row is a 4-element array
Programming Fundamentals I 39
3.4. Arrays (IX). Example
class Matrices {
public static void main(String [ ] args) {
int [ ][ ] tabla ={{1},{2,3},{4,5,6},{7,8,9,10}};
int suma;

for (int i=0;i<tabla.length;i++) { // For rows


for (int j=0;j< tabla[i].length;j++) { // For columns
System.out.print (tabla[ i ] [ j ] +" ") ;
}
System.out.println ( );
}
// Adding rows and printing the result
for (int i=0; i<tabla.length;i++) {
suma=0;
for (int j=0; j<tabla[i].length; j++) {
suma+=tabla[ i ] [ j ];
}
System.out.println(“Row: "+(i+1)+" addition: "+suma);
}
} // End method
} // End class
Programming Fundamentals I 40

You might also like