Lecture 2
Lecture 2
Java Programming
Sun Club, IITK
Day-2
Acknowledgement
Club’s website
http://www.cse.iitk.ac.in/users/sun
Club’s wiki
http://web.cse.iitk.ac.in/~sun/dokuwiki
Revision !
4
Operator precedence
5
Operator precedence
6
Default initial values
7
Questions ? Doubts ?
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 ?
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
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
34
Infinite loops
do {
statements
} while (true);
35
Infinite loops
for (expression1; ;expression2) {
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
38
break
39
Questions ?
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 ?
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
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 ?
68
Methods in problem solving
69
Return and parameter type
70
PrintMyName
• class anExample {
• public static void main (String arg[]) {
• PrintMyName(); // Method call
• }
71
Method parameters
• Methods can have parameters also
Just like functions
• class anExample {
• public static void main (String arg[]) {
• String myName = “Tintin”;
• PrintMyName(myName);
• }
72
Method parameters
• class moreExample {
• public static void main (String arg[]) {
• int n = 5;
• double x = 4.6;
• ComputeExponent(x, n);
• }
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
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
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
80
More examples
81
More examples
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
84
Checking character case
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
87
Questions ?
• 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;
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;
93
Which one is bigger?
• class whichOneIsBigger{
• public static void main(String arg[]){
• double x = Math.PI;
• double y = Math.E;
• double 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 ?
97
Sum of natural numbers
98
GCD revisited
99
GCD revisited
100
Towers of Hanoi
101
Towers of Hanoi
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
105
Fibonacci series
106
Questions ?
• Thank You