0% found this document useful (0 votes)
7 views248 pages

Introduction to Computer Programming Basics

Uploaded by

shekedeganizani2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views248 pages

Introduction to Computer Programming Basics

Uploaded by

shekedeganizani2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COM121

Introduction to Computer Programming

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!

Input prog Output

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

Transform outline into an algorithm

Test algorithm for correctness

Code the algorithm in some programming language

Run the program

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

public class Hello{


public static void main(String [] args){
[Link]("Hello, world");
}
}

• Code must be placed in a file called [Link] body of main()

• > javac [Link] Compile


• > java hello
Execute/Run

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

public class ProgramName{


public static void main(String [] args){

...

}
}

body of main()
Compiled_by_Tronic_636
Program formatting Avoid

public class Hello{public static void main(String []


args){[Link]("Hello, world");}
}
public class Hello{
public static void main(String [] args){
[Link]("Hello, world");
}
}

Compiled_by_Tronic_636
Program formatting Even better!

/************************
Program: Hello
Author: MF Msiska

Prints “Hello, word” to the console.


*************************/
public class Hello{
public static void main(String [] args){
[Link]("Hello, world");
}
} Compiled_by_Tronic_636
Programming style
• Correct use of white spaces
• Thou shall indent your code to highlight blocks!
• Why bother about style?
• Code readability

Compiled_by_Tronic_636
Coding Cycle
1. Edit program Edit

• typing the code


• Result: Source code in a text file *.java
2. Compile the program
• Run javac (compiler)
Compile Run
• Result: Java bytecode in a *.class file
3. Run the program
• Use Java runtime (java …)
• Result: program’s output

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

floating point numbers

boolean Primitive data types

String Reference data types

Built-in data types


Compiled_by_Tronic_636
Basic definitions
• Variable
• name associated with a value
• Literal
• programming language representation of a value
• Declaration statement
• associates a variable with a data type
• Assignment statement
• associates a value with a variable

Compiled_by_Tronic_636
Basic definitions
variables
data types
literals
Declarations int a;
int b;
Assignments a = 2004;
b = 2023;
int c = b - a;

Combination of declaration and assignment

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

"a + " + " b = " + "12"

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

public class Swap{ 23

public static void main(String [] args){ 5

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

Values −𝟐𝟑𝟏 to +𝟐𝟑𝟏 − 𝟏


Sample literals 23 -47 10000 0
Operations add subtract multiply divide remainder
Operator + - * / %

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

Values Real numbers


Sample literals 3.145 -4.7 0.0 5.036e12
Operations add subtract multiply divide remainder
Operator + - * / %

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

double sin(double theta) sine function


double cos(double theta) cosine function Inverses: asin(), acos() and
atan()
double tan(double theta) tangent function

theta in radians! toDegrees(),


toRadians() for interconversions.

Compiled_by_Tronic_636
Math Library

Method Return value


double exp(double a) exponential (𝒆𝒂 )
double log(double a) natural log (log 𝒆 𝒂, or ln 𝒂)
double pow(double a, double b) raise a to the bth power (𝒂𝒃 )
long round(double a) round to the nearest integer
double random() random number in [𝟎. 𝟏)
double sqrt(double a) square root of 𝒂

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

// Calculate roots of a*x*x + b*x + c.


double discriminant = b*b - 4.0*a*c;
double d = [Link](discriminant);
double root1 = (-b + d) / 2.0/a;
double root2 = (-b - d) / (2.0*a);

// Print them out.


[Link](root1);
[Link](root2);
}
}

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

Values true false


Literals true false
Operations AND OR NOT
operator && II !

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

Operator Meaning true false


== equal 2 == 2 2 == 3
!= not equal 2 != 3 2 == 3
< less than 2<3 2<2
<= less than or equal 2 <= 2 3 <= 2
> greater than 3>2 2>3
>= greater than or 3 >= 2 2 >= 3
equal

Compiled_by_Tronic_636
public class LeapYear{
public static void main(String[] args){
int year = [Link](args[0]);
boolean isLeapYear;

// divisible by 4 but not 100


isLeapYear = (year % 4 == 0) && (year % 100 != 0);

// 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;
}
}

* not defined for String


data type

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

"age: " + 21 "age: 21"

String String String


int

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

Casting applies to the whole expression


in parentheses. Drops the fractional
part (not rounding!)

Compiled_by_Tronic_636
Casting
• The cast operation has the highest precedence!

int circ = (int) (3.14159 * 10) 31

int circ = (int) 3.14159 * 10 30


Cast applies to 10, and has no
effect. 3.14159 is still a double!
int circ = (int) 10 * 3.14159 compile error!

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]

int float >java Overflow


n = -15536
𝟓𝟎𝟎𝟎𝟎 % 𝟐𝟏𝟓 − 𝟐𝟏𝟓
long double >

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;

int val = [Link](args[0]);

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

if (a > b){// swap Block


{// swap
int temp = a;
int temp = a;
a = b;
a = b;
b = temp;
b = temp;
}
}
[Link](a + ", " + b);
}
} 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]);
[Link]("Average = " + total/count);
}
}

>java DivErrorChk 32.3 0


Average = Infinity

>

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; Get the value of count, add


1 to it and store the result
back in 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]);

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

• Both have prefix and postfix variants


• Postfix: x++ - fetch the current value of x, use it in the expression before
finally increment x
• Prefix: ++x – first increment the value of x before using it in an expression

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

while (i <= n){


[Link](val);
i++;
val *=2; // val = val / 2
}
}
}
Compiled_by_Tronic_636
Example: computing the first n powers of 2
public class PowersOfTwo{ i val i < n
public static void main(String[] args){
0 1 true
int n = [Link](args[0]);
int i = 0; 1 2 true
int val = 1; // 2 to the power 0 2 4 true
3 8 true
while (i <= n){
4 16 true
[Link](val);
i++; 5 32 true
val *=2; // val = val / 2 6 64 false
}
}
}
Compiled_by_Tronic_636
Example: computing the first n powers of 2
public class PowersOfTwo{
public static void main(String[] args){ >javac [Link]
int n = [Link](args[0]);
int i = 0; >java PowersOfTwo 5
int val = 1; // 2 to the power 0 1
while (i <= n){
2
[Link](val); 4
i++; 8
val *=2; // val = val * 2 16
} 32
}
}
Compiled_by_Tronic_636
>
The for statement
Typically initializes an int Typically increments
• Syntax: the controlled variable
variable – the controlled
variable
for (initialization; condition; advancement)
statement; Initialization, condition
and advancement are all
optional!
Typically a compound
statement A boolean
expression

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

int i= 1; for(int i = 1; i < n; i++){


[Link](i);
while (i< n){ boolean expression
}
[Link](i);
i= i+ 1; Advancement (increment)
}

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;

while (cash > 0 && cash < goal)


if ([Link]() < 0.5)
if-else nested inside while
cash++;
loop, which in turn is
else
nested within for loop
cash--;

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

if (grade >= 80)


letter = 'A';
else{
if (grade >= 60)
letter = 'B';
else{
if (grade >= 50)
letter = 'C';
else
letter = 'F';
}
}
[Link]("Grade: " + grade + " -> " + letter);
}
}
Compiled_by_Tronic_636
>javac [Link]

>java GradeLetter 12
Grade: 12 -> F

>java GradeLetter 51
Grade: 51 -> C

>java GradeLetter 100


Grade: 100 -> A

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

if (grade >= 80) What is wrong with this


letter = 'A'; code?
if (grade >= 60)
letter = 'B';
consider case when grade == 90
if (grade >= 50)
letter = 'C';
else
letter = 'F';

All these evaluate to true. Therefore


[Link]("Grade: " + grade + " -> " + letter);
}the final value of letter is 'C'
} Compiled_by_Tronic_636
public class GradeLetterC{
public static void main(String[] args){
int grade = [Link](args[0]);
char letter = 'D';

if (grade >= 80)


letter = 'A';
else if (grade >= 60)
letter = 'B';
else if (grade >= 50)
letter = 'C';
else
letter = 'F';

[Link]("Grade: " + grade + " -> " + letter);


}
}
Compiled_by_Tronic_636
>javac [Link]

>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

• Some flaw with your code • Easiest to resolve (in theory)


• Caught by compiler
Runtime error • Program with syntax errors does
not compile
• Harder to find and resolve
• Compiler is not useful here
Efficiency
• Program compiles and runs but
may produce incorrect results • Is the program using computing
or crash resources efficiently?
• Resources = time + memory
• Problem typically only shows up
when the program runs on large
input
Compiled_by_Tronic_636
What is debugging?
• Removing bugs from programs
• “What programmers do 99% of their time!”
• why?
• Useful programs typically have conditionals and loops
• program with n conditionals has 2𝑛 possible execution paths!
• program with 1 loop has ∞ possible execution paths!
• Now add nesting to the concoction

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

for (i = 0; i < n; i++){


while (n % i == 0)
[Link](i + " ")
n = n / i
}
}
}

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

for (i = 0; i < n; i++){


while (n % i == 0)
[Link](i + " ")
n = n / i Missing ;
}
}
}
Missing
type for i
Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);

for (int i = 0; i < n; i++){


while (n % i == 0)
[Link](i + " ");
n = n / i;
}
}
}

Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);

for (int i >java


= 0; iFactors
< n; i++){
whileException
(n % i ==in0)thread "main"
[Link]
[Link](i + " ");
n:
n =0 n / i;
} at [Link]([Link])
}
} >
Missing command-line
argument
Compiled_by_Tronic_636
Example: The factoring problem Runtime error!

public class Factors{


public static void main(String[] args){
long n = [Link](args[0]);

for (int i >java


= 0; iFactors 6
< n; i++){
whileException
(n % i ==in0)thread "main"
[Link]:
[Link](i + " "); / by
zero
n = n / i;
} at [Link]([Link])
}
} >

Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);

for (int i = 0; i < n; i++){


while (n % i == 0)
[Link](i + " ");
n = n / i;
}
• 0 cause the “division by zero” error
}
• Need to start at 2, since 0 and 1 are
}
not factors anyway

Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);

for (int i = 2; i < n; i++){


while (n % i == 0)
[Link](i + " ");
n = n / i;
}
}
}

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

for (int i >java


= 2; iFactors 6
< n; i++){
while222222222222222222222222222222222222222
(n % i == 0)
222222222222222222222222222222222222222
[Link](i + " ");
222222222222222222222222222222222222222
n = n / i;
} 222222222222222222222222222222222222222
} 222222222222222222222222222222222222222
} 222222222222222222222222222222222222222
222222222222222222222222222222222222222
222222222222222222222222222222222222222
222222222222222222222222222222222222222
Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);

for (int i = 2; i < n; i++){


while (n % i == 0)
[Link](i + " ");
n = n / i;
}
} • These need to be enclosed in a block,
} otherwise n = n / i never gets
executed, and the value of never
changes, hence the while loops forever!
Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);

for (int i = 2; i < n; i++){


while (n % i == 0){
[Link](i + " ");
n = n / i;
}
}
}
}

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

for (int i =>java


2; Factors
i < n;98i++){
2 7 7 No output for 5
while (n % i == 0){
>java Factors 5
[Link](i + " ");
n = n / i;
} >java Factors 6
Missing the last
} 2
factor (3) for 6
} >
}

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

for (int i = 2; i <= n; i++){


while (n % i == 0){
[Link](i + " ");
n = n / i;
}
}
}
}

Compiled_by_Tronic_636
Example: The factoring problem
>javac [Link]

public class Factors{ >java Factors 98


public static void 2main(String[]
7 7 args){
long n = [Link](args[0]);
>java Factors 5
5
for (int i = >java
2; i <= n; i++){
Factors 6
while (n2 %3 i == 0){
[Link](i + " ");
>java Factors 1111111111111111
n 11
= n17 / 73 i; 101 137 5882353
} >java Factors 11111111111111111
} 2071723 -1 -1 -1 -1 -1 -1 -1 -1 -1
} -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
} -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
Compiled_by_Tronic_636
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);

for (int i = 2; i <= n; i++){


while (n % i == 0){
[Link](i + " ");
n = n / i;
}
An attempt to increment i beyond
}
} 2,147,483,647(= 𝟐𝟑𝟏 −𝟏) results in an
} overflow and i becomes -2,147,483,648

Compiled_by_Tronic_636
Example: The factoring problem
public class Factors{
public static void main(String[] args){
long n = [Link](args[0]);

for (long i = 2; i <= n; i++){


while (n % i == 0){
[Link](i + " ");
n = n / i;
}
}
}
}

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

for (long i = 2; i <= n; i++){


while (n % i == 0){
[Link](i + " ");
n = n / i;
}
}
}
} Do we really need to test
all the way to n?
Compiled_by_Tronic_636
Example: The factoring problem
• Turns out that if 𝑖 2 > 𝑛 we cannot find any factor less than 𝑛
• We have already listed all factors < 𝑖
• Therefore we need to debug the solution as follows
• 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]);

for (long i = 2; i <= n / i; i++){ Stop when 𝒊𝟐 > 𝒏


while (n % i == 0){
[Link](i + " ");
n = n / i;
}
}
We need this in order to
if (n > 1) include the last factor, since
[Link](n); we now stop searching when
} 𝒊𝟐 > 𝒏
} Compiled_by_Tronic_636
Example: The factoring problem
Digits in the largest i <= n i <= n / i
factor
3 Instant Instant
6 instant Instant
9 77 Instant
12 21 hours Instant
15 2.4 years 2.7 seconds
18 2,400 years 97 seconds

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

Run – does it work as intended?

Test – with real input data

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

• Array values are stored in contiguous locations


short[] a; • Array indices start at 0
a = new short[5]; • Direct access to every element through a[i]
int n = 0; • Very efficient

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

short[] a; • The assignment b = a does not create a copy of


a = new short[5]; the array
int n = 0; • a and b now refer to the same physical array
a[2] = 8;
short[] b;
b = a;
Compiled_by_Tronic_636
Working with arrays in Java
• Declaring an array
• Syntax: data_type[] array_name;
• Example: double [] a;
• Creating an array of a given length
• Syntax: array_name = new data_type[length_of_array];
• Example: a = new double[100];
• Refer to an element
• Syntax: array_name[index]
• Example: a[i] = a[j] + a[k];
Compiled_by_Tronic_636
Working with arrays in Java
• Length of an array
• Syntax: array_name.length
• Example: [Link]

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

short[] b = new double[[Link]];


for (int i = 0; i < [Link]; i++)
b[i] = a[i];

a b

21 0 8 10 70 21 0 8 10 70

Compiled_by_Tronic_636
How not to copy an array

short[] b = new double[[Link]];

a b

21 0 8 10 70 0 0 0 0 0

Compiled_by_Tronic_636
How not to copy an array

short[] b = new double[[Link]];


b = a;

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

>java CMDArray BSc/COM/21/16 George 24


BSc/COM/21/16 George 24

> Compiled_by_Tronic_636
Example: an array of N random double values
double[] a = new double[N]; Range: [0, 1)

for (int i = 0; i < N; i++)


a[i] = [Link]();

double[] a = new double[N];


Range: [10, 100)
for (int i = 0; i < N; i++)
a[i] = 10 + [Link]() * 90;

Compiled_by_Tronic_636
Example: Average of array values
double sum = 0.0;

for (int i = 0; i < [Link]; i++)


sum += a[i];

double average = sum / [Link];

Compiled_by_Tronic_636
Example: print array values

for (int i = 0; i < N; i++)


[Link](a[i]);

Compiled_by_Tronic_636
Example: maximum of array values
double max = a[0];

for (int i = 1; i < N; i++)


if (a[i] > max)
max = a[i];

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

Since i starts from 1, a[0]


remains unused

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

for (int i = 0; i < 10; i++)


a[i] = [Link]();
}
}
Variable a has not been
declared.

Compiled_by_Tronic_636
Typical bugs
public class RandArray{
public static void main(String[] args){
double a = new double[10];

for (int i = 0; i < 10; i++)


a[i] = [Link]();
}
}
Wrong type.
Must be double []

Compiled_by_Tronic_636
Typical bugs
public class RandArray{
public static void main(String[] args){
double[] a = new double[10];

for (int i = 0; i < 10; i++)


a[i] = [Link]();
}
}

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 = { " ", " ", " ", " " };

String[] deck = new String[52];

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

for (int j = 0; j < 4; j++)


for (int i = 0; i < 13; i++)
deck[i + 13*j] = rank[i] + suit[j];

for (int i = 0; i < 52; i++)


[Link](deck[i] + " ");

[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];

for (int i = 0; i < 13; i++)


for (int j = 0; j < 4; j++)
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]);

for (int i = 0; i < N; i++){


int rnd = (int)([Link]() * 52);
[Link](deck[rnd] + " ");
}

[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;
}

for (int i = 0; i < N; i++)


Deal
[Link](deck[i] + " ");

[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

Random sequence of cards


9 5 4 10 2 A 10 Q 3 9 5 9 7 J 8 6 Q K

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

while (distinct < M){


int rnd = (int) ([Link]() * M);
cards++;

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

• We can verify these theoretical results through simulation


1. Run the program a large number of times
2. Compute the average
Compiled_by_Tronic_636
public class Coupon{
public static void main(String[] args){
int M = [Link](args[0]);
int trials = [Link](args[1]);
int cards = 0; // number of cards collected
for (int j = 0; j < trials; j++){
int distinct = 0; // number of distinct cards
boolean[] found = new boolean[M];
while (distinct < M){
int rnd = (int) ([Link]() * M);
cards++;
if (!found[rnd]){
distinct++;
found[rnd] = true;
}
}
}
[Link](cards/trials);
}
}
Compiled_by_Tronic_636
The coupon collector problem
>java Coupon 4 100000
8
M Expected wait
>java Coupon 13 100000 4 8
41 13 41
52 236
>java Coupon 52 100000
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

Array index out of bounds


exception
Compiled_by_Tronic_636
Two-dimensional arrays syntax
• Referencing
• array_name.length gives number of
rows 0 1 2 3 4
• e.g. [Link] == 5 0 3.2 2.5 3.1 1.3 9.9
• array_name[index].length gives 1 0.7 0.1 0.0 5.1 5.2
the number of columns for row index
2 0.5 2.2 1.2 6.3 8.1
• e.g a[0].length == 4
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
• < 𝒂𝟏, 𝒃𝟏, 𝒄𝟏 > + < 𝒂𝟐, 𝒃𝟐, 𝒄𝟐 > = < (𝒂𝟏 + 𝒂𝟐), (𝒃𝟏 + 𝒃𝟐), (𝒄𝟏 + 𝒄𝟐) >
• < 𝟏𝟎, 𝟐𝟑, 𝟏𝟐 > + < 𝟕, −𝟐, 𝟎 > = < 𝟏𝟕, 𝟐𝟏, 𝟏𝟐 >

double[] c = new double[N];

for (int i = 0; i < N; i++)


c[i] = a[i] + b[i];

We have assumed that a[] and


b[] already exist.

Compiled_by_Tronic_636
Array applications
• Matrix addition

𝒂𝟏 𝒃𝟏 𝒄𝟏 𝒂𝟐 𝒃𝟐 𝒄𝟐 (𝒂𝟏 + 𝒂𝟐) (𝒃𝟏 + 𝒃𝟐) (𝒄𝟏 + 𝒄𝟐)


𝒅𝟏 𝒆𝟏 𝒇𝟏 𝒅𝟐 𝒆𝟐 𝒇𝟐 (𝒅𝟏 + 𝒅𝟐) (𝒆𝟏 + 𝒆𝟐) (𝒇𝟏 + 𝒇𝟐)
𝒈𝟏 𝒉𝟏 𝒊𝟏 𝒈𝟐 𝒉𝟐 𝒊𝟐 (𝒈𝟏 + 𝒈𝟐) (𝒉𝟐 + 𝒉𝟐) (𝒊𝟏 + 𝒊𝟐)

double[][] c = new double[N][N];


for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
c[i][j] = a[i][j] + b[i][j];
We have assumed that a[][]
and b[][] already exist.
Compiled_by_Tronic_636
Array applications
• Vector dot product
• < 𝑎1 , 𝑏1, 𝑐1 > ∙ < 𝑎2, 𝑏2, 𝑐2 > = 𝑎1𝑎2 + 𝑏1𝑏2 + 𝑐1𝑐2
• < 10, 23, 12 > ∙ < 7, −2, 0 > = 70 − 46 + 0 = 24

double dot = 0.0;

for (int i = 0; i < N; i++)


dot += a[i] * b[i];

We have assumed that a[] and


b[] already exist.

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

double[][] c = new double[N][N]; How many multiplication


for (int i = 0; i < N; i++) operations?
for (int j = 0; j < N; j++) Ans: 𝑵𝟑
for (int k = 0; k < N; k++)
c[i][j] += a[i][k] * b[k][j];

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

Standard output stream

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

} > java RandomInt 6


} 5
> java RandomInt 10000
May need to convert the
string args[x] into some 1837
other data type

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

Standard input stream


Program terminal

Standard output stream

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

public class AddTwo{


public static void main(String[] args){
Scanner in = new Scanner([Link]);

[Link]("Type the first integer: ");


int x = [Link]();
[Link]("Type the second integer: ");
int y = [Link]();
int sum = x + y;
[Link]("Their sum is " + sum);
}
}

Compiled_by_Tronic_636
Example
import [Link];

public class AddTwo{


public static void main(String[] args){
Scanner in = new Scanner([Link]);

[Link]("Type the first integer: ");


int x = [Link]();
[Link]("Type the > javainteger:
second AddTwo ");
int y = [Link](); Type the first integer: 7
int sum = x + y; Type the second integer: 5
[Link]("Their sum is " sum
Their + sum);
is 12
}
}
>

Compiled_by_Tronic_636
Example: Avarage
• Read a stream of numbers
• Compute their average

Compiled_by_Tronic_636
import [Link];

public class Average{


public static void main(String[] args){
Scanner in = new Scanner([Link]);
double sum = 0.0; // cumulative total
int n = 0; // number of values

while ([Link]()){
double x = [Link]();
sum = sum + x;
n++;
}

[Link](sum / n);
}
} Compiled_by_Tronic_636
Example: generate a stream of random numbers

public class RandomSeq{


public static void main(String[] args){
int N = [Link](args[0]);

for (int i = 0; i < N; i++)


[Link]([Link]());
}
}

Compiled_by_Tronic_636
Transferring output to input
Command-line arguments

Standard input stream

• Use external text file


RandomSeq Average • Use pipes

Standard output stream

Standard output stream

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

>

Standard output stream [Link] Average


RandomSeq

Standard input stream

Compiled_by_Tronic_636
Transferring through piping
>java RandomSeq 1000000 | java Average Set up a pipe
0.4999720048023056

>java RandomSeq 1000000 | java Average


0.500284756393421 No limit to the amount of
data transferred
>

RandomSeq Standard output stream Average


Standard input stream

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

while ([Link](t - c/t) > eps * t)


t = (c/t + t) / 2.0;
Return
return t; statement
}

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

public static void main(String[] args){


Scope of a double[] a = new double[[Link]];
for (int i = 0; i < [Link]; i++) Two different
Scope of i a[i] = [Link](args[i]); variables. The scope
of each i is limited to
block of the for-loop.
for (int i = 0; i < [Link]; i++)
Scope of i [Link](sqrt(a[i], 1e-3));
}
}
Compiled_by_Tronic_636
public class Newton{
public static double sqrt(double c, double eps){
if (c < 0)
return [Link];
double t = c;
while ([Link](t - c/t) > eps * t)
t = (c/t + t) / 2.0;
return t; c initializes to the value of a[i]
} and eps initializes to 1e-3

public static void main(String[] args){


double[] a = new double[[Link]];
for (int i = 0; i < [Link]; i++)
a[i] = [Link](args[i]);
for (int i = 0; i < [Link]; i++){
double x = sqrt(a[i], 1e-3);
[Link](x);
} the retun value replaces the function name in
} the calling statement
}
Compiled_by_Tronic_636
What does the following code do?
public class PQfunctions1a{
public static int cube(int i){
int j = i * i * i;
return j;
}

public static void main(String[] args){


int N = [Link](args[0]);
for (int i = 1; i <= N; i++)
[Link](i + " " + cube(i));
}
}
Compiled_by_Tronic_636
What does the following code do?
> javac [Link]
public class PQfunctions1a{
public static int cube(int i){> java PQfunctions1a 5
int j = i * i * i; 1 1
return j; 2 8
} 3 27
4 64
public static void main(String[]
5 125args){
int N = [Link](args[0]);
for (int i = 1; i <= N; >i++)
[Link](i + " " + cube(i));
}
}
Compiled_by_Tronic_636
What does the following code do?
public class PQfunctions1b{
public static int cube(int i){
int i = i * i * i;
return i;
}

public static void main(String[] args){


int N = [Link](args[0]);

for (int i = 1; i <= N; i++)


[Link](i + " " + cube(i));
}
}
Compiled_by_Tronic_636
What does the following code do?
public class PQfunctions1b{
public static int cube(int i){
int i = i * i * i; argument variable i is still in
return i; scope. Cannot reuse
}

public static void [Link]


> javac main(String[] args){
int [Link][Link]
= [Link](args[0]);
i is already defined
in cube(int)
for (int
int ii == i1;* ii <= N; i++)
* i;
^[Link](i + " " + cube(i));
} 1 error
}
Compiled_by_Tronic_636
What does the following code do?
public class PQfunctions1c{
public static int cube(int i){
i = i * i * i;
}

public static void main(String[] args){


int N = [Link](args[0]);

for (int i = 1; i <= N; i++)


[Link](i + " " + cube(i));
}
}
Compiled_by_Tronic_636
What does the following code do?
public class PQfunctions1c{
public static int cube(int i){
i = i * i * i; Compile error. Missing return
} statement

public static void main(String[] args){


> javac [Link]
int N = [Link](args[0]);
[Link][Link] missing
for (int i = 1;return statement
i <= N; i++)
}
[Link](i + " " + cube(i));
} ^
} 1 error

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

public static void main(String[] args){


int N = [Link](args[0]);

for (int i = 1; i <= N; i++)


[Link](i + " " + cube(i));
}
}
Compiled_by_Tronic_636
What does the following code do?
public class PQfunctions1d{
public static int cube(int i){
i = i * i * i; Works. BUT changing argument values is bad
programming practice as it results in confusing
return i; code.
}
> javac [Link]
public static void main(String[] args){
> java PQfunctions1d 5
int N = [Link](args[0]);
1 1
for (int i = 1; 2i 8<= N; i++)
3 27
[Link](i + " " + cube(i));
} 4 64
} 5 125
Compiled_by_Tronic_636
What does the following code do?
public class PQfunctions1e{
public static int cube(int i){
return i * i * i;
}

public static void main(String[] args){


int N = [Link](args[0]);

for (int i = 1; i <= N; i++)


[Link](i + " " + cube(i));
}
}
Compiled_by_Tronic_636
What does the following code do?
public class PQfunctions1e{
public static int cube(int i){
return i * i * i; Works. Compact code.
}

> javac [Link]


public static void main(String[] args){
int N = [Link](args[0]);
> java PQfunctions1d 5
for (int i = 1; 1i 1<= N; i++)
2 8
[Link](i + " " + cube(i));
} 3 27
} 4 64
5 125
Compiled_by_Tronic_636
Trace c1
1
x
2
c4
4
c3
3
c2
2

public class SomeFn{


public static int fn(int i, int a, int b, int c,
int d){
return a * i * i * i + b * i * i + c * i + d;
}

public static void main(String[] args){


int c1 = 1, c2 = 2, c3 = 3, c4 = 4, x = 2;
int n = fn(x, c1, c2, c3, c4);
[Link](n);
}
}
Compiled_by_Tronic_636
Trace c1
1
x
2
c4
4
c3
3
c2
2

public class SomeFn{


public static int fn(int i, int a, int b, int c,
int d){
return a * i * i * i + b * i * i + c * i + d;
}

public static void main(String[] args){


int c1 = 1, c2 = 2, c3 = 3, c4 = 4, x = 2;
int n = fn(x, c1, c2, c3, c4);
[Link](n);
}
}
Compiled_by_Tronic_636
Trace c1
1
x
2
a
1
c4
4
c3
3
i
2
d
4
c2
2
b
2
c
3

public class SomeFn{


public static int fn(int i, int a, int b, int c,
int d){
return a * i * i * i + b * i * i + c * i + d;
}

public static void main(String[] args){


int c1 = 1, c2 = 2, c3 = 3, c4 = 4, x = 2;
int n = fn(x, c1, c2, c3, c4);
[Link](n);
}
}
Compiled_by_Tronic_636
Trace c1
1
x
2
a
1
c4
4
c3
3
i
2
d
4
c2
2
b
2
c
3

public class SomeFn{


public static int fn(int i, int a, int b, int c,
int d){
return a * i * i * i + b * i * i + c * i + d;
}

public static void main(String[] args){


int c1 = 1, c2 = 2, c3 = 3, c4 = 4, x = 2;
int n = fn(x, c1, c2, c3, c4);
[Link](n);
}
}
Compiled_by_Tronic_636
Trace c1
1
x
2
N
26
c4
4
c3
3
c2
2

public class SomeFn{


public static int fn(int i, int a, int b, int c,
int d){
return a * i * i * i + b * i * i + c * i + d;
}

public static void main(String[] args){


int c1 = 1, c2 = 2, c3 = 3, c4 = 4, x = 2;
int n = fn(x, c1, c2, c3, c4);
[Link](n);
}
}
Compiled_by_Tronic_636

You might also like