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);
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; }
break Another way to achieve the same effect without using break class identifySquare{ 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*i) != n); i++) ; if ((i*i)==n) { System.out.println(n + “ is square of ” + i);
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.”);
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.”);
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 }
switch-case Same as if (expression==constant1) { statements1 … statementsN statementsD } else if (expression==constant2) { statements3 // continued on next slide
switch-case else if (expression==constant3) { statements3 statements4 … statementsN statementsD } else if (expression==constantN) { else {
switch-case with break switch (expression) { case constant1: statements1 break; case constant2: statements2 … case constantN: statementsN default: statementsD }
switch-case with break Same as if (expression==constant1) { statements1 } else if (expression==constant2) { statements2 … else if (expression==constantN) { statementsN else { statementsD
switch-case: more flavors switch (expression) { case constant1: case constant2: statements1 break; case constant3: statements3 … case constantN: statementsN default: statementsD }
switch-case: more flavors Same as if ((expression==constant1) || (expression==constant2)) { statements1 } else if (expression==constant3) { statements3 … else if (expression==constantN) { statementsN else { statementsD