1UCD Computer Science COMP-2001
COMP-2001
• Data structures & algorithms I (then in January: COMP-2006: DS&A II)
• Eleni Mangina / [email protected]
• Course web: http://www.cs.ucd.ie/staff/emangina/COMP2001
Lectures 1 & 2
2UCD Computer Science COMP-2001
PracticalsSessions as assigned; attendance mandatory10 practicals (nearly 1 per week)
Each will probably require:2-4 hours prior to your session1.5 hours in lab2 hours after session
Several problems each, lifted directly from text-bookProgramming requires practice!30% of total course mark!Examination will require you understand the practicals!
1 week late? Maximum of 50% > 1 week late? No marks earned
3UCD Computer Science COMP-2001
Practicals
Don’t cheat
Cooperation and group studying are encouraged.But it’s easy to detect, andCheating will be dealt with according to theDepartment’s harsh plagiarism policy.
4UCD Computer Science COMP-2001
Course outline• Java refresher (1 week)• Object-oriented and modular design (1 week)• Mathematical tools for analyzing programs (1 week)• Remaining 9 weeks on a variety of useful topics
– Stacks– Queues– Lists– Vectors– Trees– Priority queues– Heaps
• Topics relevant to all programming languages 2001 is not just a course on “more Java”
A useful “bag of tools”that forms the foundationof all large software projects
5UCD Computer Science COMP-2001
Textbook• Goodrich & Tomassia -- Buy it!
Many useful resources at book’s web site.
• You Must read assigned sections before corresponding lecture!– Otherwise you’ll be lost
6UCD Computer Science COMP-2001
Java refresher• Forget Java over the summer? Try the COMP-2001
notes, or any of the excellent books or Web tutorials (see course Web for pointers)
• For Thursday: Read G&T Chapter 1• Start Practical #1 (due Friday 29/9 @ 5pm)
• Some of the following details may be bewildering or overly complicated at first -- come back to these notes or resources later when you understand what’s going on
7UCD Computer Science COMP-2001
Basic Concepts• Classes: a conceptual “box” that holds data (“instance
variables”) and methods that can be invoked in the data.• Objects: instances of a given class• Types: classes + primitive types (int, float, ...) +
built-in data structures (array)• Methods: a.k.a. “functions”, “subroutines”• Access modifiers: public, private, static, …• Expressions: create new values from combinations of
existing values• Control flow: if, for, return, ...• Packages: how classes are organized
8UCD Computer Science COMP-2001
Classesclass Fish {
int nfins; // instanceString name; // variables
Fish(int _nfins, String _name) { // constructornfins = _nfins; // methodname = _name;
}
void morefins(int delta) { // “regular” method
nfins += delta;}
}
9UCD Computer Science COMP-2001
A complete program• A Java program doesn’t “do anything” unless is
contains a special main method:
class Fish {int nfins;String name;Fish(int _nfins, String _name) {
nfins = _nfins;name = _name;
}void morefins(int delta) {
nfins += delta;}public static void main(String args[]) {
Fish f = new Fish(3, "Fred"); // object creationf.morefins(4); // method invocationSystem.out.println("Fred has " + f.nfins + "fins");
}}
10UCD Computer Science COMP-2001
Files, packages, classes• A single Java application typically comprises many
classes, grouped into several packages, much of which might be shared with other applications:
Payroll Program Human Resources Program
package A
package B
package C package DC1
C2
C4
C3
C6
C7
C5
C9
C10
C8
11UCD Computer Science COMP-2001
Files, packages, classes - continued• There must be a 1-to-1 correspondence between:
Classes - Java source files Packages - directories comtaining the class files
/app/acounting/packageA/C1.java /C2.java /packageB/C3.java /C4.java /sharedstuff/packageC/C5.java /C6.java /C7.java /human-res/packageD/C8.java /C9.java /C10.java
12UCD Computer Science COMP-2001
Creating objects and valuestype variablename = expression
int nfingers = 4;double weight; // very occasionally, initial value inappropriate/unnessaryboolean defective = weight<0; // initial value can be any expression
Integer ntoes = new Integer(4); // primitive data types aren’t objects
Boolean problem = new Boolean(defective || (nfingers<0);
String name = "Bob";
Fish f = new Fish(3, "Bob");
13UCD Computer Science COMP-2001
Simple Input/Output• Java has an incredibly complicated hierarchy of classes for
performing input/output. • Output
System.out.println(f.name + " has " + f.nfins + " fins");
• Inputimport java.io.*; // enable access to all Java I/O classes
…
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));
String line = stdin.readLine(); // read 1 line of text
Next step depends on what data type the user is expected to enter. For example…int xnfins = Integer.valueOf(line).intValue(); // expecting an integer
… or … float weight = Float.valueOf(line).floatValue(); // expecting a float
14UCD Computer Science COMP-2001
Exceptions• Any number of exceptional circumstances may
arise during program execution that cause troubleimport java.io.*;class IOExample { public static void main(String[] args) { try { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String line; System.out.print("Enter the number of fins > "); // wait til user enters something other than just RETURN while ((line=stdin.readLine()) == null) ; int nfins = Integer.valueOf(line).intValue(); } catch (IOException x) { // oops -- something strange went wrong System.out.println("Is your keyboard OK?! -- " + x); } catch (NumberFormatException x) { // entered something like “frog” System.out.println("Integers only! -- " + x); } }}
15UCD Computer Science COMP-2001
Control flowif (nfins > 10) { // execute block only if condition holds
System.out.println(“Are you sure??!??!”);}
int a = 10, b = 20;while (a>0) { // repeatedly execute body until a=0
b = b+a;if (b > 60) break; // immediately terminate while loopa = a-1;
}// now a=5 and b=65for (int i = 0; i < b; i++) { // set i=0, 1, 2, …, 64
a++; // shorthand for “a = a+1”}// now a=70 (and b is still 65)
16UCD Computer Science COMP-2001
Expressions• float appendageCost = (nfins + ntoes) * costPerAppendage;
• int remainder = numerator % divisor; // eg 5%2 = 1
• boolean probablySick = (whiteCellCount > 145);
• x = ++j; // increment j, and set x to the new value• y = j++; // increment j, and set y to the current value
• String fullname = firstname + " " + surname;
• double w = 45; // set w to the real number 45.0• int x = 45; // set x to the integer 45• double y = w/10; // set y = 4.5• double z = x/10; // set z = 4.0 not 4.5 !!??!!• double z = ((double)x)/10; // set z = 4.5
• int q = 3 + 4 * 5; // sets q to 23, not 60 !!?!?
17UCD Computer Science COMP-2001
Arrays• Java has one built-in “primitive” data structure
• When array is created, its capacity must be specified (with any integer expression!) and then can’t change
System.out.println("Enter the number of cities >");
int ncities = Integer.valueOf(stdin.readLine()).intValue();
int rainfall[ncities];
String name[ncities];
for (int i = 0; i < cities.length; i++) {
System.out.print("City " + i + " name > ");
name[i] = stdin.readLine();
System.out.print("City " + i + " rainfall > ");
rainfall[i] = Integer.valueOf(stdin.readLine()).intValue();
}
(danger -- no exception handling for simplicity)
18UCD Computer Science COMP-2001
Defining methodsclass Rectangle {
int height, width;
int area() {
return height*width;
}
void wider(int delta) {
width += delta;
}
void taller(int delta) {
height += delta;
}
RETURN-TYPE NAME( ARG1, ARG2, … ) {
BODY
}
}
19UCD Computer Science COMP-2001
The Dereference (“Dot”) Operator• If X is an an object of some class C that contains
an instance variable Y, then X.Y accesses that value of Y in object X
• Methods work exactly the same way
• stdin.readLine().toLowerCase().indexOf(“dog”)
the next string entered at the keyboard
the keyboard standard-input object
the position in that string of the first occurrence of “dog”
the string formed by replacing all UPPER case letters with lower
20UCD Computer Science COMP-2001
Sample practical problem• R1.13 - write a Java function that takes an integer n and
returns the sum of the odd integers smaller than n.
class R113 {static int oddsum(int x) {
…return …;
}}
Assumption: presumably the sum of all positive ints x !
We need to loop over all odd integers less than x
We need a variable to store the sum
21UCD Computer Science COMP-2001
R113 - continuedint sum = 0;
for (int i = 1; i<=x; i+=2) {… // i=1,3,5,…
}
Before proceeding… does this loop stop at the correct value of i??
22UCD Computer Science COMP-2001
R113 - continuedint sum = 0;
for (int i = 1; i<x; i+=2) {sum += i;
}// now sum = sum of all odd integers less than x
Does this handle negative values of x properly?Does this handle zero properly?Does this handle one properly?
Hint: what is the minimum number of timesany “for” loop will execute!
23UCD Computer Science COMP-2001
R113 - putting it all togetherclass R113 { static int oddsum(int x) { if (x<2) return 0; // special case! int sum = 0; for (int i=1; i<x; i+=2) { sum += i; } return sum; } public static void main(String[] args) { int i = 6; // “regular” input int osi = oddsum(i); System.out.println("got " + osi + " should be 9"); int j = -10; // problem with negative inputs? int osj = oddsum(j); System.out.println("got " + osj + " should be 0"); int k = 5; // problem with odd inputs? int osk = oddsum(k); System.out.println("got " + osk + " should be 4"); }}