Workshop: Lab 4 Engineering Software 1 Lab 4: Control Statements Learning Objectives In this lab exercise you will learn: • To use basic problem-solving techniques. • To develop algorithms through the process of top-down, stepwise refinement. • To use the if and if…else selection statements to choose among alternative actions. • To use the while repetition statement to execute statements in a program repeatedly. • To use counter-controlled repetition and sentinel-controlled repetition. • To use the assignment, increment and decrement operators. Lab Work General Note: Study every exercise and for each of them draw a structure diagram. Type in all these programs and run them inside your Java development kit. In your log-book take note of all the results from the execution of these programs and write down any problems that you had to solve. For each program of the exercises, explain clearly what each section of the program is doing. You may need to perform a walk-through, line by line, where this is appropriate. Record all your explanations in the log-book. Remember to put a date in your log-book and also to offer some discussions and a brief conclusion after every week’s work. Finally, complete the programming assignments at the end of the exercises, then enter comments in your logbook as you are doing this and save to your floppy disk/CD for submission with your logbook. Background • An algorithm is a procedure for solving a problem in terms of the actions to execute and the order in which the actions execute. • Specifying the order in which statements (actions) execute in a program is called program control. • Pseudocode helps a programmer think out a program before attempting to write it in a programming language. • Activity diagrams are part of a design modeling technique. • An activity diagram models the workflow (also called the activity) of a software system. • Activity diagrams are composed of special-purpose symbols, such as action-state symbols, diamonds and small circles. These symbols are connected by transition arrows that represent the flow of the activity. • Like pseudocode, activity diagrams help programmers develop and represent algorithms. • An action state is represented as a rectangle with its left and right sides replaced with arcs curving Stavros Dimitriou ©London South Bank University 1 Workshop: Lab 4 Engineering Software 1 outward. The action expression appears inside the action state. • The arrows in an activity diagram represent transitions, which indicate the order in which the actions represented by action states occur. • The solid circle located at the top of an activity diagram represents the initial state—the beginning of the workflow before the program performs the modeled actions. • The solid circle surrounded by a hollow circle that appears at the bottom of the activity diagram represents the final state—the end of the workflow after the program performs its actions. • Rectangles with the upper-right corners folded over are called notes in the UML. Notes are explanatory remarks that describe the purpose of symbols in the diagram. A dotted line connects each note with the element that the note describes. • A diamond or decision symbol in an activity diagram indicates that a decision is to be made. The workflow will continue along a path determined by the symbol’s associated guard conditions, which can be true or false. Each transition arrow emerging from a decision symbol has a guard condition (specified in square brackets next to the transition arrow). If a guard condition is true, the workflow enters the action state to which the transition arrow points. • A diamond in an activity diagram also represents the merge symbol, which joins two flows of activity into one. A merge symbol has two or more transition arrows pointing to the diamond and only one transition arrow pointing from the diamond, to indicate multiple activity flows merging to continue the activity. • Top-down, stepwise refinement is a process for refining pseudocode by maintaining a complete representation of the program during each refinement. • There are three types of control structures—sequence, selection and repetition. • The sequence structure is built into Java—by default, statements execute in the order they appear. • A selection structure chooses among alternative courses of action. • The if single-selection statement either performs (selects) an action if a condition is true, or skips the action if the condition is false. • The if…else double-selection statement performs (selects) an action if a condition is true and performs a different action if the condition is false. • To include several statements in an if’s body (or the body of else for an if…else statement), enclose the statements in braces ({ and }). A set of statements contained within a pair of braces is called a block. A block can be placed anywhere in a program that a single statement can be placed. • An empty statement, indicating that no action is to be taken, is indicated by a semicolon (;). • A repetition statement specifies that an action is to be repeated while some condition remains true. • The format for the while repetition statement is while ( condition ) statement • Counter-controlled repetition is used when the number of repetitions is known before a loop begins executing. • The unary cast operator (double) creates a temporary floating-point copy of its operand. • Sentinel-controlled repetition is used when the number of repetitions is not known before a loop begins executing. • A nested control statement appears in the body of another control statement. • Java provides the arithmetic compound assignment operators +=, -=, *=, /= and %= for abbreviating assignment expressions. • The increment operator, ++, and the decrement operator, --, increment or decrement a variable by 1, respectively. If the operator is prefixed to the variable, the variable is incremented or decremented by 1 first, and then its new value is used in the expression in which it appears. If the operator is postfixed to the variable, the variable is first used in the expression in which it appears, and then the variable’s value is incremented or decremented by 1. • The primitive types (boolean, char, byte, short, int, long, float and double) are portable across all computer platforms that support Java. Stavros Dimitriou ©London South Bank University 2 Workshop: Lab 4 Engineering Software 1 • Java is a strongly typed language—it requires all variables to have a type. • Local variables are declared inside methods and are not assigned default values. • Variables declared outside of methods as fields are assigned default values. Instance variables of types char, byte, short, int, long, float and double are all given the value 0 by default. Instance variables of type boolean are given the value false by default. Reference-type instance variables are initialized by default to the value null. Part A: Reinforce your understanding of key Java programming concepts After reading the background above along with lecture notes, answer the given questions. The questions are intended to test and reinforce your understanding of key concepts. For each term in the left column, write the letter for the description from the right column that best matches the term. Stavros Dimitriou ©London South Bank University 3 Workshop: Lab 4 Engineering Software 1 Answer the following questions in your logbook. Your answers should be as concise as possible; aim for two or three sentences. 1. Explain the purpose of a selection statement. 2. Use pseudocode or an FD diagram to give an example of sequence control statements. 3. Describe the term “algorithm” and why pseudocode can help programmers develop algorithms. 4. Use pseudocode or an FD diagram to give an example of an if… else selection statement. 5. Explain the difference between the if selection statement and the if… else selection statement. 6. Use pseudocode to give an example of a looping construct in which the number of repetitions is known in advance. Part B: Java programs Exercise 1 For each of the given program segments, read the code, and write the output in your logbook. Assume the following class definition. 1.1 What will be output by lines 11–14 if the user enters the integer 2 at line 9? 1.2 What will be output by lines 11–14 if the user enters the integer 3 at line 9? 1.3 What will be the output if the following code is placed at line 10 of the preceding class definition? Assume that the user enters 5. Stavros Dimitriou ©London South Bank University 4 Workshop: Lab 4 Engineering Software 1 Exercise 2 For each of the given program segments, read the code, and write the output in your logbook. 2.1 What is output by the following program? Exercise 3 For each of the given program segments, read the code, and write the output in your logbook. Assume the following class definition. 3.1 What will be the output if the following code is placed at line 8 of the class? 3.2 What will be the output if the following code is placed at line 8 of the class? Stavros Dimitriou ©London South Bank University 5 Workshop: Lab 4 Engineering Software 1 3.3 What will be the output if the following code is placed at line 8 of the class? Exercise 4 Determine if there is an error in each of the following program segments. If there is an error, specify whether it is a logic error or a compilation error, circle the error in the program and write the corrected code in the space provided after each problem. If the code does not contain an error, write “no error.” [ Note: There may be more than one error in each program segment.] 4.1 The following segment of code should calculate whether a student has a passing grade. If so, the code should print "Passed." Otherwise, the code should print "Failed." and "You must take this course again." 4.2 The following while loop should print all the even integers between 0 and 20, inclusive. 4.3 The following while loop should print the sum of the integers between 0 and 5, inclusive. Stavros Dimitriou ©London South Bank University 6 Workshop: Lab 4 Engineering Software 1 Programming Assignment Develop a Java application that will determine whether any of several department-store customers has exceeded the credit limit on a charge account. For each customer, the following facts are available: a) account number b) balance at the beginning of the month c) total of all items charged by the customer this month d) total of all credits applied to the customer’s account this month e) allowed credit limit. The program should input all of these facts as integers, calculate the new balance ( = beginning balance + charges – credits), display the new balance and determine whether the new balance exceeds the customer’s credit limit. For those customers whose credit limit is exceeded, the program should display the message "Credit limit exceeded”. Problem-Solving Tips 1. There are five input values required. But the account number must be input before the loop in order to test whether it is equal to the sentinel value. So there should be six input statements, five in the loop and one before it. 2. Use the formula given in the problem description to compute the new balance. 3. Use an if statement to determine whether newBalance is larger than the customer’s creditLimit . If so, indicate that the credit limit was exceeded. 4. Write out your algorithms in pseudocode before writing any code. 5. Be sure to follow the spacing and indentation conventions mentioned in the text. 6. If you have any questions as you proceed, ask your lab instructor for assistance. Stavros Dimitriou ©London South Bank University 7