Introduction to Computer Programming Basics
Introduction to Computer Programming Basics
LECTURE_1
Compiled_by_Tronic_636
What is a computer program?
• What is a computer program?
• Sequence of instructions, in some computer programming language
• Instructs a computer to perform some task
• Transform some input data to output data
prog Output
Input
Compiled_by_Tronic_636
What is a computer program?
• Program doesn’t have to physically exist!
Compiled_by_Tronic_636
Programming language levels
computer comprehension
human comprehension
Compiled_by_Tronic_636
Programming language levels
• Compiler
• A special program that transform a program written in a high-level language
to a lower-level language (usually machine languge)
• In this course, we will use Java as our high-level programming
language
Compiled_by_Tronic_636
What is programming?
• Writing programs?
• Not the full story!
• Programming is solving problems using computer programs
• Involves the following steps
1. Problem analysis
2. Solution design
3. Coding the solution in some programming language
• Caveat!
• Skipping 1. and 2. and rushing to 3. usually ends in tears!
Compiled_by_Tronic_636
Programming is a skill!
• Mastery of programming requires tons of practice!
• Reading alone is seldom useful!
• So practice until you become a guru!
Compiled_by_Tronic_636
Procedural thinking
• Solutions to problems need to presented in steps
• sequential
• order matters
• logical
• Example: Making a cup of tea
1. boil water 1. pour the hot mixture into a cup
2. add tea leaves to boiling water 2. add tea leaves to the boiling water
3. pour the hot mixture into a cup 3. boil water
4. add sugar to the cup 4. add sugar to the cup
Compiled_by_Tronic_636
Why procedural thinking?
• Computer hardware is a machine
• Not intelligent!
• Does not understand anything!
• Does exactly as told
• If it does a silly thing, it means it was told to do so – may need to reevaluate who is silly!
• Complex tasks need to be broken down into sub-tasks
• Small enough to be handled by some language construct
• Procedural thinking leads to structured programming
Compiled_by_Tronic_636
Elements of structured programming
• Three core elements
1. Sequence
2. Selection
3. Repetition
• Modularity
• A necessary extension to manage complexity
Compiled_by_Tronic_636
Sequence
• Execute list of instructions in order
• Example: Making a cup of tea
1. boil water
2. add tea leaves to boiling water
3. pour the hot mixture into a cup
4. add sugar to the cup
Compiled_by_Tronic_636
Selection
• Choose one action from multiple alternatives
• Example: Check if a real number has a real square root
1. get the real number, x
2. if x >= 0 then
3. print “x has a real root”
4. else
5. print “x has no real root”
Compiled_by_Tronic_636
Repetition
• Repeat a list of instructions while some condition remains true
• Example: rinsing a stack of plates
1. get the stack of plates
2. fill basin with clean water
3. while plates remain in the stack
4. get a plate from the stack
5. dip in clean water
6. put the plate on a rack
7. end while
Compiled_by_Tronic_636
Modularity
• Assigning names to blocks instructions
• Each block may use all three elements
• sequence, selection, repletion
• The named block is treated as a single instruction
Compiled_by_Tronic_636
Modularity
• Example: ATM Withdraw
1. authenticate customer authenticate customer
2. validate amount 1. get card
2. read Card
3. Dispense cash 3. get customer PIN
4. if card PIN != customer PIN read card
5. return card 1. if has chip then
6. abort withdraw 2. read chip
7. end if 3. get card PIN
4. else
5. read magnetic strip
6. get card PIN
7. end if
Compiled_by_Tronic_636
Steps in program development
Define the problem
Document the
program
Outline the solution
Compiled_by_Tronic_636
House Keeping
• Prescribed text
• Sedgewick, R., and Wayne, K. (2017). Introduction to Programming in Java: A
Multidisciplinary Approach (2nd ed.). Addison-Wesley Professional
• Assessment
• 50% continuous assessment
• 2 paper based tests
• 1 practical test
• Tons of exercises (some of which may be handed in, on request)
• 50% EOS
• Name: Mwawi Msiska
Compiled_by_Tronic_636
Basics
LECTURE_2
Compiled_by_Tronic_636
First program Name of program
main() method
Compiled_by_Tronic_636
First program: compiling and executing
Compiled_by_Tronic_636
First Program: What could go wrong?
public class Hello{
public static main(String [] args){
[Link]("Hello, world");
}
forgot the
}
word ‘void’
Compiled_by_Tronic_636
First program: what could go wrong?
public class Hello{
public static void main(String [] args){
[Link]("Hello, world")
}
}
forgot ;
Compiled_by_Tronic_636
First program: what could go wrong?
public class Hell0{
static void main(String [] args){
[Link]("Hello, world")
}
missing the word ‘public’
}
Compiled_by_Tronic_636
First program: what could go wrong?
public class Hell0{
public static void main(String [] args){
[Link]("Hello, world")
}
wrong file name
}
Compiled_by_Tronic_636
Simple program outline
Name of program main() method
...
}
}
body of main()
Compiled_by_Tronic_636
Program formatting Avoid
Compiled_by_Tronic_636
Program formatting Even better!
/************************
Program: Hello
Author: MF Msiska
Compiled_by_Tronic_636
Coding Cycle
1. Edit program Edit
Compiled_by_Tronic_636
Coding Cycle Tools: virtual terminal
• Text editor + virtual terminal
• Pros
• works with any language
• useful beyond programming
• used by professionals
• tradition in computing
• Cons
• working at low level
• dealing with multiple independent applications
• cumbersome in the context of large projects
Compiled_by_Tronic_636
Coding Cycle Tools: Integrated Development
Environment
• Text editor + virtual terminal
• Pros
• easier handling of large projects
• system independent (to some extent)
• used by professionals
• can be helpful to beginners
• Cons
• overkill for small programs
• steep learning curve (the system itself)
• language/system specific
Compiled_by_Tronic_636
Built-in data types
• Data type: set of values + operations
• Integral types
• byte – 8-bit integers. Range: −27 to 27 − 1 (-128 to 127)
• short – 16-bit integers. Range: −215 to 215 − 1
• int – 32-bit integers. Range: −231 to 231 − 1
• long – 64-bit integers. Range: −263 to 263 − 1
• char – characters, e.g. 'a'
• Floating point numbers
• float – 32-bit floating point number
• double – 64-bit floating point number
• Operations: add, subtract, multiply, divide, etc.
Compiled_by_Tronic_636
Built-in data types
• boolean – truth values
• Values: true, false
• Operations: and, or , not
• String – sequence of characters
• Operations: concatenate, length, etc.
Compiled_by_Tronic_636
Built-in data types
Integral types
Compiled_by_Tronic_636
Basic definitions
variables
data types
literals
Declarations int a;
int b;
Assignments a = 2004;
b = 2023;
int c = b - a;
Compiled_by_Tronic_636
Example: Swapping values
int a = 2004; a b temp
int b = 2023; ? ? ?
int temp = a; int a = 2004; 2004 ? ?
a = b; int b = 2023; 2004 2023 ?
b = temp; int temp = a; 2004 2023 2004
a = b; 2023 2023 2004
b = temp; 2023 2004 2004
Trace
Compiled_by_Tronic_636
Strings
• A string is a sequence of characters
• The Java data type for strings is String
• literals delimited by double quotes
• "my name is " – 11 characters
• "+ " – 2 characters
• " " – 1 character
• "" – 0 characters
Compiled_by_Tronic_636
String Operations
Operation Operator
Concatenate +
• Examples
Expression Value
"hello, " + "world" "hello, world"
"a + " + " b = " + "12" "a + b = 12"
"12" + "34" "1234"
Compiled_by_Tronic_636
Characters and context
white
operator spaces
character space
characters
Compiled_by_Tronic_636
Input and output
• [Link]()
• built-in method to print a string
• converts numbers to strings
• Command-line inputs
• strings you type after program name when running the program
• available as args[0], args[1], etc
• [Link]()
• converts a string into an integer
Compiled_by_Tronic_636
Example
int a = [Link](args[0]);
int b = [Link](args[1]);
int temp = a;
a = b;
b = temp;
[Link](a + ", " + b);
}
} Compiled_by_Tronic_636
Data type int
Compiled_by_Tronic_636
Operator precedence: int
1. Parentheses
2. Multiplicative operators
3. Additive operator
• Operators at the same level are left associative
• 5 + 4 * 7 = 33
• 5–3+2=4
• 5*3%2=1
Compiled_by_Tronic_636
Example
public class IntOps{
public static void main(String[] args){
int a = [Link](args[0]);
int b = [Link](args[1]);
int sum = a + b;
int prod = a * b;
int quot = a / b;
int rem = a % b;
[Link](a + " + " + b + " = " + sum);
[Link](a + " * " + b + " = " + prod);
[Link](a + " / " + b + " = " + quot);
[Link](a + " % " + b + " = " + rem);
}
} Compiled_by_Tronic_636
Data type double
Compiled_by_Tronic_636
Data type double Not a Number
• Special values
• 1.0 / 0.0 = Infinity
• [Link](-1.0) = NaN
• double does not truly represent real numbers
1
• For example: no values for 2, π, , 𝑒 etc
3
Compiled_by_Tronic_636
Data type double
Expression Value
3.1453 + 0.14 3.2853000000000003
3.1453 - 0.14 3.0053
3.14e60 / 2.0 1.57E60
3.14 % 3.0 0.14000000000000012
3.14 * 10.0 31.400000000000002
Compiled_by_Tronic_636
Math Library
Method Return value
double abs(double a) absolute value of a Also define for
double max(double a, double b) maximum of a and b int, long and
double min(double a, double b) minimum of a and b float
Compiled_by_Tronic_636
Math Library
Compiled_by_Tronic_636
Math Library
Constant value
double E 𝒆
double PI 𝝅
Compiled_by_Tronic_636
Example: Using Math Library
• Write a program to compute the roots of a quadratic equation
• 𝑎𝑥 2 + 𝑏𝑥 + 𝑐
−𝑏± 𝑏 2 −4𝑎𝑐
• Roots are given by
2𝑎
• Algorithm
1. Get three command-line inputs
2. Convert the inputs into double values, a, b, c
3. Calculate discrimininant
4. Calculate the first root
5. Calculate the second root
Compiled_by_Tronic_636
public class Quadratic{
public static void main(String[] args){
// Parse coefficients from command-line.
double a = [Link](args[0]);
double b = [Link](args[1]);
double c = [Link](args[2]);
Compiled_by_Tronic_636
Compiled_by_Tronic_636
public class Quadratic{
public static void main(String[] args){
// Parse coefficients from command-line.
double a = [Link](args[0]);
double b = [Link](args[1]);
Compiled_by_Tronic_636
boolean data type
Compiled_by_Tronic_636
boolean data type
a b !a a && b a || b
true true false true true
true false false false true
false true true false true
false false true false false
Compiled_by_Tronic_636
Comparison operators
• Defined for all primitive types
• Operands must be of the same type
• Result: Boolean value
Compiled_by_Tronic_636
Comparison operators
Compiled_by_Tronic_636
public class LeapYear{
public static void main(String[] args){
int year = [Link](args[0]);
boolean isLeapYear;
// or divisible by 400
isLeapYear = isLeapYear || (year % 400 == 0);
[Link](isLeapYear);
}
}
Compiled_by_Tronic_636
Compiled_by_Tronic_636
Type checking
• Operations must match data type
• Compiler enforces this rule!
public class TypeError{
public static void main(String[] args){
String name = "George" * 2;
}
}
Compiled_by_Tronic_636
Type checking
public class TypeError{
public static void main(String[] args){
String name = "George" * 2;
}
}
Compiled_by_Tronic_636
Type conversions
• Allows use of multiple types in an expression
• Three types of conversions
• Automatic
• Explicit
• Cast
Compiled_by_Tronic_636
Automatic Conversion
• Automatic promotion of a lower-precision/lower-range type to a
higher one
3.142 * 10 31.42
double
double int double
Compiled_by_Tronic_636
Explicit Conversion
• A method that takes input one type, and returns another type
• Examples
[Link]("46") 46
• [Link](String)
• Converts a String into an integer String int
• [Link](String)
• Converts a String into a double
• [Link](double) [Link](3.456) 3
• Converts a double into a long
double long
Compiled_by_Tronic_636
Cast
• For primitive types
• Useful when conversion would potentially result in loss of data due to
range or precision
• Otherwise results in a compile error as shown in the next slide.
Compiled_by_Tronic_636
Lossy Conversions
public class LossyConversion{
public static int main(String[] args){
double pi = 3.14159;
int diameter = 10;
int circ = pi * diameter;
}
}
Attempt to convert a
double value into an int –
loss of precision!
Compiled_by_Tronic_636
Casting
• In the previous slide, we can tell the compiler that the potential loss
in range/precision is intentional by casting the expression
• Syntax: (data_type) exprssion
Compiled_by_Tronic_636
Casting
public class LossyConversion{
public static void main(String[] args){
double pi = 3.14159;
int diameter = 10;
int circ = (int) (pi * diameter);
[Link](circ);
}
}
Compiled_by_Tronic_636
Casting
• The cast operation has the highest precedence!
Compiled_by_Tronic_636
Type conversions: caveat
public class Overflow{
• Not always possible public static void main(String[] args){
short n = (short) 50000;
short [Link]("n = " + n);
}
} >javac [Link]
Compiled_by_Tronic_636
Control Flow
LECTURE_3
Compiled_by_Tronic_636
Program with linear control flow
• Statements executed in sequence
Statement 1
• Linear flow
Statement 2
• No jumping
Statement 3 • No looping
Statement 4
Statement n
Compiled_by_Tronic_636
Program with non-linear control flow
Statement 1 • Possible control flows:
false
boolean 1
• 1,2,4,5,6,4,5,6,7
Statement 2
true
Statement 3
Statement 4 true
false
Statement 5 boolean 2
Statement 6
Statement 7
Compiled_by_Tronic_636
Program with non-linear control flow
Statement 1 • Possible control flows:
false
boolean 1
• 1,2,4,5,6,4,5,6,7
Statement 2
• 1,3,4,5,6,7
true
Statement 3
Statement 4 true
false
Statement 5 boolean 2
Statement 6
Statement 7
Compiled_by_Tronic_636
Program with non-linear control flow
Statement 1 • Possible control flows:
false
boolean 1
• 1,2,4,5,6,4,5,6,7
Statement 2
• 1,3,4,5,6,7
Statement 3
true • etc
Statement 4 true
false
Statement 5 boolean 2
Statement 6
Statement 7
Compiled_by_Tronic_636
if statement true false
bool_expr
• Syntax:
statement
if (bool_expr)
statement;
if (bool_expr)
statement1;
true false
else bool_expr
statement2;
statement1 statement2
Compiled_by_Tronic_636
Example: computing the absolute value
• Solution
• If the value is negative, multiply by -1 true
val < 0
false
• if value is non-negative, leave it
val = -val;
if (val < 0)
val = -val;
[Link](val);
Compiled_by_Tronic_636
Example: maximum of two integers
• Solution: true
a>b
false
• Say the integers are a and b
• if a > b, max is a max = a; max = b;
• Otherwise max is b
if (a > b)
max = a;
else
max = b;
Compiled_by_Tronic_636
Example: Simulating tossing a coin
• Solution: >java CoinToss
• Generate a random number, r, between 0 and 1 Tails
• If r >= 0.5 heads
• Otherwise tails >java CoinToss
Heads
public class CoinToss{
public static void main(String[] args){ >java CoinToss
double r = [Link](); Tails
if ( r >= 0.5)
[Link]("Heads"); >java CoinToss
else Tails
[Link]("Tails");
} >
} Compiled_by_Tronic_636
Blocks
• A sequence of statement enclosed in { }
• A block is treated as a single statement
• So, the statement in if-else can be a block!
Compiled_by_Tronic_636
Example: Sorting two integers
• Solution:
• Given two integers, a and b, in that order
• If a > b, swap their values
Compiled_by_Tronic_636
Example: Sorting two integers
public class TwoSort{
public static void main(String[] args){
int a = [Link](args[0]);
int b = [Link](args[1]);
>
Compiled_by_Tronic_636
Use if-else statement to check errors
public class DivErrorChk{
public static void main(String[] args){
double total = [Link](args[0]);
int count = [Link](args[1]);
if (count != 0)
[Link]("Average = " + total/count);
else
[Link]("Error. Division by 0");
}
}
Compiled_by_Tronic_636
Use if-else statement to check errors
public class DivErrorChk{
public static void main(String[] args){
double total = [Link](args[0]);
int count = [Link](args[1]);
>java DivErrorChk 32.3 0
if (count != 0)
Error. Division by 0
[Link]("Average = " + total);
else
>java DivErrorChk 32.3 10
[Link]("Error. Division by 0");
Average = 3.2299999999999995
}
}
>
Compiled_by_Tronic_636
The while loop
• Syntax: true
bool_expr
false
while (bool_exp) Normally a
statement; block
statement
1. Evaluate bool_exp
2. If true execute statement and go
back to 1.
3. If false, exit the loop and proceed with
the next statement
Compiled_by_Tronic_636
Example: Counting
• Problem: Write a program that count from 1 to n.
• Solution:
1. Initialize integer count to 0
2. While count < n
count = count + 1
print count
Compiled_by_Tronic_636
Example: Counting
public class Counting{
public static void main(String[] args){ true false
count < n
int n = [Link](args[0]);
count = count +1;
int count = 0;
[Link](count);
while (count < n){
count = count + 1;
[Link](count);
}
}
}
Compiled_by_Tronic_636
Example: Counting
public class Counting{
public static void main(String[] args){
int n = [Link](args[0]);
>javac [Link]
int count = 0;
>java Counting 5
while (count < n){ 1
count = count + 1; 2
[Link](count); 3
} 4
} 5
}
Compiled_by_Tronic_636 >
Example: Counting
public class Counting{
public static void main(String[] args){
int n = [Link](args[0]);
int count = 0;
Shorthand for count = count +1
– compound addition assignment
while (count < n){
count += 1;
[Link](count);
}
} In General x = x + expression
} can be written as x += expression
Compiled_by_Tronic_636
Example: Counting
public class Counting{
public static void main(String[] args){
int n = [Link](args[0]);
int count = 0;
Shorthand for count = count +1
– increment operator
while (count < n){
count++;
[Link](count);
}
}
}
Compiled_by_Tronic_636
Other compound assignments
Operation Name Meaning
x += expression Compound addition assignment x = x + expression
x -= expression Compound subtraction assignment x = x - expression
x *= expression Compound multiplication assignment x = x * expression
x /= expression Compound division assignment x = x / expression
Compiled_by_Tronic_636
Increment/Decrement Operators
Operation Name Meaning
x++ Increment x=x+1
X-- Decrement x=x-1
Compiled_by_Tronic_636
Increment/Decrement Operators
public class Increment{
public static void main(String[] args){
int val = 10;
[Link](val++); // postfix
[Link](val);
[Link](++val); // prefix
}
}
Compiled_by_Tronic_636
Increment/Decrement Operators
public class Increment{ >javac [Link]
public static void main(String[] args){
int val = 10; >java Increment
[Link](val++); // postfix
10
[Link](val); 11
[Link](++val); // prefix
12
}
} >
Compiled_by_Tronic_636
Example: computing the first n powers of 2
public class PowersOfTwo{
public static void main(String[] args){
int n = [Link](args[0]);
int i = 0;
int val = 1; // 2 to the power 0
Compiled_by_Tronic_636
The for loop
initialization;
• Syntax:
for (initialization; condition; advancement)
statement; true false
condition
statement;
advancement
Compiled_by_Tronic_636
Every for loop has an equivalent while loop
Initialization
Compiled_by_Tronic_636
Example: Computing the sum of the first n
natural numbers
public class ArithmeticSum{ i sum
public static void main(String[] args){ 1 1
int n = [Link](args[0]);
2 3
int sum = 0;
3 6
for (int i = 1; i <= n; i++) 4 10
sum+=i;
[Link](sum);
}
}
Compiled_by_Tronic_636
Example: computing factorial
public class Factorial{
public static void main(String[] args){ i product
int n = [Link](args[0]); 1 1
long product = 1; 2 2
3 6
for (int i = 1; i <= n; i++)
product*=i; 4 24
[Link](product);
}
}
Compiled_by_Tronic_636
Nesting
• Any statement within a conditional or a loop may be another
conditional or loop
Compiled_by_Tronic_636
Example: nesting
While loop nested inside for
for (int t = 0; t < trials; t++){ loop
int cash = stake;
if (cash == goal)
wins++; if nested inside for
}
Compiled_by_Tronic_636
Example: computing grade letters
• 0 – 49: F
• 50 – 59: C
• 60 – 79: B
• 80 – 100: A
Compiled_by_Tronic_636
public class GradeLetter{
public static void main(String[] args){
int grade = [Link](args[0]);
char letter = 'D';
>java GradeLetter 12
Grade: 12 -> F
>java GradeLetter 51
Grade: 51 -> C
>java GradeLetter 75
Grade: 75 -> B
>
Compiled_by_Tronic_636
public class GradeLetterB{
public static void main(String[] args){
int grade = [Link](args[0]);
char letter = 'D';
>java GradeLetterC 90
Grade: 90 -> A
>java GradeLetterC 70
Grade: 70 -> B
>java GradeLetterC 60
Grade: 60 -> B
>java GradeLetterC 55
Grade: 55 -> C
>java GradeLetterC 27
Grade: 27 -> F
> Compiled_by_Tronic_636
Example: gamblers ruin problem
• Game with 50% chance of winning – eg tossing a coin
• Bet K1000 per toss
• Heads wins you K1000
• Tails loses you K1000
• Starting with Kx,000, can you reach a target of Ky,000
• Two possible solutions
• Find closed-form solution
• Simulation Let’s try this
Compiled_by_Tronic_636
public class Gambler{
public static void main(String[] args){
int stake = [Link](args[0]);
int goal = [Link](args[1]);
int trials = [Link](args[2]);
int wins = 0;
for (int t = 0; t < trials; t++){
int cash = stake;
while (cash > 0 && cash < goal){
if ([Link]() < 0.5)
cash +=1000;
else
cash -= 1000;
}
if (cash == goal) wins++;
}
[Link](wins + " wins of " + trials);
}
}
Compiled_by_Tronic_636
Debugging
LECTURE_4
Compiled_by_Tronic_636
What is bug? Syntax error
Compiled_by_Tronic_636
Example: The factoring problem
• Problem: Calculate all factors of a given integer
• Solution:
• Let the integer be 𝑛
1. consider each integer 𝑖 < 𝑛
2. while 𝑖 dives 𝑛 evenly
a) print 𝑖 (𝑖 is a factor of 𝑛)
b) replace 𝑛 with 𝑛/𝑖
Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0])
Compiled_by_Tronic_636
Example: The factoring problem
Program does not
public class Factors{ compile!
public static void main(String[] args){
long n = [Link](args[0])
Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);
Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);
Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);
Compiled_by_Tronic_636
Example: The factoring problem Runtime error – logical error
– non-terminating loop!
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);
Compiled_by_Tronic_636
Example: The factoring problem Runtime logical
error!
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);
Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);
Runtime logical
for (int i = 2; i < n; i++){ error!
while (n % i == 0){
[Link](i + " ");
n = n / i;
} Because of <, i can
} never reach n, so n
} is never tried!
}
Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);
Compiled_by_Tronic_636
Example: The factoring problem
>javac [Link]
Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);
Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{ >java Factors 98
2 7main(String[]
public static void 7 args){
>java Factors 5
long n = [Link](args[0]);
5
for (long i>java
= 2; Factors
i <= n; 6i++){
while 2(n3 % i == 0){
>java Factors 1111111111111111
[Link](i + " ");
11
n =17n 73
/ i;101 137 5882353
} >java Factors 11111111111111111
} 2071723 5363222357
} >
} Took too long to compute!
Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);
Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);
Compiled_by_Tronic_636
Example: The factoring problem
• A very important problem
• RSA encryption algorithm’s strength depends on the fact that if 𝑛 =
𝑝𝑞, where 𝑝 and 𝑞 are prime numbers, it is difficult to factorize 𝑛 if 𝑝
and 𝑞 are very large integers (eg, 200 digits long)
• Internet security is based on the RSA algorithm
Compiled_by_Tronic_636
Summary
Edit program
Syntax error
Compile
Compiled_by_Tronic_636
Arrays
LECTURE_5
Compiled_by_Tronic_636
Arrays
• The first data structure for this course
• A data structure is an arrangement of data that enables efficient
processing by a program
• Defn. An array is an indexed sequence of values of the same type
• Indices are no-negative integers starting at 0
• Purpose: storage and manipulation of data
Compiled_by_Tronic_636
Why arrays?
double a0 = 0.0; double[] a;
double a1 = 0.0; a = new double[10]; With arrays
double a2 = 0.0; ...
One variable declaration
double a3 = 0.0; a[4] = 3.0;
One initialization
double a4 = 0.0; ...
double a5 = 0.0; a[8] = 8.0;
double a6 = 0.0; double = x = a[4] + a[8];
double a7 = 0.0;
double a8 = 0.0;
double a9 = 0.0;
...
a4 = 3.0; Without arrays
... Tedious – 10 definitions and assignments!
a8 = 8.0; 10 variable names!
double = x = a4 +
a8; Compiled_by_Tronic_636
Why arrays?
double a0 = 0.0; double[] a;
double a1 = 0.0; a = new double[10];
double a2 = 0.0; ...
double a3 = 0.0; a[4] = 3.0;
double a4 = 0.0; ...
double a5 = 0.0; a[8] = 8.0;
double a6 = 0.0; double = x = a[4] + a[8];
double a7 = 0.0;
double a8 = 0.0;
double a9 = 0.0;
...
a4 = 3.0;
...
a8 = 8.0;
double = x = a4 +
a8; Compiled_by_Tronic_636
Why arrays?
double a0 = 0.0; double[] a;
double a1 = 0.0; a = new double[10];
double a2 = 0.0; ...
double a3 = 0.0; a[4] = 3.0;
double a4 = 0.0; ...
double a5 = 0.0; a[8] = 8.0;
double a6 = 0.0; double = x = a[4] + a[8];
double a7 = 0.0;
double a8 = 0.0;
double a9 = 0.0;
...
a4 = 3.0;
...
a8 = 8.0;
double x = a4 + a8;
Compiled_by_Tronic_636
Why arrays?
double a0 = 0.0; double[] a;
double a1 = 0.0; a = new double[10];
double a2 = 0.0; ...
double a3 = 0.0; a[4] = 3.0;
double a4 = 0.0; ...
double a5 = 0.0; a[8] = 8.0;
double a6 = 0.0; double = x = a[4] + a[8];
double a7 = 0.0;
double a8 = 0.0; Easy to scale, say to
double[] a;
double a9 = 0.0; 1,000,000 stored values
a = new double[1000000];
... ...
a4 = 3.0; a[4] = 3.0;
... ...
a8 = 8.0; a[8] = 8.0;
double = x = a4 + double x = a[4897] + a[890881];
a8; Compiled_by_Tronic_636
Arrays in memory
a accessing the cells n
a[0] a[1] a[2] a[3] a[4]
0 0 0 0 0 0
Indices 0 1 2 3 4
Compiled_by_Tronic_636
Arrays in memory
a accessing the cells n
a[0] a[1] a[2] a[3] a[4]
0 0 8 0 0 0
Indices 0 1 2 3 4
short[] a;
a = new short[5];
int n = 0;
a[2] = 8;
Compiled_by_Tronic_636
Arrays in memory
a accessing the cells n
a[0] a[1] a[2] a[3] a[4]
0 0 8 0 0 0
Indices 0 1 2 3 4
b
Compiled_by_Tronic_636
Array initializations
• Numeric types initialize to 0 by default
• Example: a = new double[10]; // all ten cells contain 0.0
• Can combine declaration, creation and initialization in one
statement
• Example: long[] n = new long[1000]; // all 0’s by default
• Example: double[] x = {0.2, 0.3, 0.4, 0.1};
// initialization with literal values
Compiled_by_Tronic_636
Copying an array
a b
21 0 8 10 70 21 0 8 10 70
Compiled_by_Tronic_636
How not to copy an array
a b
21 0 8 10 70 0 0 0 0 0
Compiled_by_Tronic_636
How not to copy an array
21 0 8 10 70 0 0 0 0 0
Compiled_by_Tronic_636
Example: command-line arguments
args is an array
public class CMDArray{
public static void main(String[] args){
String reg = args[0]; elements of args
String name = args[1];
int age = [Link](args[2]);
[Link](reg + " " + name + " " + age);
}
}
Compiled_by_Tronic_636
• Program requires three command –line
Example: command-line arguments
arguments
• User did not supply 3rd string ( at args[2])
public class CMDArray{
public static void main(String[] args){
String reg = args[0];
String name = args[1];
int age = [Link](args[2]);
[Link](reg
>java CMDArray BSc/COM/21/16 24 + " " + name + " " + age);
}
Exception in thread "main"
}[Link]: 2
at [Link]([Link])
> Compiled_by_Tronic_636
Example: an array of N random double values
double[] a = new double[N]; Range: [0, 1)
Compiled_by_Tronic_636
Example: Average of array values
double sum = 0.0;
Compiled_by_Tronic_636
Example: print array values
Compiled_by_Tronic_636
Example: maximum of array values
double max = a[0];
Compiled_by_Tronic_636
Typical bugs
double[] a = new double[10];
Array index out of bounds
for (int i = 1; i <= 10; i++)
– no a[10]
a[i] = [Link]();
Compiled_by_Tronic_636
Typical bugs
double[] a;
Missing a = new double[N];
for (int i = 0; i < 9; i++)
a[i] = [Link]();
At this point, a is
uninitialized – the array has
not been created.
Compiled_by_Tronic_636
Typical bugs
public class RandArray{
public static void main(String[] args){
a = new double[10];
Compiled_by_Tronic_636
Typical bugs
public class RandArray{
public static void main(String[] args){
double a = new double[10];
Compiled_by_Tronic_636
Typical bugs
public class RandArray{
public static void main(String[] args){
double[] a = new double[10];
Compiled_by_Tronic_636
Example: representing a deck of playing cards
• Deck has 52 cards (excluding joker)
• 13 ranks: 2, 3, 4, 5, 6, 7, 8, 9 , 10,
J – Jack
Q – Queen
K – King
A – Ace
• Suits: – clubs
– diamonds
– hearts
– spades
Compiled_by_Tronic_636
Example: representing a deck of playing cards
• Want to store the 52 unique cards in an array
• One approach is to define each of the 52 cards
• deck[0] = "2 "; deck[1] = "3 "; ...
• 52 definitions!
• Why not use loops?
1. Create three arrays: rank, suit and deck
2. Combine each suit with all ranks
Compiled_by_Tronic_636
Example: representing a deck of playing cards
String[] rank = {"2", "3", "4", "5", "6", "7",
"8", "9", "10", "J", "Q", "K", "A" };
String[] suit = { " ", " ", " ", " " };
i 0 1 2 3 4 5 6 7 8 9 10 11 12
rank 2 3 4 5 6 7 8 9 10 J Q K A
j 0 1 2 3
suit
i 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 … 51
deck …
Compiled_by_Tronic_636
Example: representing a deck of playing cards
for (int j = 0; j < 4; j++)
for (int i = 0; i < 13; i++)
deck[i + 13*j] = rank[i] + suit[j];
i 0 1 2 3 4 5 6 7 8 9 10 11 12
rank 2 3 4 5 6 7 8 9 10 J Q K A
j 0 1 2 3
suit
i 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 … 51
deck 2 3 4 5 6 7 8 9 10 J Q K A 2 3 4 … A
j = 0 j = 1
(i + 13*j) = i (i + 13*j) = 13 + i
Compiled_by_Tronic_636
public class Deck{
public static void main(String[] args){
String[] rank = {"2", "3", "4", "5", "6", "7",
"8", "9", "10", "J", "Q", "K", "A" };
String[] suit = { " ", " ", " ", " " };
String[] deck = new String[52];
[Link]();
}
} Compiled_by_Tronic_636
>javac [Link]
>java Deck
2 3 4 5 6 7 8 9 10 J Q K A 2 3 4 5 6 7
8 9 10 J Q K A 2 3 4 5 6 7 8 9 10 J Q
K A 2 3 4 5 6 7 8 9 10 J Q K A
>
Compiled_by_Tronic_636
Example: representing a deck of playing cards
• What if we change the order of loops?
for (int j = 0; j < 4; j++)
for (int i = 0; i < 13; i++)
deck[i + 13*j] = rank[i] + suit[j];
Compiled_by_Tronic_636
Example: representing a deck of playing cards
for (int i = 0; i < 13; i++)
for (int j = 0; j < 4; j++)
deck[i + 13*j] = rank[i] + suit[j];
i 0 1 2 3 4 5 6 7 8 9 10 11 12
rank 2 3 4 5 6 7 8 9 10 J Q K A
j 0 1 2 3
suite Same array, different filling order
i 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 … 51
deck 2 3 4 5 6 7 8 9 10 J Q K A 2 3 4 … A
1 5 9 13 2 6 10
Compiled_by_Tronic_636
Drawing a random card from the deck
• Solution:
1. Generate a random int between 0 and 51
2. print card at deck[r]
The value of this expression is a
random int between 0 and 51.
int rnd = (int)([Link]() * 52); Recall that casting a double into
[Link](deck[rnd]); an int simply drops the
fractional part
Compiled_by_Tronic_636
Drawing a random sequence of cards
• Naiive solution
1. Repeat for N times
a. Generate a random int between 0 and 51
b. print card at deck[r]
int N = [Link](args[0]);
[Link]();
Compiled_by_Tronic_636
Drawing a random sequence of cards
• Naiive solution
1. Repeat for N times
a. Generate a random int between 0 and 51
b. print card at deck[r]
int N = [Link](args[0]);
The algorithm simulates picking
>java Deck 10 a card and replacing it in the
for (int i = 0; i7 < 4N; 2i++){
8 J 7 K J deck3 before
6
int rnd = (int)([Link]() * 52); picking the next
[Link](deck[rnd] + " "); one.
>java Deck 20
} 9 3 3 9 4 J 8 Q 7 5 4 6 A K
10 J 10 5 9 7
[Link]();
>
Compiled_by_Tronic_636
Simulating shuffle and deal
• Dealing
• No replacement once a card is drawn
• Shuffling:
1. Consider each card i
a. generate random int rnd between 0 and 51
b. swap card at i and rnd
• Dealing
1. Print the first N cards in the deck
Compiled_by_Tronic_636
Simulating shuffle and deal
Shuffle
for (int i = 0; i < 52; i++){
int rnd = (int)([Link]() * 52);
String temp = deck[i];
deck[i] = deck[rnd]; Swap
deck[rnd] = temp;
}
[Link]();
Compiled_by_Tronic_636
Simulating shuffle and deal
for (int i = 0; i < 52; i++){
int rnd = (int)([Link]() * 52);
String temp = deck[i];
deck[i]
>java = deck[rnd];
Deck 20
deck[rnd]
J 10 6 A J= temp;
2 3 8 K 9 7 Q 6 3 7 10 4 7
} K A
for>java
(int Deck
i = 0;
20 i < N; i++)
10 [Link](deck[i]
7 K 2 Q 3 3 Q 7 5 + "J ");
4 2 J 5 4 9 3 8
A
[Link]();
>
Compiled_by_Tronic_636
The coupon collectors problem
• M different types of coupons
• Collector acquires random coupons, one at a time
• Each coupon is equally likely
• What is the average number of coupons that must be collected to
guarantee a full collection?
Compiled_by_Tronic_636
The coupon collectors problem
• Example: Collect all ranks in a random sequence of cards
Collection
2 3 4 5 6 7 8 9 10 J Q K A
2 3 4 5 6 7 8 9 10 J Q K A
5 9 10 Q
9 18 cards to complete collection
Compiled_by_Tronic_636
The coupon collector problem
• Solution:
1. Generate random int values between 0 and M – 1
2. Count number int values used to generate each value at least once
• Refined solution:
1. Create an array of Boolean values, all initialized to false
2. When random rnd is generated, check the array index rnd
a. if false
a. count as new distinct value
b. set value at index to true
Compiled_by_Tronic_636
public class Coupon{
public static void main(String[] args){
int M = [Link](args[0]);
int cards = 0; // number of cards collected
int distinct = 0; // number of distinct cards
boolean[] found = new boolean[M];
if (!found[rnd]){
distinct++;
found[rnd] = true;
}
}
[Link](cards);
}
} Compiled_by_Tronic_636
The coupon collector problem
>java Coupon 10
38
>java Coupon 10
23
>java Coupon 10
32
>java Coupon 10
31
>
Compiled_by_Tronic_636
The coupon collector problem
• The average number of cards to guarantee full collection is
approximated by
𝑀 ln 𝑀 + 0.57722𝑀
M Expected wait
4 8
13 41
52 236
>
Compiled_by_Tronic_636
Two-dimensional arrays
row index
• Represent tabular data 0 1 2 3 4
• matrices 0
• table of student grades column 1
column
• pixels in an image index 2
• etc 3
row
Note that rows and columns are switched in the
usual representation of tables! This has been done
for convenience when printing contents of 2D
arrays.
Compiled_by_Tronic_636
Two-dimensional arrays syntax
• Declaration
• data_type [][] array_name;
• e.g. double[][] a;
• Creation
• array_name = new data_type[rows][columns];
• e.g. a = new double[5][100];
Compiled_by_Tronic_636
Two-dimensional arrays syntax
• Referencing
• array_name[row_index][col_index]
• e.g. a[1][2] 0 1 2 3 4
0 3.2 2.5 3.1 1.3 9.9
1 0.7 0.1 0.0 5.1 5.2
2 0.5 2.2 1.2 6.3 8.1
3 3.5 3.3 3.0 0.9 0.1
Compiled_by_Tronic_636
Two-dimensional arrays syntax
• Referencing
• array_name[row_index][col_index]
• e.g. a[3][0] 0 1 2 3 4
0 3.2 2.5 3.1 1.3 9.9
1 0.7 0.1 0.0 5.1 5.2
2 0.5 2.2 1.2 6.3 8.1
3 3.5 3.3 3.0 0.9 0.1
Compiled_by_Tronic_636
Two-dimensional arrays syntax
• Referencing
• array_name[row_index][col_index]
• e.g. a[0][3] 0 1 2 3 4
0 3.2 2.5 3.1 1.3 9.9
1 0.7 0.1 0.0 5.1 5.2
2 0.5 2.2 1.2 6.3 8.1
3 3.5 3.3 3.0 0.9 0.1
Compiled_by_Tronic_636
Two-dimensional arrays syntax
• Referencing
• array_name[row_index][col_index]
• e.g. a[4][1] 0 1 2 3 4
0 3.2 2.5 3.1 1.3 9.9
1 0.7 0.1 0.0 5.1 5.2
2 0.5 2.2 1.2 6.3 8.1
3 3.5 3.3 3.0 0.9 0.1
Compiled_by_Tronic_636
Two-dimensional arrays syntax
• Referencing
• array_name[row_index][col_index]
• e.g. a[4][1] = a[0][0] + a[3][2] 0 1 2 3 4
0 3.2 2.5 3.1 1.3 9.9
1 0.7 0.1 0.0 5.1 5.2
2 0.5 2.2 1.2 6.3 8.1
3 3.5 3.3 3.0 0.9 0.1
Compiled_by_Tronic_636
Two-dimensional arrays syntax
• Referencing
• array_name[row_index][col_index]
• e.g. a[4][1] = a[0][0] + a[3][2]; 0 1 2 3 4
0 3.2 2.5 3.1 1.3 9.9
1 0.7 0.1 0.0 5.1 9.5
2 0.5 2.2 1.2 6.3 8.1
3 3.5 3.3 3.0 0.9 0.1
Compiled_by_Tronic_636
Two-dimensional arrays syntax
• Referencing
• array_name[row_index][col_index]
• e.g. a[1][4] 0 1 2 3 4
0 3.2 2.5 3.1 1.3 9.9
1 0.7 0.1 0.0 5.1 5.2
2 0.5 2.2 1.2 6.3 8.1
3 3.5 3.3 3.0 0.9 0.1
Compiled_by_Tronic_636
Two-dimensional arrays initializations
• Default initializations
• a = new double [3][2];
• All the six cells initialized to 0.0 by default
• Declare, create and initialize in one statement
• double a = new double[3][2];
• All the six cells initialized to 0.0 by default
Compiled_by_Tronic_636
Two-dimensional arrays initializations
• Initialization with literal values
double[][] st = {{3.0, 0.0, 0.0, 0.0},
{0.0, 3.0, 0.0, 0.0},
{0.0, 0.0, 3.0, 0.0},
{0.0, 0.0, 0.0, 0.1}};
Compiled_by_Tronic_636
Array applications
• Vector addition
• < 𝒂𝟏, 𝒃𝟏, 𝒄𝟏 > + < 𝒂𝟐, 𝒃𝟐, 𝒄𝟐 > = < (𝒂𝟏 + 𝒂𝟐), (𝒃𝟏 + 𝒃𝟐), (𝒄𝟏 + 𝒄𝟐) >
• < 𝟏𝟎, 𝟐𝟑, 𝟏𝟐 > + < 𝟕, −𝟐, 𝟎 > = < 𝟏𝟕, 𝟐𝟏, 𝟏𝟐 >
Compiled_by_Tronic_636
Array applications
• Matrix addition
Compiled_by_Tronic_636
Array applications
We have assumed that a[][]
• Square matrix multiplication and b[][] already exist.
3.0 0.0 0.0 0.0 1.0 3.0 0.5 0.0 3.0 9.0 1.5 0.0
0.0 3.0 0.0 0.0 0.4 1.0 1.0 0.0 1.2 3.0 3.0 0.0
0.0 0.0 3.0 0.0 0.3 0.5 0.7 0.0 0.9 1.5 2.1 0.0
0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0
Compiled_by_Tronic_636
row index
Printing contents of 2D arrays 0 1 2 3 4
0
column 1
column
index 2
for(int i = 0; i<N; i++){
3
for(int j = 0; j < N; j++)
[Link](a[i][j] + "\t");
row
[Link]();
}
Compiled_by_Tronic_636
Input and output
LECTURE_6
Compiled_by_Tronic_636
Current situation: program vs. outside world
Command-line arguments
Program terminal
Compiled_by_Tronic_636
Input: command-line arguments
Available via the args[]
array in the program
public class RandomInt{
public static void main(String[] args){
int N = [Link](args[0]);
double r = [Link](); Typed after program
int t = (int) (r * N); name when running
[Link](t); program
Compiled_by_Tronic_636
Output: standard output stream
• Abstraction of an infinite output sequence
• In theory, never full / never run out of memory
• Strings from [Link]() are appended to the
standard output stream by default
• Standard output stream is sent to the terminal by default
Terminate the current output line and move
• Some useful methods insertion point to the first column of the next line
• [Link]() Print the given string, terminate the current line
• [Link](String s) so that next output print on the next line
• [Link](String s) Print the string
• [Link](String f,…) formatted printing
Compiled_by_Tronic_636
Extension: program vs. outside world
Command-line arguments
Compiled_by_Tronic_636
Standard input stream
• Abstraction of an infinite input sequence
• Accessible via the object called [Link]
• Connected to the keyboard by default
• Cannot use [Link] directly in a console application
• Need to encapsulate [Link] in a Scanner object
• Scanner input = new Scanner ([Link]);
• Scanner is defined in a package called [Link]
• Need to import the Scanner definition before you can use it
• import [Link]; // first statement in the file
Compiled_by_Tronic_636
Advantages of standard input stream over
command-line arguments
• Can provide input on-the-fly as the program is execute
• No limit on the amount of data input
• Handles conversion to primitive types explicitly
Compiled_by_Tronic_636
Some useful Scanner methods (for this course)
Method Data Type Description
nextInt() int Get next int from the user.
nextFloat() float Get next float from the user.
nextBoolean() boolean Get next boolean from the user.
nextLine() String Get next line from the user.
next() String Get next token (string) from the user.
nextByte() byte Get next byte from the user.
nextDouble() double Get next doublefrom the user.
nextShort() short Get next short from the user.
nextLong() long Get next long from the user.
Compiled_by_Tronic_636
More useful Scanner methods (for this course)
Method Data Type Description
hasNextInt() boolean Is there an int in the input stream?
hasNextFloat() boolean Is there a float in the input stream?
hasNextBoolean() boolean Is there a boolean in the input stream?
hasNextLine() boolean Is there a line in the input stream?
hasNext() boolean Is there a String in the input stream?
hasNextByte() boolean Is there a byte in the input stream?
hasNextDouble() boolean Is there a double in the input stream?
hasNextShort() boolean Is there a short in the input stream?
hasNextLong() boolean Is there a long in the input stream?
Compiled_by_Tronic_636
Example
import [Link];
Compiled_by_Tronic_636
Example
import [Link];
Compiled_by_Tronic_636
Example: Avarage
• Read a stream of numbers
• Compute their average
Compiled_by_Tronic_636
import [Link];
while ([Link]()){
double x = [Link]();
sum = sum + x;
n++;
}
[Link](sum / n);
}
} Compiled_by_Tronic_636
Example: generate a stream of random numbers
Compiled_by_Tronic_636
Transferring output to input
Command-line arguments
Compiled_by_Tronic_636
Transferring via external file
>java RandomSeq 1000 > [Link] The amount of data
transferred is limited by
>java Average < [Link] the maximum file size
0.47395011579773716
>
Compiled_by_Tronic_636
Transferring through piping
>java RandomSeq 1000000 | java Average Set up a pipe
0.4999720048023056
Compiled_by_Tronic_636
Functions
Static methods
LECTURE_7
Compiled_by_Tronic_636
Outline
• In Java, functions are available as static methods
• Another kind of method is the instance method – for later (OOP)
• Function
• Takes 0 or more arguments
• Returns 0 or 1 output value
• May cause some side effects – e.g. print text, draw, play sound, etc
• Examples:
• Built-in: [Link](), [Link](),
[Link](), etc
• User-defined: main()
Compiled_by_Tronic_636
Outline
Inputs
Side effects
Output
Compiled_by_Tronic_636
Example Return type Argument
declarations
Method name
Method’s
public static double sqrt(double c, double eps){ signature
if (c < 0)
return [Link];
Method
double t = c; body
Compiled_by_Tronic_636
Library/Module
• Module: collection of functions
• Library: collection of modules
• Simply put: both refer to a collection of functions
• For this course, we assume module = library
Compiled_by_Tronic_636
Scope of variables
• Defn. Scope of a variable is the section of code that can refer to the
variable
• From point of declaration to the end of the block in which it is
declared
• Nested blocks can also refer to the variable
• Good programming practice: limit the scope of variables
• Makes reading of the code easier
Compiled_by_Tronic_636
public class Newton{
public static double sqrt(double c, double eps){
Scope of c and eps if (c < 0)
return [Link];
double t = c;
while ([Link](t - c/t) > eps * t)
Scope of t
t = (c/t + t) / 2.0;
return t;
}
Compiled_by_Tronic_636
What does the following code do?
public class PQfunctions1d{
public static int cube(int i){
i = i * i * i;
return i;
}