CS-121 Programming I

CS-121
Programming I
Dr. Nagia M. Ghanem
[email protected]
Topics
• What is flow of control
• Control Flow
– Conditional Statements
– Loops (next lectures)
• Reference
•
Java 2, the Complete Reference, 7th edition, Herbert Schildt, 2007, ISBN: 0-07-222420-7
– Chapter 5
2
What is Flow of Control
• Flow of control is the execution order of
instructions in a program
• All programs can be written with three control
flow elements
– Sequence - just go to the next instruction
– Branching or Selection - a choice of at least two
• either go to the next instruction
• or jump to some other instruction
– Loop or Repetition - a loop (repeat a block of code) ,
at the end of the loop
• either go back and repeat the block of code
• or continue with the next instruction after the block
3
Selection
• Conditional statements are executed only if a
condition is met
• The if statement
• The switch statement
4
The if statement
if (a>b)
Z = a;
• Evaluate condition
• if (a>b)
A>b
True
False
Z=a
• If true, evaluate inner statement
• Z = a;
• Otherwise, do nothing
5
The else keyword
if (a>b)
A>b
Z = a;
else
Z = b;
• Optional
True
Z=a
False
Z=b
• Execute statement if condition is false
Z = b;
• Either inner statement may be block
6
Blocks and compound statements
• A simple statement ends in a semicolon:
Z=foo(x+y);
• Consider the multiple statements:
temp = x+y;
Z=foo(temp);
• Curly braces – combine into compound statement/block
7
Blocks
• To group several statements together to form a
single statement
• Compiled as a single unit
• Variables can be declared inside
{
int temp = x+y;
z = foo(temp);
}
• Block can be empty {}
• No semicolon at end
8
Nested if
if (x>3)
if(x != 0)
System.out.println(“Hello from
2nd if”);
else
System.out.println(“Hello
from the else”);
System.out.println(“The end”);
if (x>3)
if(x != 0)
System.out.println(“Hello
from 2nd if”);
else
System.out.println(“Hello from
System.out.println(“The
the else”);
end”);
(dangling else)
• If x=2, what will be printed?
9
Nested if
if (x>3)
if(x != 0)
System.out.println(“Hello from
2nd if”);
else
System.out.println(“Hello
from the else”);
System.out.println(“The end”);
if (x>3)
if(x != 0)
System.out.println(“Hello
from 2nd if”);
else
System.out.println(“Hello from
System.out.println(“The
the else”);
end”);
• Indentation in first example is very confusing and misleading
• Second example is written with proper indentation
• This ambiguity is resolved by associating the else with the closest previous
else-less if.
• So, if x=2, the output will be:
The end
10
Nested if
if (x>3) {
if(x != 0)
System.out.println(“Hello from
2nd if”);
}
else
System.out.println(“Hello from
System.out.println(“The
the else”);
end”);
•So, if x=2, the output will be:
Hello from the else
The end
11
Comparing Values:
Relational Operators
• Relational operators compare values
Java
Math Notation
Description
>
>
Greater than
>=
≥
Greater than or equal
<
<
Less than
<=
≤
Less than or equal
==
=
Equal
!+
≠
Not equal
• The == denotes equality testing
a = 5; // Assign 5 to a
if (a == 5) . . . // Test whether a equals 5
12
Comparing Floating-Point Numbers
• Consider this code:
double r = Math.sqrt(2);
double d = r * r -2;
if (d == 0)
System.out.println("sqrt(2)squared minus 2 is 0");
else
System.out.println("sqrt(2)squared minus 2 is not 0 but " + d);
• It prints:
sqrt(2)squared minus 2 is not 0 but 4.440892098500626E-16
13
Comparing Floating-Point Numbers
• To avoid roundoff errors, don't use == to
compare floating-point numbers
• To compare floating-point numbers test
whether they are close enough: |x - y| ≤ ε
final double EPSILON = 1E-14;
if (Math.abs(x - y) <= EPSILON)
// x is approximately equal to y
ε is a small number such as 10-14
14
Comparing Strings
• Don't use == for strings!
if (input == "Y") // WRONG!!!
• Use equals method:
if (input.equals("Y"))
== tests identity, equals tests equal contents
• Case insensitive test ("Y" or "y")
if (input.equalsIgnoreCase("Y"))
Continued…
15
Comparing Strings
• s.compareTo(t) < 0 means s comes before t in
the dictionary
– "car" comes before "cargo"
• All uppercase letters come before lowercase:
"Hello" comes before "car"
16
Comparing Strings
• string1.compareTo(string2) < 0 means:
string1 comes before string2 in the dictionary
• string1.compareTo(string2) > 0 means:
string1 comes after string2
• string1.compareTo(string2) == 0 means:
string1 equals string2
• "car" comes before "cargo"
• All uppercase letters come before lowercase:
"Hello" comes before "car"
Lexicographic Comparison
Figure 3:
Lexicographic Comparison
18
Multiple If-then Statement
19
Example 1
Tax computations based on salary
if (net_income <= 15000)
tax_bill = 0;
else if (net_income <= 25000)
tax_bill=(0.05*(net_income-15000));
else
{
five_percent_tax = 0.05*10000;
ten_percent_tax = 0.10*(net_income-25000);
tax_bill = five_percent_tax + ten_percent_tax ;
}
•What would happen if we remove the first „else‟ ward?
20
The switch statement
• Instead of using multiple if-thenelse branches which test a single
value against several constants,
the switch statement can be used.
•
If one case branch matches, all
statements after it will be
executed. Use break to avoid this
•
otherwise, the statements after the
(optional) default: are executed.
switch (expression)
{
case const-expr: statement; break;
case const-expr : statement; break;
case const-expr : statement; break;
...
default: statement;
}
21
The switch statement - Example
switch(digit)
{
case 0: printf("zero\n"); break;
case 1: printf("one\n“) break;
case 3: printf("three\n"); break;
case 4: printf("four\n"); break;
case 5: printf("five\n"); break;
case 6: printf("six\n"); break;
case 7: printf("seven\n"); break;
case 8: printf("eight\n"); break;
case 9: printf("nine\n"); break;
default: printf(“not a single digit\n”);
}
•Compares variable to each case in order
•When match found, starts executing inner code until break; reached
•Execution “falls through” if break; not included
22
The switch Statement - Example
What would be printed in each case?
i = -1;
switch( i )
{
case -1:
i = -1;
switch( i )
{
case -1:
printf(“Negative”);
break;
printf(“Negative”);
case 0 :
case 0 :
printf(“Zero”);
break;
printf(“Zero”);
case 1 :
case 1 :
printf(“Positive”);
break;
printf(“Positive”);
}
}
23
If & switch Statements
if (i == -1)
printf(“Negative”);
else if (i == 0)
printf(“Zero”);
else if (i ==1)
printf(“Positive”);
switch( i )
{
case -1:
printf(“Negative”);break;
case 0 :
printf(“Zero”); break;
case 1 :
printf(“Positive”); break;
}
• switch statement: All branches test the same value, namely i
•The test cases must be integers or characters. You cannot use a
switch to branch on floating-point or string values.
24