You are on page 1of 22

Course Notes for

CS 0401
Intermediate Programming
(with Java)
By
John C. Ramirez
Department of Computer Science
University of Pittsburgh
• These notes are intended for use by students in CS0401
at the University of Pittsburgh and no one else
• These notes are provided free of charge and may not be
sold in any shape or form
• Material from these notes is obtained from various
sources, including, but not limited to, the following:
4 Starting Out with Java, From Control Structures through Data
Structures, Fourth Edition, by Gaddis and Muganda
4 Starting Out with Java, From Control Structures through Objects,
Third to Seventh Editions by Gaddis
4 Java Software Solutions, Fourth and Fifth Editions by Lewis and
Loftus
4 Java By Dissection by Pohl and McDowell
4 The Java Tutorial (click for link)
4 The Java home page and its many sub-links:
http://www.oracle.com/technetwork/java/index.html

2
Lecture 4: if statement

• Nested ifs
4 Since both <true option> and <false option>
can be any Java statement, they can certainly
be if statements
4 This allows us to create nested if statements
• We can nest on <true option>, on <false option> or
both
• Enables us to test multiple conditions and to have a
different result for each possibility
• Let's look at an example

3
Lecture 4: if statement
double score = inScan.nextDouble();
String grade;
if (score >= 90)
grade = "A";
else if (score >= 80) Statement for first 'else' is all remaining code
grade = "B";
else if (score >= 70) Statement for second 'else' is all remaining code
grade = "C";
else if (score >= 60) Statement for third 'else' is all remaining code
grade = "D";
else Statement for last 'else' is assignment
grade = "F";
• Note that by using nesting on the 'else' clauses we are
making the conditions exclusive
– Only one grade will ever be chosen per score
• Also note that each 'else' is nested one level deeper
than the previous
– Even though they are all typed at the same level
4
Lecture 4: if statement

4 Dangling else
• The structure of a Java if statement allows for an
interesting special case:
if (score >= 95) // condition1
if (extraCredit) // condition2
grade = "A+";
else
grade = "??";
• Question: is the <else> for condition1 or condition2?
– Note how it is drawn
> Does this matter?
– As shown above the else will ALWAYS be for condition2
– Rule is that an else will always be associated with the
“closest” unassociated, non-terminated if

5
Lecture 4: if statement

• Thus, there is no problem for the computer


– Problem is if the programmer does not understand
the rule and thinks the 'else' goes with the outer 'if'
> May think indenting determines logic or may just misread
the code
– Result is a LOGIC ERROR
> Logic errors can be very problematic and difficult to correct
> Unlike a syntax error, which prevents the program from
being compiled, with a logic error the program may run
and may seem fine
> However, one or more errors in the programmer’s logic
cause the result will be incorrect!
• What if we want to 'else' to go with the outer 'if'?
– Put braces around the inner 'if'
– This will terminate it so the 'else' will move to the outer
'if'
6
Lecture 4: Programming Errors

• Let's compare 3 common types of


programming errors:
• COMPILATION ERROR
4 Error in the structure or syntax of the code
• Ex: missing semicolon
• Ex: using reserved word as an identifier
4 Detected by the compiler (javac)
• It typically is very helpful, telling the error and location
• Does not always correctly identify cause of error but
often does

7
Lecture 4: Programming Errors

• RUN-TIME ERROR
4 Error during program execution
4 Ex: InputMismatchException,
ArrayIndexOutOfBoundsException
• We will see many more of these
4 Detected by the interpreter (JRE)
• Also quite helpful identifying occurrence and location
of the error
• May not always detect underlying cause of the error
– Why did we go past the end of the array?
– Programmer may have to figure this out

8
Lecture 4: Programming Errors

• LOGIC ERROR
4 Error in the logic or meaning of the code
4 Ex: Programmer meant Z = X + Y;
• But actually typed Z = X * Y;
• Note that both statements are legal and will compile
and run, but they will give different answers
4 Ex: Dangling else
• Programmer thought else was associated with outer if
but it was really associated with inner if
4 Note that since these programs will compile and
(usually) run, detecting logic errors is often
difficult
9
Lecture 4: Programming Errors

4 Often detecting and fixing logic errors requires a


lot of effort
• When we talk about "debugging our code" or we talk
about "quality assurance" we are usually talking about
fixing logic errors
• A program could be in use for quite some time before
these are even detected
– May not occur in all situations
4 When learning to program
• Compilation errors cause grief
– Programmers don't know syntax yet
4 Later
• Logic errors cause most grief by far
10
Lecture 4: while loop

• The while loop is fairly intuitive


while (booleanexpression)
<loop body>;
4 where <loop body> can be any Java statement
4 Logic of while loop:
• Evaluate (booleanexpression)
• If result is true, execute <loop body>, otherwise skip to
next statement after loop
• Repeat
4 while loop is called an entry loop, because a
condition must be met to get IN to the loop body
• Implications of this?
11
Lecture 4: Example

• Let's now use if and while in a simple


program:
4 User will enter some scores and the program will
calculate the average
4 Consider some questions / issues:
• What type of data will the scores be?
• What is the acceptable range for the scores?
– What do we do if a score is unacceptable?
• How many scores are there?
– Do we even know this in advance?
– What to do if we do not know this in advance?

12
Lecture 4: Example

• Are there any special cases that we need to consider?


– What if there are 0 scores entered?
• What variables will we need to use?
– And what will be their types?
– We will discuss these in the Zoom session
4 Once we have an idea for a solution, let’s look at
two possible approaches
• ex5a.java and ex5b.java
• Note that for many programming problems, there are
MANY possible solutions
– Does not necessarily mean one is right and the other is
wrong

13
Lecture 4: Counting Loop

4 ex5a uses a counting loop


• Idea here is that we are iterating a certain number of
times, which we keep track of with a counter
int count = 0;
while (count < max)
{
// do stuff
count++;
}
• In this approach we know how many iterations that
we want
– Which for the average of scores problem would be the
number of scores
– However, in the ex5a program some entries are not
actually counted
> If the score is not valid we should not count it
14
Lecture 4: Counting Loop

• The loop is counting how many scores have been


accepted
– The total number of iterations includes scores that are
not accepted
• Thus the actual total number of iterations can be
arbitary
• See ex5a.java

15
Lecture 4: Sentinel-controlled Loop

4 ex5b uses a sentinel-controlled loop


• Idea here is we loop, reading input each time
• We check to see if the input is a special value, called a
sentinel
– In this case, it tells us to exit the loop
– Otherwise, we use the input and iterate again
read input
while (input != sentinel)
{
process input
read next input
}
• In this approach we don't know the number of
iterations until the loop terminates
– It depends on when the sentinel value is entered

16
Lecture 4: Sentinel-controlled Loops

• Note that the sentinel could be entered at any time,


including the first input
• It could also be entered by accident
– We could have premature termination of the loop
> Think: User enters 87 out of 125 scores and accidently
types in the sentinel value
> DOH!
– To combat this we should put in a check / confirmation
when the sentinel is entered
• See ex5b.java
• See ex5bnew.java

17
Lecture 4: for loop

• Another important Java control structure is


the for loop
4 Its obvious use is as a counting loop
• Goes through a specified number of iterations
for (int i = 0; i < max; i++)
{ // will iterate max times }
4 However it is much more general than that
for (init_expr; go_expr; inc_expr)
{
// loop body
}
• Let’s talk about this a bit
18
Lecture 4: for loop

• init_expr
– Any legal Java statement expression
– Evaluated one time, when the loop is FIRST executed
• go_expr
– Java Boolean expression
– Evaluated PRIOR to each execution of the for loop body
> If true, body is executed
> If false, loop terminates
• inc_expr
– Any legal Java statement expression
– Evaluated AFTER each execution of the for loop body
4 These expressions make the for loop extremely
flexible

19
Lecture 4: for loop

4 Try some examples:


• For loop to sum the numbers from N to M
N + (N+1) + … + (M-1) + M
– Intuitively, would this be a counting loop or a sentinel-
controlled loop?
> Counting loop
– Our counter would start at N and proceed to M
> In each iteration we add the value of the counter to the
sum
// read in values for N and M
int sum = 0;
for (int curr = N; curr <= M; curr++)
sum += curr;
– Note the go_expr --> be careful about this condition

20
Lecture 4: for loop

• For loop to output powers of 2 less than or equal to K


– Think about how this is different from prev. example
– At each iteration we are "automatically" updating two
different values:
> Value of the power (0, 1, 2, 3, …)
> Value of the result (1, 2, 4, 8, …)
– We could do these separately, but the for loop actually
allows us to update these both within the loop structure
// read in K
for (int pow = 0, val = 1; val <= K; pow++, val *= 2)
{
System.out.println("2^" + pow + "=" + val);
}
> Note multiple expressions in header
> Don't feel obliged to do this!
> See forexamples.java

21
Lecture 4: for loop

4 In effect we can use a for loop as a counting


loop or a sentinel-controlled loop
• Or some other variant
4 However, it is more readable and less prone to
logic errors if you use it as a counting loop
• This tends to be its most common use

4 We will revisit our score sum program using a


for loop in the next lecture

22

You might also like