# else if

Document Sample

```					    Operators

• Arithmetic operators:
+            -        /    *         %
• Relational operators:
==           >    <   <=      >=     !=
• Logical operators:
||               &&        !

11/18/2012                 ITK 275        1
Logical Operators              || &&          !
Assume x = 10
(1 || 0)    true
((18 <= x) && (x <= 50))       false

((18 <= x) || (x <= 50))        true

!(x < 5)    is same as       (x >= 5)   true
(((x % 2) == 0) && ((x % 3) == 0))      false

11/18/2012                  ITK 275                      2
De Morgan’s law
I am not a female student.
 I am not female or I am not a student.

!(A && B)             is same as             !A || !B

I will not be in my office or in the lab.
 I will not be in my office and will not be in the lab.

!(A || B)              is same as             !A && !B

11/18/2012                   ITK 275                           3
Branching

T   Statement
T   Statement
Condition                                Condition
list 1
list
F
F

Statement
list 2

11/18/2012                    ITK 275                          4
The Syntax of if and if-else statements
A Boolean expression (logical
expression). In Java, there are two
Reserved words               if ( condition )            possible values: true and false.
{
statement list;
A reserved word             }
can’t be used as an
identifier

if ( condition )
{
statement list1;
}
else
{
statement list2;
}

Indentation indicates that the statements in the statement
list are at the level next to the if-else statement.
11/18/2012                             ITK 275                                  5
Nested if/else statement
if ( condition 1 )
{
if ( condition 2 )
{
statement list;

}
else
{
statement list;
};
statement list;
}
else
{
statement list;
}

Indentation indicates the level of statements.
11/18/2012                                ITK 275             6
Disney
Roller Coaster Ride          Measure the
kid’s height, h

h<4            No

Yes

Ride the
boy         Boy or        girl        roller coaster
Girl?

Give a Mickey                 Give a Mini

Next Stop
11/18/2012                     ITK 275                                7
Disney Ride in Program – OK

n = Integer.parseInt(
JOptionPane.showInputDialog(“How tall is the kid?”));
// IsBoy = true or false;

if (h < 4)
if (IsBoy)
System.out.println(“Take a Mickey”);
else
System.out.println(“Take a Mini.”);
else
System.out.println(“You can ride!!”);

System.out.println(“Go to the next stop.”);

but not really a good idea;
put { } to improve readability
11/18/2012                  ITK 275                            8
Ambiguity
I saw the little girl with a
binocular on the mountain top.

I saw the little girl with a
binocular on the mountain top.

I saw the little girl with a
binocular on the mountain top.

I saw the little girl with a
binocular on the mountain top.
11/18/2012                ITK 275                     9
Rule: else belongs to the nearest if that not yet has an else

if (condition1)
if (condition2)
{
.....;             Indentation can’t
.....;             help compiler
}
else // not a kid
{
.....;
.....;
}

11/18/2012                 ITK 275                       10
Boy Scout:

Yes                  No
Is a kid?

Is a                              Parent?
boy?      No                 No
Yes                                Yes

Give a badge                         Give a guidebook

Welcome

11/18/2012                      ITK 275                      11
Boy Scout: in program

if (IsKid)
{
if (IsBoy)
{
}
}
else // not a kid
{
if (IsParent)
{
System.out.println(“Take a Guidebook”);
}
}
System.out.println(“Welcome, everybody!.”);

11/18/2012                       ITK 275                    12
if (IsKid)                     Boy Scout: wrong program
if (IsBoy)
else // not a kid
if (IsParent)
System.out.println(“Take a Guidebook”);
System.out.println(“Welcome, everybody!.”);

if (IsKid)
{
if (IsBoy)
{
}
else // not a boy
{
if (IsParent)
System.out.println(“Take a Guidebook”);
}
}
System.out.println(“Welcome, everybody!.”);

11/18/2012                   ITK 275                        13
Other forms of Nested if/else statements (Cascaded) I

if (condition_1)                    if (condition_1)
statement_1;                        statement_1;

if (condition_2)                    else if (condition_2)
statement_2;                        statement_2;

if (condition_3)
V.S.        else if (condition_3)
statement_3;                        statement_3;

if (condition_4)                    else if (condition_4)
statement_4;                        statement_4;

if (condition_5)                    else if (condition_5)
statement_5;                        statement_5;

11/18/2012                 ITK 275                           14
Another form of Nested if/else statement

if (points >= 650)

else if (points >= 500)
650 --     A               System.out.println(“B”);

else if (points >= 400)
500 -- 649    B               System.out.println(“C”);

else if (points >= 300)
400 -- 499    C               System.out.println(“D”);

300 -- 399    D         else
System.out.println(“F”);
0--299     F

11/18/2012             ITK 275                              15
Other forms of Nested if/else statements (Cascaded) II

if (condition_1)                     if (
if (condition_2)                         condition_1 &&
if (condition_3)                         condition_2 &&
if (condition_4)
statement_1;
=              condition_3 &&
condition_4
else                                     )
statement_2;                        statement_1;
else
statement_2;

11/18/2012                 ITK 275                        16

if (i == 1)                switch (i)
statement_1;           {
case 1: statement_1;
else if (i == 2)                      break;
statement_2;             case 2: statement_2;
break;
else if (i == 3)             case 3: statement_3;
statement_3;                      break;
case 4: statement_4;
else if (i == 4)                      break;
statement_4;             case 5: statement_5;
break;
else if (i == 5)             case 6: statement_6;
statement_5;                      break;
}
else if (i == 6)
statement_6;

11/18/2012                ITK 275                   17
if (i == 1)
statement_1;                 Switch vs.
else if (i == 2) {
statement_2;
statement_3;
}                     switch (i)
else if (i == 3)      {
statement_3;        case 1: statement_1;
break;
else if (i == 4) {      case 2: statement_2;
statement_4;        case 3: statement_3;
statement_5                  break;
statement_6         case 4: statement_4;
}                       case 5: statement_5;
else if (i == 5) {      case 6: statement_6;
statement_5;      }
statement_6;
}
else if (i == 6)
statement_6;
11/18/2012            ITK 275                      18
Definite Loops vs indefinite loops

• A definite loop is a loop that number of iterations is
known before the loop begins, at least the upper bound
is known.
I.e., repeat the loop 100 times.

• An indefinite loop is a loop that number of iterations is
not known before the loop begins, at least the upper
bound is known.
I.e., repeat the loop until some condition reached.

Precisely speaking, there is no definite loop in Java.

11/18/2012                  ITK 275                        19
while loop                                    for loop

T   Statement
Condition                                            <n   Statement
list         repeat n times
list
F
=n

while (Condition)
{                                     for (???;???;???)
Statement list                     {
}                                        Statement list
}

11/18/2012                   ITK 275                               20
The general format for a for loop
1                      2           3
for (Initialization_action; Condition; Condition_update)
{
statement_list;
}

Summation         1+2+3+...(n-1)+ n
int i, n, sum = 0;

n = Integer.parseInt(
JOptionPane.showInputDialog(“input n”));

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

System.out.println(“This answer is ” + sum);

11/18/2012                ITK 275                     21
1                  2              3
for (Initialization_action; Condition; Condition_update)
{
statement_list;
}

Factorial of n is   n(n-1)(n-2)...21
int n,f=1;

n = Integer.parseInt(
JOptionPane.showInputDialog(“input n”) );

if (n < 0) System.out.println(“No can do!!”);
else
for (i=2; i<=n; i++) {
f = f*i;
}

System.out.println(“This answer is ” + f);

11/18/2012                ITK 275                     22
while
while (Condition)
{
Statement list
}

T   Statement
Condition
list
F
while (Condition);
{
Statement list
}

11/18/2012                       ITK 275                        23
Compare for and while

int i;                           i=2;
while (i<=n)
for (i=2; i<=n; i++)             {
{                                   f *= i;
f *= i;                          i++;
}                                }

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

11/18/2012             ITK 275                  24
Another form of loop:       do loop

do
{
Statement                               Statement list
list                              } while (condition);

don’t forget “;” be careful
T          This is not uncommon
Condition

F

E.g., ITK’s student has to take ITK168
until he/she gets a C or better.

11/18/2012                    ITK 275                            25
Another example of using do-loop
Ask the user to input y (yes) or n (no), where y and n are the
only two valid inputs for the program to proceed. This way, we
avoid a great chance of accidentally pressing the keyboard.

do
{

{
}
11/18/2012               ITK 275                            26
Primality Test

A prime number is a positive integer that cannot be
factorized, i.e., no numbers other that 1 and itself
can divide it.

Is (893 % 2 == 0) ?
is 893 a prime?              Is (893 % 3 == 0) ?
Is (893 % 4 == 0) ?
This test is silly but        Is (893 % 5 == 0) ?
can do the job!               Is (893 % 6 == 0) ?
.
We can write a loop                     .
to test these.                          .
Is (893 % 892 == 0) ?

11/18/2012                  ITK 275                      27
Primality Test
int p,r,i; // r: remainder, i: factor
do {
p = Integer.parseInt(
JOptionPane.showInputDialog(“input an number:));
} while (p <= 1);

i=1;
do
{
i++;
r = p % i; // r is the remainder of p divided by i
} while (i < p && r != 0);

if (i == p)
System.out.println(“a prime number.”);
else
{
System.out.println(“not a prime number.”);
System.out.println(“The least factor is ”+i);
}

11/18/2012               ITK 275                         28
The break statement in a loop
Break a loop           will force the program to jump out
of the loop immediately.

int i = 2;                         int i = 2;
do                                 do
{                                  {
r = p % i;                         r = p % i;
i++;                               if (r == 0) break;
} while (i < p && r != 0);            i++;
} while (i < p);

11/18/2012                  ITK 275                       29
Break a loop
import javax.swing.JOptionPane;
....
....

do {
"Would you marry me? (y/n)");

"Really? (y/n)");

JOptionPane.showMessageDialog(null, "Great!!");
}

11/18/2012                     ITK 275                            30
break and continue

The break statement in a for/while loop will force the
program to jump out of the for/while loop immediately.

The continue statement in a for/while loop will force
the program to update the loop condition and then
check the condition immediately.

for (Initialization_action; Condition; Condition_update)
{
statement_list;
}

11/18/2012                ITK 275                      31
The Loops with multiple breaking points
....
....

while (......) {
....
if (....) break;
....
if (....) break;
T
Condition           Statement
....
if (....) break;                          list
....
if (....) break;        F
.....
.....
}
....
....                                    Spaghetti code?

Well, this is not spaghetti code!
11/18/2012                ITK 275                          32
The Loops with multiple breaking points

This is Spaghetti
code?

This is not spaghetti
code! All paths come
to the same point        Multiple-break-loop does not
cause the trouble as the
spaghetti code does

11/18/2012             ITK 275                         33
Euclid Algorithm

Public int GCD(int a, int b) {

int r = a % b;

while (r != 0)
{
a = b;
b = r;
r = a % b;
}
return (b);
}

11/18/2012                    ITK 275   34
My own square root function (incorrect my_sqrt)
double my_sqrt(double a)                                 up
{                                                   a
double up=a,down=0,st=a/2;

if (a < 0) return -1;
while (a - st*st != 0)
{                                                   guess st
if (st*st > a)
up = st;                                     real square
else
down = st;
root
st = (up+down)/2;
}                                               0      down
return st;
}

1. Where can I improve the program?
2. Where is the potential problem?

11/18/2012                     ITK 275                        35
My own square root function (incorrect my_sqrt)

double my_sqrt(double a)
{
double up=a,down=0,st=a/2,est;

if (a < 0) return -1;
est = st*st;

`while (a - est > 0.0000001)
{
if (est > a)
up = st;
else
down = st;
st = (up+down)/2;
est = st*st;
}                              Any problem? What is it?
return st;
}

11/18/2012                      ITK 275                         36
My own square root function (incorrect my_sqrt)

double my_sqrt(double a)
{
double up=a,down=0,st=a/2,est;

if (a < 0) return -1;
est = st*st;
while ((a - est > 0.0000001)||(a - est < -0.0000001))
{
if (est > a)
up = st;
else
down = st;
st = (up+down)/2;     Still wrong!!
est = st*st;
}                          What is the roblem?
return st;
}

11/18/2012                     ITK 275                          37
My own square root function (my_sqrt)
double my_sqrt(double a)
{
double up,down,st,est;
if (a < 0) return -1;
if ( a >= 1)
{ up=a; down=0;}
else
{ up=1; down=a;}
st = (up+down)/2;
est = st*st;
while ((a - est > 0.0000001) || (a - est < -0.0000001))
{
if (est > a)
up = st;
else
down = st;
st = (up+down)/2;
est = st*st;
}
return st;
}

11/18/2012                  ITK 275                         38
Nested loops (loop in loop)
int a = Integer.parseInt(
JOptionPane.showInputDialog(“input a:”);
int b = Integer.parseInt(
JOptionPane.showInputDialog(“input b:”);

for (int i = 0; i < a; i++)
{                                            b
for (int j=0; j<b; j++)
{                              *************
System.out.print(“*”);     a *************
}                              *************
System.out.print(“\n”);        *************
}

11/18/2012             ITK 275                  39
Nested loops (2)
int a = Integer.parseInt(
JOptionPane.showInputDialog(“input a:”);
int b = Integer.parseInt(
JOptionPane.showInputDialog(“input b:”);

for (int i = 0; i < a; i++)                   b
{
for (int j=0; j<b; j++)
*
{                                  a **
if (j > i)                         ***
break;                           ****
System.out.print(“*”);
}
System.out.print(“\n”);
}

11/18/2012             ITK 275                   40
Java Blocks
• In Java and other C-like languages:
a compound statement using { and }
• A compound statement also serves as a block:

while (i < 0) {          for (int i=0;i<0; i++) {
int c = i*i*i;           int c = i*i*i;
p += c;                  p += c;
q += c;                  q += c;
i -= step;               i -= step;
}                        }

11/18/2012              ITK 327                   41
Can we do this?               Yes!
{
for (int i=0; i<n; i++)
{
....
....
....                     Scope of red i
....
}

int i=2;

Scope of blue i
}

11/18/2012                         ITK 275            42
Can we do this?           No!
{
for (int i=0; i<n; i++)
{
....
....
....                             Scope of red i
....
}

i=2;                      blue i is undefined

}

11/18/2012                       ITK 275                         43
Can we do this?           No!
{
int i=2;
for (int i=0; i<n; i++)
{
....
....
....
....
}

Scope of blue i
}

11/18/2012                       ITK 275            44

```
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
 views: 5 posted: 11/18/2012 language: Latin pages: 44