0% found this document useful (0 votes)
23 views108 pages

Lecture 2

The document provides an introduction to loops in Java programming. It discusses while, do-while, and for loops. The while loop executes statements repeatedly as long as a condition is true. The do-while loop executes statements at least once before checking the condition. For loops allow iterating over a range by specifying an initialization, condition, and increment expression. Examples are provided to illustrate calculating sums and converting numbers between bases using loops.

Uploaded by

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

Lecture 2

The document provides an introduction to loops in Java programming. It discusses while, do-while, and for loops. The while loop executes statements repeatedly as long as a condition is true. The do-while loop executes statements at least once before checking the condition. For loops allow iterating over a range by specifying an initialization, condition, and increment expression. Examples are provided to illustrate calculating sums and converting numbers between bases using loops.

Uploaded by

it.krunalpatel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 108

Introduction to

Java Programming
Sun Club, IITK

Day-2
Acknowledgement

• Thanks to Dr. Mainak Chaudhuri, Instructor,


ESC101N for helping us with the content of the
presentation.
Sun Club ?

• This presentation will be shared at


http://groups.google.com/group/jug_sunclub

Club’s website
http://www.cse.iitk.ac.in/users/sun

Club’s wiki
http://web.cse.iitk.ac.in/~sun/dokuwiki
Revision !

Operators and Expressions:


Wrap up

4
Operator precedence

• Higher to lower precedence


 ++, -- (both post and pre) unary
 !, +, - (logical NOT, unary +, unary -) unary
 *, /, % (multiply, divide, mod) binary
 +, - (add, subtract) binary
 <, <=, >, >= (LT, LE, GT, GE) binary
 ==, != (equality and non-equality) binary
 && (logical AND) binary
 || (logical OR) binary
= (assignment) binary

5
Operator precedence

• What is the answer? (assume x=1)


• x*x+x%2
• 2*x/2%4 (need to know associativity)
• Almost all operators are left associative
 This indicates in which direction the operators of
the same precedence will evaluate
 Assignment has right associativity
 x=y=2; // assigns y=2 first and then x=y
 The above expression would lead to wrong
answer if assignment was left associative

6
Default initial values

• Every declared variable gets a pre-defined


default initial value in Java
 Not true for many other languages
 All primitive types get a zero value (boolean gets
false)
 You should not rely on this in your programs
even if the compiler allows you to do so
• Never use uninitialized variables in a program

7
Questions ? Doubts ?

• Let’s move on to a very important topic


“Conditionals”
if statement
if (condition) {
statements
}
Nested if
if (condition1) {
statements1
if (condition2) {
statements2
}
statements3
}

9
Nested if
Sometimes possible to simplify nested if
if (condition1) {
if (condition2) {
statements
}
}
Same as
if ((condition1) && (condition2)) {
statements
}

10
Example
class exampleIf {
public static void main(String arg[]) {
int x=10, y, z;
if ((x%2)==0) {
System.out.println(x + “ is even.”);
if ((x%3)==0) {
System.out.println(x + “ is a multiple of 6.”);
y = x/6;
}
z = x%6;
}
}
}

11
if-else
if (condition) {
statements1
}
else {
statements2
}
if within else
if (condition1) { statements1 }
else {
if (condition2) { statements2 }
statements3
}

12
if-else if-else if-…-else
if (condition1) {
statements1
}
else if (condition2) {
statements2
}
else if (condition3) {
statements3
}

else {
statementsn
}

13
Example
class greetings {
public static void main(String arg[]) {
int hour = 3;
if ((hour >= 0) && (hour < 12)) {
System.out.println(“Good Morning!”);
}
else if ((hour >= 12) && (hour < 18)) {
System.out.println(“Good Afternoon!”);
}
else if ((hour >=18) && (hour < 24)) {
System.out.println(“Good Evening!”);
}
else {
System.out.println(“Bad time!”);
}
}
}

14
Conditional assignment

if ((x%2)==0) {
y = x/2;
}
else {
y = (x+1)/2;
}
Same as
y = ((x%2)==0) ? x/2 : (x+1)/2;

15
Integer part and absolute value
class integerPart {
public static void main(String arg[]) {
double x = -3.7;
int ipart;
double aval;
ipart = ((x >= 0) || ((int)x==x)) ? (int)x : (int)(x-1);
aval = (x >= 0) ? x : -x;
System.out.println(“Integer part of ” + x + “ is ” + ipart +
“. Absolute value is ” + aval + “.”);
}
}

16
Integer part and absolute value
class integerPartAlternate {
public static void main(String arg[]) {
double x = -3.7;
int ipart;
double aval;
ipart = ((x < 0) && ((int)x!=x)) ? (int)(x-1) : (int)x;
aval = (x < 0) ? -x : x;
System.out.println(“Integer part of ” + x + “ is ” + ipart +
“. Absolute value is ” + aval + “.”);
}
}

17
Sorting three numbers
class sortThree {
public static void main(String arg[]) {
int x = 2, y = 5, z = 1;
int max, mid, min;
if ((x > y) && (x > z)) {
max = x;
if (y > z) {
mid = y;
min = z;
}
else {
mid = z;
min = y;
}
}
// next slide

18
Sorting three numbers
else {
if (y > z) {
max = y;
if (x > z) {
mid = x;
min = z;
}
else {
mid = z;
min = x;
}
}
else { // the remaining two permutations}
} // end else
} // end main
} // end class

19
Questions ?

• Let’s move to the next topic “Iteration”


Loops

• Needed in problems that require solving the


same subproblem over and over
 Computing the sum of the first 100 natural
numbers and putting the result in y
 Algorithm:
 y = 1;
 y = y + 2;
 y = y + 3;
…
 y = y + 100;
 Cannot write 99 such additions: use a loop

21
while

while (condition) {
statements
}
• Can put anything in “statements”
 The entire construct is called a while loop
 statements are executed until condition is true
 Even before executing it the first time condition is
evaluated
• A while loop may not execute even once

22
Example
class justAnExample {
public static void main(String arg[]) {
int x = 5;
int y = 0;
while (x < 10) {
y--;
x++;
}
System.out.println(y);
}
}

23
Example
class justAnExample {
public static void main(String arg[]) {
int x = 15;
int y = 0;
while (x < 10) {
y--;
x++;
}
System.out.println(y);
}
}

24
Sum of natural numbers
class naturalSum {
public static void main(String arg[]) {
int n = 2;
int y = 1;
while (n <= 100) {
y += n;
n++;
}
System.out.println(“Sum of the first ” + (n-1) + “ natural
numbers is ” + y);
}
}

25
Sum of natural numbers
class naturalSumAnotherWay {
public static void main(String arg[]) {
int n = 99;
int m = n+1;
int y = 100;
while (n > 0) {
y += n;
n--;
}
System.out.println(“Sum of the first ” + m + “ natural numbers is ” +
y)
}
}

26
Integer index
class integerIndex {
public static void main(String arg[]) {
int n = 3;
double x = 3.14, y = 1.0;
int m = n;
if (n < 0) {
x = 1/x;
m = -n;
}
while (m > 0) {
y *= x;
m--;
}
System.out.println(x + “ to the power ” + n + “ is ” + y);
}
}

27
Positive Decimal to Binary
class positiveDecimalToBinary {
public static void main(String arg[]) {
int n = 34, y=0, polyTerm = 1;
if (n < 0) {
System.out.println(“Sorry, cannot handle negative integers today!”);
}
else {
while (n > 0) {
y += (polyTerm*(n%2));
n /= 2;
polyTerm *= 10;
}
System.out.println(“Required binary: ” + y);
}
}
}

28
do-while

do {
statements
} while (condition);
“statements” execute at least once irrespective of
condition

29
for loops

for (expression1; condition; expression2) {


statements
}
Same as
expression1
while (condition) {
statements
expression2
}

30
Sum of natural numbers
class naturalSum {
public static void main(String arg[]) {
int n;
int y = 1;
for (n=2; n <=100; n++) {
y += n;
}
System.out.println(“Sum of the first ” + (n-1) + “ natural
numbers is ” + y);
}
}

31
Comma operator in for loop
for (expression1a, expression2a, …; condition; expression1b,
expression2b,…) {
statements
}
Same as
expression1a
expression2a …
while (condition) {
statements
expression1b
expression2b …
}

32
Sum of natural numbers

class naturalSum {
public static void main(String arg[]) {
int n;
int y;
for (n=2, y=1; n <=100; y += n, n++) { }
System.out.println(“Sum of the first ” + (n-1)
+ “ natural numbers is ” + y);
}
}

33
Empty for loop body

for (expression1; condition; expression2) {


}
• Same as
for (expression1; condition; expression2);

34
Infinite loops

• Loops that never terminate


while (true) {
statements
}

do {
statements
} while (true);

35
Infinite loops
for (expression1; ;expression2) {
statements
}

for (i=0; i > -10; i++) {


statements
}

for (i=0; i<=100; i--) {


statements
}

36
Perfect squares
class identifySquareButLessClever {
public static void main (String arg[]) {
int n = 48;
int i;
if (n < 0) {
System.out.println (n + “ is not a perfect square.”);
}
else if ((n==0) || (n==1)) {
System.out.println (n + “ is a perfect square.”);
}
else {
for (i=2; i<=n/2; i++) {
if ((i*i) == n) {
System.out.println(n + “ is square of ” + i);
}
}
}
}
}

37
break

• In the last example you may want to come out of the


for loop as soon as you discover that n is a square
 The computation done after this is useless
 Use break
 Breaks out of the loop (while, do-while, or for)
currently you are in
for (i=2; i<=n/2; i++) {
if ((i*i)==n) {
System.out.println(n + “ is square of ” + i);
break;
}
}

38
break

• Another way to achieve the same effect without


using break
for (i=2; (i<=n/2) && ((i*i) <= n); i++) {
if ((i*i)==n) {
System.out.println(n + “ is square of ” + i);
}
}

39
Questions ?

• Let’s proceed with more examples !


Primality testing
class primalityTestSlow {
public static void main (String arg[]) {
int n = 42, d;
if (n <= 1) {
System.out.println(n + “ is not a prime.”);
}
else {
for (d=2; d<=n/2; d++) {
if ((n%d)==0) {
System.out.println(n + “ is not a prime.”);
break;
}
}
if (d > n/2) {
System.out.println(n + “ is a prime.”);
}
}}}

41
Primality testing
class primalityTestLittleBetter {
public static void main (String arg[]) {
int n = 42, d;
if (n <= 1) {
System.out.println(n + “ is not a prime.”);
}
else {
for (d=2; d*d<=n; d++) {
if ((n%d)==0) {
System.out.println(n + “ is not a prime.”);
break;
}
}
if (d*d > n) {
System.out.println(n + “ is a prime.”);
}
}}}

42
continue
Allows you to skip parts of a for or while or do-while loop
statements
Example (want to print two-digit numbers with both digits odd)
for (i=10; i<100; i++) {
if ((i%2)==0) {
continue;
}
if (((i/10)%2)==1) {
System.out.println(i + “ has odd digits.”);
}
}

43
Perfect numbers
class perfectNumber {
public static void main (String arg[]) {
int n = 24;
int d, sigma_n = 1+n;
for (d=2; d<=n/2; d++) {
if ((n%d) != 0) {
continue;
}
sigma_n += d;
}
if (sigma_n == 2*n) {
System.out.println (n + “ is perfect.”);
}
}
}

44
Questions ?

• More on conditionals and loops


switch-case
An alternative of if-else if-…-else
switch (expression) {
case constant1: // integer or character
statements1
case constant2:
statements2

case constantN:
statementsN
default:
statementsD
}

46
switch-case
Same as
if (expression==constant1) {
statements1
statements2

statementsN
statementsD
}
else if (expression==constant2) {
statements2
statements3

statementsN
statementsD
}
// continued on next slide

47
switch-case
else if (expression==constant3) {
statements3
statements4

statementsN
statementsD
}

else if (expression==constantN) {
statementsN
statementsD
}
else {
statementsD
}

48
switch-case with break
switch (expression) {
case constant1:
statements1
break;
case constant2:
statements2
break;

case constantN:
statementsN
break;
default:
statementsD
break;
}

49
switch-case with break
Same as
if (expression==constant1) {
statements1
}
else if (expression==constant2) {
statements2
}

else if (expression==constantN) {
statementsN
}
else {
statementsD
}

50
switch-case: more flavors
switch (expression) {
case constant1:
case constant2:
statements1
break;
case constant3:
statements3
break;

case constantN:
statementsN
break;
default:
statementsD
break;
}

51
switch-case: more flavors
Same as
if ((expression==constant1) || (expression==constant2)) {
statements1
}
else if (expression==constant3) {
statements3
}

else if (expression==constantN) {
statementsN
}
else {
statementsD
}

52
Classification of numbers
class classifyNumbers {
public static void main (String arg[]) {
int n = 8;
switch (n) {
case 0 :
System.out.println(“Zero!”);
break;
case 1 :
System.out.println(“Smallest positive!”);
break;
case 2 :
System.out.println(“Smallest prime!”);
break;
// continued in next slide

53
Classification of numbers
case 3 :
System.out.println(“Smallest odd prime!”);
break;
case 4 :
System.out.println(“Smallest prime squared!”);
break;
case 5 :
System.out.println(“Number of fingers!”);
break;
case 6 :
System.out.println(“Smallest perfect!”);
break;
// continued in next slide

54
Classification of numbers
case 7 :
System.out.println(“North seven stars!”);
break;
case 8 :
System.out.println(“Smallest prime cubed!”);
break;
case 9 :
System.out.println(“Smallest odd prime squared!”);
break;
default :
System.out.println(“Not a digit!”);
break;
} // end of switch
} // end of main
} // end of class

55
More classification
class differentClassification {
public static void main (String arg[]) {
int n = 8;
switch (n) {
case 2:
case 3:
case 5:
case 7:
System.out.println(“Prime!”);
break;
case 1:
case 4:
case 9:
System.out.println(“Square!”);
break;
// continued in next slide

56
More classification

case 6:
System.out.println(“Perfect!”);
break;
case 8:
System.out.println(“Cube!”);
break;
case 0:
System.out.println(“Zero the Great!”);
break;
default:
System.out.println(“Not a digit!”);
break;
} // end switch
} // end main
} // end class

57
More example of switch
class rainbow {
public static void main (String arg[]) {
char c = ‘V’;
switch (c) {
case ‘V’ :
case ‘v’ :
System.out.println (“Violet”);
break;
case ‘I’ :
case ‘i’ :
System.out.println (“Indigo”);
break;
case ‘B’ :
case ‘b’ :
System.out.println (“Blue”);
break;

58
More example of switch

case ‘G’ :

case ‘g’ :
System.out.println (“Green”);
break;
case ‘Y’:
case ‘y’ :
System.out.println (“Yellow”);
break;
case ‘O’ :
case ‘o’ :
System.out.println (“Orange”);
break;
case ‘R’ :
case ‘r’ :
System.out.println (“Red”);
break;
// continued in next slide

59
More example of switch

default :
System.out.println (“You are not in
rainbow!”);
break;
}
}
}

60
Nested loops
• Loop within loop
for (i=0; i<=100; i++) {
for (j=0; j<=100; j++) {
System.out.println (i+j);
}
}
• Number of loops is called the depth of the nest
• The innermost loop executes most frequently
• The outermost loop executes least
• You can nest while loops within for loops and vice-versa
• Loop variables should be different for different loops e.g., i and j
in this case (what happens if both are i ?)

61
Nested loops
for (i1=p1; i1<q1; i1++) {// outermost
statements1 // can be empty
for (i2=p2; i2<q2; i2++) {
statements2 // can be empty
for (i3=p3; i3<q3; i3++) {
statements3 // can be empty

for (iN=pN; iN<qN; iN++) { // innermost
statementsN
}

}
}
} // How many times does statementsK execute?

62
All perfect numbers
class allPerfectNumbersUptoOneLakh {
public static void main (String arg[]) {
int n, d, sigma_n;
for (n=2; n<=100000; n++) {
sigma_n = 1+n;
for (d=2; d<=n/2; d++) {
if ((n%d)==0) {
sigma_n += d;
}
}
if (sigma_n == 2*n) {
System.out.println (n + “is perfect.”);
}
}
}
}

63
Euclid’s division algorithm

• A fast way to compute the greatest common


divisor of two numbers a and b
• Algorithm (this is not a program)
• Divide b by a, assign a to b and the remainder
to a; loop until a is zero. The value of b at this
point is the gcd.
• Assumes a is less than b
• Main observation: gcd (a, b) = gcd (a, b-a)

64
GCD
class gcd {
public static void main (String arg[]) {
int a = 40, b = 24, r, gcd;
if ((a==0) || (b==0)) {
gcd = (a > b) ? a : b;
}
else if (a < b) {
while (a!=0) {
r = b%a;
b = a;
a = r;
}
gcd = b;
}
// next slide

65
GCD
else {
while (b!=0) {
r = a%b;
a = b;
b = r;
}
gcd = a;
}
System.out.println(“GCD: ” + gcd);
}
}

66
Questions ?

• Let’s move on to the next topic “Methods”


Methods in problem solving

• Often we think of solving a large problem in parts


 Computing the number of digits in n! involves two
major steps: computing k=n! and computing the
number of digits in k
 So I can have two “procedures”, one computes n!
and the other computes the number of digits in it
 Such procedures are called methods
• These are just like functions
 A method may or may not produce a value
 The type of the produced value determines the
“return type” of a method

68
Methods in problem solving

• Methods are useful in carrying out similar type


of computation repeatedly
 Imagine evaluating a polynomial P (x, n) = a0 +
a1x + a2x2 + … + anxn for a particular pair (x0,
n0)
 It is enough to have a single method that takes
a, x and n as arguments or parameters and
computes the value of axn
 We repeatedly “call” this method to evaluate P
(x0, n0)
 Methods improve “modularity” of your program

69
Return and parameter type

• Can be int, float, String, double, char, or void


• We have seen one method so far: main
• It does not produce any value: void
• public static void PrintMyName () {
• System.out.println(“Tintin”);
• }
• Every method must be a part of a class

70
PrintMyName
• class anExample {
• public static void main (String arg[]) {
• PrintMyName(); // Method call
• }

• public static void PrintMyName () {


• // Method declaration
• System.out.println(“Tintin”);
• }
• }

71
Method parameters
• Methods can have parameters also
 Just like functions
• class anExample {
• public static void main (String arg[]) {
• String myName = “Tintin”;
• PrintMyName(myName);
• }

• public static void PrintMyName (String s) {


• System.out.println(s);
• }
• }

72
Method parameters
• class moreExample {
• public static void main (String arg[]) {
• int n = 5;
• double x = 4.6;
• ComputeExponent(x, n);
• }

• public static void ComputeExponent (double base, int index) {


• double y = 1.0;
• System.out.println(“Base: ” + base + “, index: ” + index);
• // continued in next slide

73
Method parameters
• if (index < 0) {
• base = 1/base;
• index = -index;
• }
• while (index > 0) {
• y *= base;
• index--;
• }
• System.out.println(“Required answer: ” + y);
• }
• }

74
Producing values and using them

• Methods can return values to the calling


method
 The calling method can use these values to
compute further
• Suppose we want to check if 2^x + 2^(2x+1) + 1
is a perfect square
 Involves two major procedures: computing 2x +
22x+1 + 1 and checking if it is a square

75
Example of method
• class exampleOfReturnValue {
• public static void main (String arg[]) {
• int x = 4, y = 1, z; // assume x is positive
• boolean isSquare;
• z = ComputePowerOfTwo(x);
• y += z;
• z = ComputePowerOfTwo(2*x+1); // Reuse
• y += z;
• isSquare = CheckSquare(y);
• if (isSquare) {
• System.out.println(“Expression is square for x = ” + x);
• }
• }

76
Example of method

• public static int ComputePowerOfTwo (int


index) {
• int y = 1; // This is a different y
• while (index > 0) {
• y *= 2;
• index--;
• }
• return y;
• }

77
Example of method
• public static boolean CheckSquare (int x) {
• int y; // This is another y
• for (y=0; y*y <= x; y++) {
• if (y*y == x) {
• return true;
• }
• }
• return false;
• }
• } // end class

78
More examples

• class Trigonometry {
• public static void main (String arg[]) {
• double error, x = 0.785; // quarter pi
• error = cos(x)*cos(x) + sin(x)*sin(x) – 1;
• System.out.println(“Error: ” + error);
• }
• // continued in next slide

79
More examples

• public static double cos (double theta) {


• return (1 – theta*theta/2 +
ComputeExponent(theta, 4)/factorial(4));
• }

• public static double sin (double theta) {


• return (theta – ComputeExponent(theta,
3)/factorial(3) + ComputeExponent(theta, 5)/
factorial(5));
• }

80
More examples

• public static double ComputeExponent (double a, int n) {


• double y = 1.0;
• if (n < 0) {
• a = 1/a;
• n = -n;
• }
• while (n > 0) {
• y *= a;
• n--;
• }
• return y;
• }

81
More examples

• public static int factorial (int n) {


• int y = 1;
• while (n > 1) {
• y *= n;
• n--;
• }
• return y;
• }
• } // end class Trigonometry

82
Checking character case
• class characterCase {
• public static void main (String arg[]) {
• char c = ‘A’;
• if (isUpperCase(c)) {
• System.out.println(c + “ is upper case.”);
• }
• else if (isLowerCase(c)) {
• System.out.println(c + “ is lower case.”);
• }
• else {
• System.out.println(c + “ is not in English alphabet.”);
• }
• }// continued in next slide

83
Checking character case

• public static boolean isUpperCase (char c) {


• return (isBetween(‘A’, c, ‘Z’));
• }

• public static boolean isLowerCase (char c) {


• return (isBetween(‘a’, c, ‘z’));
• }
• // continued in next slide

84
Checking character case

• public static boolean isBetween (char a, char


b, char c) {
• return ((a <= b) && (b <= c));
• }
• } // end class

85
Case conversion
• class convertCase {
• public static void main (String arg[]) {
• char c = ‘M’;
• System.out.println(“Original: ” + c);
• if (isBetween(‘A’, c, ‘Z’)) {
• System.out.println(“After conversion: ” + toLower(c));
• }
• else if (isBetween(‘a’, c, ‘z’)) {
• System.out.println(“After conversion: ” + toUpper(c));
• }
• else {
• System.out.println(“Cannot convert case!”);
• }
• } // continued in the next slide

86
Case conversion

• public static boolean isBetween (char a, char b, char c) {


• return ((a <= b) && (b <= c));
• }

• public static char toLower (char c) {


• return (c – ‘A’ + ‘a’);
• }

• public static char toUpper (char c) {
• return (c – ‘a’ + ‘A’);
• }
• } // end class

87
Questions ?

• Lets proceed with “Library methods”


Math library

• Math.sqrt (x)
 Takes double, returns double
• Math.pow (x, n)
 Takes two doubles, returns double
• Math.sin (x)
 Takes double, returns double
• Math.cos (x)
 Takes double, returns double
• Check out online Math library and other libraries

89
Roots of a quadratic
• class QuadraticSolver {
• public static void main (String arg[]) {
• double a=1.0, b=-2.0, c=1.0;
• double r1, r2;

• r1 = (-b+Math.sqrt(b*b-4*a*c))/(2*a);
• r2 = (-b-Math.sqrt(b*b-4*a*c))/(2*a);
• System.out.println(“Roots are: ” + r1 + “, ” + r2);
• }
• }

90
Velocity on inclined plane
• class velocityExample{
• public static void main(String arg[]){
• double theta=Math.PI/3.0;
• double g=9.81;
• double x=10;
• double velocity;
• velocity = Math.sqrt(2*g*Math.sin(theta)*x);
• System.out.println(“Final velocity: ” + velocity + “ m/s”);
• }
• }

91
Error in e^PI
• class errorE{
• public static void main(String arg[]){
• double x = Math.PI;
• double approx, error;

• approx = 1 + x + x*x/2 + Math.pow(x, 3)/6 + Math.pow(x,


4)/24;
• error = Math.exp(x) – approx;
• System.out.println(“Error up to fourth power: ” + error);
• }
• }

92
Sum of vectors
• class vectorSum{
• public static void main(String arg[]){
• double v1 = 10.0;
• double v2 = 21.2;
• double angle = 120; // In degrees
• double resultant;

• resultant = Math.sqrt(v1*v1 + v2*v2 -


2*v1*v2*Math.cos(angle*Math.PI/180.0));
• System.out.println(“Resultant of ” + v1 + “ and ” + v2 + “ at ” +
angle + “ degrees is ” + resultant);
• }
• }

93
Which one is bigger?
• class whichOneIsBigger{
• public static void main(String arg[]){
• double x = Math.PI;
• double y = Math.E;
• double difference;

• difference = Math.exp(x) – Math.pow(x, y);


• System.out.println(“Difference: ” + difference);
• }
• }

94
Adiabatic expansion
• class Adiabatic{
• public static void main(String arg[]){
• double P1 = 10;
• double P2 = 15.6;
• double V1 = 100;
• double V2;
• double gamma = 1.66;

• V2 = V1*Math.pow((P1/P2), 1.0/gamma);
• System.out.println(“New volume: ” + V2);
• }
• }

95
Questions ?

Let’s move on to the next topic “Recursion”


Sum of natural numbers
• class SumOfNaturalNumbers {
• public static void main (String arg[]) {
• int m = 3, n = 10;
• if (m > n) {
• System.out.println (“Invalid input!”);
• }
• else {
• System.out.println (“Sum of numbers from ” + m + “ to
” + n + “ is ” + Sum(m, n));
• }
• }

97
Sum of natural numbers

• public static int Sum (int m, int n) {


• int x, y;
• if (m==n) return m;
• x = Sum(m, (m+n)/2);
• y = Sum((m+n)/2+1, n);
• return (x+y);
• }
• } // end class

98
GCD revisited

• Recall that gcd (a, b) = gcd (a-b, b) assuming a >


b.
 Directly defines a recurrence

• public static int gcd (int a, int b) {


• if ((a==1) || (b==1)) return 1;
• if (a==b) return a;
• if (a < b) return gcd (a, b-a);
• if (a > b) return gcd (a-b, b);
• }

99
GCD revisited

• Refinement: gcd (a, b) = gcd (a-nb, b) for any


positive integer n such that a >= nb, in particular
n = a/b, assuming a > b

• public static int gcd (int a, int b) {


• if (0==a) return b;
• if (0==b) return a;
• if (a < b) return gcd (a, b%a);
• if (a > b) return gcd (a%b, b);
• }

100
Towers of Hanoi

• Three pegs, one with n disks of decreasing


diameter; two other pegs are empty
• Task: move all disks to the third peg under the
following constraints
 Can move only the topmost disk from one peg to
another in one step
 Cannot place a smaller disk below a larger one
• An example where recursion is much easier to
formulate than a loop-based solution

101
Towers of Hanoi

• We want to write a recursive method THanoi (n,


1, 2, 3) which moves n disks from peg 1 to peg
3 using peg 2 for intermediate transfers
• The first step is to formulate the algorithm
 Observation: THanoi (n, 1, 2, 3) Ξ THanoi (n-1,
1, 3, 2) followed by transferring the largest disk
to peg 3 from peg 1 and calling THanoi (n-1, 2,
1, 3)
 Stopping condition: n = 1

102
Towers of Hanoi

• class TowersOfHanoi {
• public static void main (String arg[]) {
• int n = 10;
• THanoi(n, 1, 2, 3);
• }

103
Towers of Hanoi

• public static void THanoi (int n, int source, int extra, int
destination) {
• if (n > 1) {
• THanoi (n-1, source, destination, extra);
• }
• System.out.println (“Move disk ” + n + “ from peg ” + source
+ “ to peg ” + destination);
• if (n > 1) {
• THanoi (n-1, extra, source, destination);
• }
• } // How many moves needed? 2n-1
• } // end class

104
Towers of Hanoi

• Total number of method calls


 Let Tn be the number of method calls to solve for
n disks
 Tn = 2Tn-1 + 1 for n > 1; T1 = 1
 Use generating function to solve the recurrence
(worked out in class on board)

105
Fibonacci series

• Number of method calls


 Refer to the program in the last lecture
 Let Tn be the number of method calls to find the
nth Fibonacci number
 Tn = Tn-1 + Tn-2 + 1 for n > 2; T1 = T2 = 1
 Use generating function to solve the recurrence
 Observe that Tn = 2Fn – 1 where Fn is the nth
Fibonacci number
 Tn = (21-n/√5)((1+√5)n – (1-√5)n) – 1
 The number (1+√5)/2 is called the golden ratio,
which is lim n →∞ (Fn+1/Fn)

106
Questions ?

• Let’s shoot some advanced topics


Hitlist 
• Arrays
• Class
• Interfaces
• Abstract Class
• You suggest something ?

• Thank You

You might also like