Control Structures - Florida International University
Chapter 1 2
Chapter 2 2
Chapter 3 2
Chapter 4 Control Structures 3
Objectives 3
Introduction 3
Selection Statements 4
The if Statements 5
The if .. else Statements 10
Pitfalls 15
Pitfall I – Misplacing Semi-colon 15
Pitfall II – Separating else with semi-colon 16
Pitfall III – Failing to block statement properly 17
Pitfall IV – Misusing series of if statements 18
Pitfall V – Misrepresenting nested if statements 19
Pitfall VI Misusing = and == 21
Rules Governing the if Statement 21
The switch Statement 24
Pitfalls 32
Pitfall I – Forgetting the parentheses 32
Pitfall II – Forgetting the braces. 32
Pitfall III – Forgetting the break keyword 32
Rules Governing the Switch Statement 35
Iterative Statements 39
The while Statement 39
Nested while Loop 46
The do…while Statement 58
The for Statement 60
Nesting for Loops. 65
Scope of a Loop control variable 66
PitFall 67
Pitfall I – Updating the loop variable incorrectly 67
Pitfall II – Modifying the loop variable in loop body 67
Summary 70
Exercises 71
Control Structures
Objectives
• To understand what control structures are and the need for them.
• To understand the two types control flow – selection and iteration.
• To understand selection statements – if, if/else and switch.
• To understand iterative statements – while, do/while, and for.
Introduction
The order in which statements are executed in programs is determined by the controls to which each statement is subjected. Unless otherwise specified, the execution of a program proceeds in a linear fashion, from the first statement to the last; no statement is skipped, and none is repeated. Figure 4.1 shows what happens when statements are executed in sequence; each statement represented by S, is executed in the order in which each is written.
Figure 4.1Program statements executed in sequence.
The invocation of methods do not constitute an altering of the control flow, but rather it is an expansion of the statement call, in which case the statement is expanded by the method definition. If we let M represents a method instead of a single statement, as shown in Figure 4.2, then when the method is called, it simply executes its statements, and then re-enters the original linear formation of statements.
Original Linear Formation
Method M() definition
Figure 4.2 Method M is called from the original linear formation
Control structures seek to alter the flow of program statements within a given piece of code. This is carried out using two control structures - selection and iteration.
Selection Statements
Selection statements are those statements that allow for choice to be made. The decision for making a choice is based on the result of a conditional expression. Figure 4.3 represents a decision making process. In this Figure, notice that the result of the conditional expression – representing a decision – is one of the Boolean values, true or false.
true
false
Figure 4.3 Symbol representing selection.
There are two basic forms of selection statements in Java. These are the if statement and the switch statement.
The if Statements
As we said earlier, the if statement allows us to make choice. The statement has two forms, namely, if without an alternate choice, and if with alternate choice, symbolized by the keyword else. The word if is also a keyword. The general format of the if statement without an alternate choice is as follows:
if ( conditional_expression )
a_single_statement;
or
if ( conditional_expression )
{
Two or more statements;
}
The interpretation of this form of the if statement is this, if the conditional expression evaluates to true, then the statement or the block of statements that follow the condition will be executed. If the result is false, then the statement or block of statements that follow the condition will be skipped. Figure 4.4 shows conceptually, the format of the if statement that does not have an alternate choice.
true
false
Figure 4.4 An if statement without alternate choice
The following is an example of its usage:
if ( 30 > 25)
System.out.println(“That is correct”);
Where the word if is the keyword, and 30 > 25 is the conditional expression that is being tested. In this case the condition evaluates to true, and so the print statement is executed.
Example 4.1
The cost of an international telephone call is a flat fee of $4.00 for up to the first 5 minutes, and $0.25 per minute for any additional minutes. Write a class definition called Telephone that accepts an integer, representing the number of minutes used. Provide a method called calculateBill that calculates customers, bill.
Solution
• Name of class Telephone
• Constants:
o Flat rate $4.00
o Cost per additional minutes 0.25
o Maximum number of minutes at flat rate, 5
• Instance variable – the minutes
• Constructor:
o Accepts number of minutes spent on each call
• Method calculateBill()
The total cost of a call is the flat rate up to 5 minutes, and 25 cents * any additional minutes. The condition for the additional expense must be based on the relation between the number of minutes used, and the five minutes for the flat rate. That is:
if (minutes > 5 )
then charge the additional cost.
Listing 4.1 shows the class Telephone. Lines 3 – 4 set up the class constants. Lines 5 – 6 declare the instance variables. The constructor which receives a single value representing the number of minutes used, spans Lines 7 – 11. Notice that the initial charge is $4.00. Any additional minutes must be charged. The method calculateBill(), shown on Lines 12 – 15, determines if the number of minutes used, exceed the maximum number of minutes at the flat rate. Notice also that the test does not indicate an alternate choice.
1. public class Telephone
2. {
3. private final static float FLAT_RATE = 4.0F,
RATE = 0.25F;
4. private final static int MAX_MINUTES = 5;
5. private int minutes;
6. private float charges;
7. public Telephone(int minutes)
8. {
9. this.minutes = minutes;
10. charges = FLAT_RATE;
11. }
12. public void calculateBill()
13. {
14. if (minutes > MAX_MINUTES)
charges = charges + (minutes - MAX_MINUTES)*RATE;
15. }
16. public float getBill()
17. {
18. return charges;
19. }
20. }
Listing 4.1 Implementing the if without an alternative choice.
Listing 4.2 shows a typical test class. Line 10 simply creates a customer object that spends m number of minutes on a call. Line 11 calls the calculate method, and Line 12 calls the getBill() method in order to print the bill for the customer.
1. import java.text.NumberFormat;
2. import java.util.Scanner;
3. public class TestTelephone
4. {
5. public static void main(String[] arg)
6. {
7. NumberFormat nf = NumberFormat.getCurrencyInstance();
8. Scanner s = Scanner.create(System.in);
9. int m = s.nextInt();
10. Telephone t = new Telephone(m);
11. t.calculateBill();
12. System.out.println("Your bill is " + nf.format(t.getBill()));
13. s.close();
14. }
15. }
Listing 4.2 Test class for the class Telephone.
If two or more statements depend on the outcome of a conditional expression, then those statements form a block, and they must be enclosed within curly braces. For instance, in the program segment below, the two print statements depend on the outcome of the test in the if statement, as such these statements must be enclosed within the pair of curly brace, as shown below..
if ( 30 > 25 )
{
System.out.println(“That is correct”);
System.out.println();
}
Again, in this case the conditional expression is evaluated to true, hence, the block of statements is executed.
In Example 4.1 we used a relational expression for the conditional expression. Logical expressions can also be used, as we will see in the next example.
Example 4.2
The ABC Company offers scholarships to individuals who are in need of financial assistance. The company advertises the scholarship nation wide. Preference however, is given to Florida residents who range from 18 years old to 25 years old.
Write a class called Scholarship that accepts the name, age, and the state in which the applicant resides. Include a Boolean instance method called checkEligibility that determines a candidate’s eligibility for a scholarship. The class must also provide methods to retrieve the name and age of those applicants who are selected.
Analysis
• Name of entity:
o Scholarship.
• Member variables:
o name, state (String)
o age (int).
• Things to be done:
o Determine eligibility (check the state)
o Provide method to return whether or not the individual is eligible (true/false)
o Provide methods to return other relevant information such as name and age
• To determine eligibility status of an applicant, we must form a logical expression using age and place of residence as operands. That is:
state.equals(“Florida”) && age >= 18 && age = 18 && age ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- florida state university education department
- florida state university course catalog
- international university accreditation list
- florida state university online certificates
- florida public university system
- florida state university employee salaries
- florida state university pay scale
- florida state university map printable
- florida state university certificate programs
- florida state university football schedule
- florida state university pictures
- florida state university football roster