# Control Statements: Part 1

Size: px
Start display at page:

Transcription

1 4 Let s all move one place on. Lewis Carroll Control Statements: Part 1 The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert Frost All the evolution we know of proceeds from the vague to the definite. Charles Sanders Peirce OBJECTIVES In this chapter 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.

2

3 Chapter 4 Control Statements: Part 1 99 Assignment Checklist Date: Section: Exercises Assigned: Circle assignments Date Due Prelab Activities Matching YES NO Fill in the Blank YES NO Short Answer YES NO Programming Output YES NO Correct the Code YES NO Lab Exercises Exercise 1 Credit YES NO Follow-Up Questions and Activities 1, 2 Exercise 2 Palindromes YES NO Follow-Up Question and Activity 1 Exercise 3 Largest Number YES NO Follow-Up Question and Activity 1 Debugging YES NO Postlab Activities Coding Exercises 1, 2, 3, 4, 5, 6 Programming Challenges 1, 2

4

5 Chapter 4 Control Statements: Part Prelab Activities Matching Date: Section: After reading Chapter 4 of Java How to Program: Seventh Edition, answer the given questions. These questions are intended to test and reinforce your understanding of key Java concepts. You may answer these questions either before or during the lab. For each term in the left column, write the letter for the description that best matches the term from the right column. Term Description M I A K H O P C E Q G D B F J L N ?: 4. algorithm 5. selection statement 6. sentinel-controlled repetition 7. ; 8. pseudocode 9. repetition statement 10. counter-controlled repetition 11. program control 12. top-down, stepwise refinement 13. if 14. if else 15. block 16. +=, -=, *=, /=, %= 17. primitive types a) Java s only ternary operator. b) A selection statement that executes an indicated action only when the condition is true. c) An artificial and informal language that helps programmers develop algorithms. d) A process for refining pseudocode by maintaining a complete program representation for each refinement. e) Allows the programmer to specify that an action is to be repeated while some condition remains true. f) A selection statement that specifies separate actions to execute when a condition is true and when a condition is false. g) Specifying the order in which statements are to be executed in a computer program. h) Chooses among alternative courses of action in a program. i) Increment operator. j) A set of statements contained within a pair of braces. k) A procedure for solving a problem in terms of the actions to execute and the order in which the actions should execute. l) Arithmetic assignment operators. m) Decrement operator. n) Building blocks for more complicated types in Java. o) Used when the number of repetitions is not known before the loop begins executing. p) Empty statement. q) Used when the number of repetitions is known before the loop begins executing.

6

7 Chapter 4 Control Statements: Part Prelab Activities Fill in the Blank Fill in the Blank Date: Section: Fill in the blanks for each of the following statements: 18. Specifying the order in which statements execute in a computer program is called program control. 19. The if selection statement executes an indicated action only when the condition is true. 20. Top-down, stepwise refinement is a process for refining pseudocode by maintaining a complete representation of the program during each refinement. 21. Java requires all variables to have a type before they can be used in a program. For this reason, Java is referred to as a(n) strongly typed language. 22. Java uses internationally recognized standards for both characters and floating-point numbers. 23. A(n) declaration specifies the type and name of a variable. 24. The if else selection statement specifies separate actions to execute when the condition is true and when the condition is false. 25. The ++ operator and the -- operator increment and decrement a variable by 1, respectively. 26. Unary cast operator ( double ) creates a temporary double-precision, floating-point copy of its operand. 27. A value that contains a fractional part is referred to as a floating-point number and is represented by the types float or double.

8

11 Chapter 4 Control Statements: Part Prelab Activities Programming Output Programming Output Date: Section: For each of the given program segments, read the code and write the output in the space provided below each program. [ Note: Do not execute these programs on a computer.] For questions assume the following class definition: 1 public class Test2 2 { 3 public static void main( String args[] ) 5 Scanner input = new Scanner(); 6 int number1; 7 8 System.out.println( "Enter an integer:" ); 9 number1 = input.nextint(); if ( number1 % 2 == 0 ) 12 System.out.println( "%d is even\n", number1 ); 13 else 14 System.out.println( "%d is odd\n", number1 ); 15 } // end main 16 } // end class Test2 37. What will be output by lines if the user enters the integer 2 at line 9? Your answer: 2 is even 38. What will be output by lines if the user enters the integer 3 at line 9? Your answer: 3 is odd 39. 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. 1 number1 = number1 + 3 ;

12 108 Control Statements: Part 1 Chapter4 Prelab Activities Programming Output Your answer: 8 is even 40. What is output by the following program? 1 public class Grade 2 { 3 public static void main( String args[] ) 5 int grade1 = 65; 6 int grade2 = 50; 7 8 System.out.println( grade1 >= 60? "Passed." : "Failed." ); 9 System.out.println( grade2 >= 60? "Passed." : "Failed." ); 10 } // end main 11 } // end class Grade Your answer: Passed Failed For questions 41 43, assume the following class declaration: 1 public class Value 2 { 3 public static void main( String args[] ) 5 int x; 6 int xlimit; 7 8 /* assign values to x and xlimit here */ 9 10 while ( x <= xlimit ) 11 { 12 x++; 13 System.out.printf( "The value of x is %d\n", x ); 14 } // end while System.out.printf( "The final value of x is %d\n", x ); 17 } // end main 18 } // end class Value

13 Chapter 4 Control Statements: Part Prelab Activities Programming Output 41. What will be the output if the following code is placed at line 8 of the class? 1 x = 1 ; 2 xlimit = 5 ; Your answer: The value of x is 2 The value of x is 3 The value of x is 4 The value of x is 5 The value of x is 6 The final value of x is What will be the output if the following code is placed at line 8 of the class? 1 x = 1 ; 2 xlimit = -2; Your answer: The final value of x is What will be the output if the following code is placed at line 8 of the class? 1 x = 10; 2 xlimit = 5 ; Your answer: The final value of x is 10

14 110 Control Statements: Part 1 Chapter4 Prelab Activities Programming Output For questions 44 46, assume the following class declaration: 1 public class Value 2 { 3 public static void main( String args[] ) 5 int x; 6 int xlimit; 7 8 /* assign values to x and xlimit here */ 9 10 while ( x <= xlimit ) 11 { 12 x++; if ( x % 2 == 0 ) 15 System.out.printf( "%d is even.\n", x ); 16 else 17 System.out.printf( "%d is odd.\n", x ); 18 } // end while 19 } // end main 20 } // end class Value 44. What will be the output if the following code is placed at line 8 of the class? 1 x = 0 ; 2 xlimit = 10; Your answer: 1 is odd. 2 is even. 3 is odd. 4 is even. 5 is odd. 6 is even. 7 is odd. 8 is even. 9 is odd. 10 is even. 11 is odd. 45. What will be the output if the following code is placed at line 8 of the class? 1 x = 0 2 xlimit = -2; Your answer: (no output)

15 Chapter 4 Control Statements: Part Prelab Activities Programming Output 46. What will be the output if the following code is placed at line 8 of the class? 1 x = 10; 2 xlimit = 5 ; Your answer: (no output)

16

17 Chapter 4 Control Statements: Part Prelab Activities Correct the Code Correct the Code Date: Section: 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.] 47. 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." 1 if ( grade >= 60 ) 2 System.out.println( "Passed." ); 3 else 4 System.out.println( "Failed." ); 5 System.out.println( "You must take this course again." ); Your answer: 1 if ( grade >= 60 ) 2 System.out.println( "Passed." ); 3 else 5 System.out.println( "Failed." ); 6 System.out.println( "You must take this course again." ); 7 } Missing braces before line 4 and after line 5. Logic error. 48. The following while loop should compute the product of all the integers between 1 and 5, inclusive. 1 int i = 1 ; 2 int product = 1 ; 3 4 while ( i <= 5 ); 5 product *= i;

18 114 Control Statements: Part 1 Chapter4 Prelab Activities Correct the Code Your answer: 1 int i = 1 ; 2 int product = 1 ; 3 4 while ( i <= 5 ); 5 { 6 product *= i; 7 i++; 8 } The value of variable i is not incremented in the while loop. Logic error. The semicolon after the while loop s header must be removed. Logic error. 49. The following while loop should print all the even integers between 0 and 20, inclusive. 1 int i = 0 ; 2 3 while ( i <= 20 ) 4 5 if ( i % 2 = 0 ) 6 System.out.printf( "%d ", i ); 7 8 i++ Your answer: 1 int i = 0 ; 2 3 while ( i <= 20 ) 5 if ( i % 2 = 0 ) 6 System.out.printf( "%d ", i ); 7 8 i++ 9 } Missing braces on lines 4 and 9. Variable i must be incremented within the while loop or the program will enter an infinite loop. Logic error. 50. The following while loop should print the numbers 0 through 5, inclusive. 1 int i = 0 ; 2 3 while ( i < 5 ) 5 System.out.printf( "%d ", i ); 6 i++; 7 }

19 Chapter 4 Control Statements: Part Prelab Activities Correct the Code Your answer: 1 int i = 0 ; 2 3 while ( i <= 5 ) 5 System.out.printf( "%d ", i ); 6 i++; 7 } The if statement on line 3 should use the <= operator. Otherwise, the loop will not print i when it is equal to 5. Logic error. 51. The following while loop should print the even numbers from 20 down through 0, inclusive. 1 int i = 20; 2 3 while ( i >= 0 ) 5 if ( i % 2 == 0 ) 6 System.out.printf( "%d ", i ); 7 8 i++; 9 } 10 Your answer: 1 int i = 20; 2 3 while ( i >= 0 ) 5 if ( i % 2 == 0 ) 6 System.out.printf( "%d ", i ); 7 8 i--; 9 } 10 Variable i should be decremented on line 8. If the value is incremented, the program will enter an infinite loop. Logic error.

20 116 Control Statements: Part 1 Chapter4 Prelab Activities Correct the Code 52. The following while loop should print the sum of the integers between 0 and 5, inclusive. 1 int sum = 0 ; 2 3 while ( i <= 5 ) 5 sum += i; 6 i++; 7 } 8 9 System.out.printf( "The sum is: %d\n", sum ); Your answer: 1 int sum = 0 ; 2 int i = 0 ; 3 4 while ( i <= 5 ) 5 { 6 sum += i; 7 i++; 8 } 9 10 System.out.printf( "The sum is: %d\n", sum ); Variable i must be declared and initialized on line 2. Compilation error. 53. The following while loop should print the sum of the odd integers between 0 and 15, inclusive. 1 int sum = 0, i = 0 ; 2 3 while ( i < 15 ) 5 if ( i % 2!= 0 ) 6 sum += i; 7 8 i++; 9 } System.out.printf( "The sum is: %d\n", sum );

21 Chapter 4 Control Statements: Part Prelab Activities Correct the Code Your answer: 1 int sum = 0, i = 0 ; 2 3 while ( i <= 15 ) 5 if ( i % 2!= 0 ) 6 sum += i; 7 8 i++; 9 } System.out.printf( "The sum is: %d\n", sum ); The while loop should use the <= operator on line 3 so that the loop runs when i is equal to 15. Logic error. 54. The following while loop should print the product of the odd integers between 0 and 10, inclusive. 1 int product = 1, i = 0 ; 2 3 while ( i <= 10 ) 5 if ( i % 2!= 0 ) 6 i *= product; 7 8 product++; 9 } System.out.printf( "The product is: %d\n", product ); Your answer: 1 int product = 1, i = 0 ; 2 3 while ( i <= 10 ) 5 if ( i % 2!= 0 ) 6 product *= i; 7 8 i++; 9 } System.out.printf( "The product is: %d\n", product ); The program should multiply product by i during each iteration of the while loop. The while loop should then increment i. Logic error.

22

23 Chapter 4 Control Statements: Part Lab Exercises Lab Exercise 1 Credit Date: Section: The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 4.1 and Fig. L 4.2) 5. Problem-Solving Tips 6. Follow-Up Questions and Activities The program template represents a complete working Java program with one or more key lines of code replaced with comments. Read the problem description and examine the sample output, then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up questions. The source code for the template is available at and Lab Objectives This lab was designed to reinforce programming concepts from Chapter 4 of Java How to Program: Seventh Edition. In this lab, you will practice: Writing pseudocode. Using selection statements. The follow-up questions and activities also will give you practice: Using counter-controlled repetition. Description of the Problem 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".

24 120 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 1 Credit Sample Output Enter Account Number (or -1 to quit): 1 Enter Balance: 100 Enter Charges: 80 Enter Credits: 25 Enter Credit Limit: 200 New balance is 155 Enter Account Number (or -1 to quit): 2 Enter Balance: 450 Enter Charges: 240 Enter Credits: 300 Enter Credit Limit: v New balance is 390 Enter Account Number (or -1 to quit): 3 Enter Balance: 500 Enter Charges: 300 Enter Credits: 125 Enter Credit Limit: 400 New balance is 675 Credit limit exceeded Enter Account Number (or -1 to quit): -1 Program Template 1 // Lab 1: Credit.java 2 // Program monitors accounts. 3 import java.util.scanner; 4 5 public class Credit 6 { 7 // calculates the balance on several credit accounts 8 public void calculatebalance() 9 { 10 Scanner input = new Scanner( System.in ); int account; // account number 13 int oldbalance; // starting balance 14 int charges; // total charges 15 int credits; // total credits 16 int creditlimit; // allowed credit limit 17 int newbalance; // new balance System.out.print( "Enter Account Number (or -1 to quit): " ); 20 /* write code to input an integer and store it in account */ /* write code to loop while the account number is not -1 */ /* write code to input the rest of the customer information. */ /* write code to compute the new balance */ 27 Fig. L 4.1 Credit.java. (Part 1 of 2.)

25 Chapter 4 Control Statements: Part Lab Exercises Lab Exercise 1 Credit 28 /* write code that will check if the new balance is greater than the 29 credit limit and output the proper information */ /* write code to input a new account number and close the while loop. */ } // end method calculatebalance 34 } // end class Credit Fig. L 4.1 Credit.java. (Part 2 of 2.) 1 // Lab 1: CreditTest.java 2 // Test application for class Credit 3 public class CreditTest 5 public static void main(string args[]) 6 { 7 Credit application = new Credit(); 8 application.calculatebalance(); 9 } // end main 10 } // end class CreditTest Fig. L 4.2 CreditTest.java Problem-Solving Tips Solution Top: 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. Determine if each of an arbitrary number of department store customers has exceeded the credit limit on a charge account. First refinement: Input the account number, beginning balance, total charges, total credits, and credit limit for a customer, calculate the customer s new balance and determine if the balance exceeds the credit limit. Then process the next customer.

26 122 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 1 Credit Second refinement: Input the first customer s account number While the sentinel value (-1) has not been entered for the account number Input the customer s beginning balance Input the customer s total charges Input the customer s total credits Input the customer s credit limit Calculate the customer s new balance Print the new balance If the balance exceeds the credit limit Print "Credit Limit Exceeded" Input the next customer s account number 1 // Lab 1: Credit.java 2 // Program monitors accounts. 3 import java.util.scanner; 4 5 public class Credit 6 { 7 // calculates the balance on several credit accounts 8 public void calculatebalance() 9 { 10 Scanner input = new Scanner( System.in ); int account; // account number 13 int oldbalance; // starting balance 14 int charges; // total charges 15 int credits; // total credits 16 int creditlimit; // allowed credit limit 17 int newbalance; // new balance System.out.print( "Enter Account Number (or -1 to quit): " ); 20 account = input.nextint(); // read in account number // exit if the input is -1 otherwise, proceed with the program 23 while ( account!= -1 ) 2 25 System.out.print( "Enter Balance: " ); 26 oldbalance = input.nextint(); // read in original balance System.out.print( "Enter Charges: " ); 29 charges = input.nextint(); // read in charges System.out.print( "Enter Credits: " ); 32 credits = input.nextint(); // read in credits System.out.print( "Enter Credit Limit: " ); 35 creditlimit = input.nextint(); // read in credit limit // calculate and display new balance 38 newbalance = oldbalance + charges - credits; 39 System.out.printf( "New balance is %d\n", newbalance );

27 Chapter 4 Control Statements: Part Lab Exercises Lab Exercise 1 Credit // display a warning if the user has exceed the credit limit 42 if ( newbalance > creditlimit ) 43 System.out.println( "Credit limit exceeded" ); System.out.print( "\nenter Account Number (or -1 to quit): " ); 46 account = input.nextint(); // read in next account number 47 } // end while 48 } // end method calculatebalance 49 } // end class Credit 1 // Lab 1: CreditTest.java 2 // Test application for class Credit 3 public class CreditTest 5 public static void main(string args[]) 6 { 7 Credit application = new Credit(); 8 application.calculatebalance(); 9 } // end main 10 } // end class CreditTest Follow-Up Questions and Activities 1. Modify the program to use counter-controlled repetition to process 10 accounts. Solution 1 // Lab 1: Credit.java 2 // Program monitors accounts. 3 import java.util.scanner; 4 5 public class Credit 6 { 7 // calculates the balance on several credit accounts 8 public void calculatebalance() 9 { 10 Scanner input = new Scanner( System.in ); int account; // account number 13 int oldbalance; // starting balance 14 int charges; // total charges 15 int credits; // total credits 16 int creditlimit; // allowed credit limit 17 int newbalance; // new balance 18 int count = 0 ; // number of accounts entered // exit if the input is -1 otherwise, proceed with the program 21 while ( count < 10 ) 22 { 23 System.out.print( "\nenter Account Number: " ); 24 account = input.nextint(); // read in account number System.out.print( "Enter Balance: " ); 27 oldbalance = input.nextint(); // read in original balance

28 124 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 1 Credit System.out.print( "Enter Charges: " ); 30 charges = input.nextint(); // read in charges System.out.print( "Enter Credits: " ); 33 credits = input.nextint(); // read in credits System.out.print( "Enter Credit Limit: " ); 36 creditlimit = input.nextint(); // read in credit limit // calculate and display new balance 39 newbalance = oldbalance + charges - credits; 40 System.out.printf( "New balance is %d\n", newbalance ); // display a warning if the user has exceed the credit limit 43 if ( newbalance > creditlimit ) 44 System.out.println( "Credit limit exceeded" ); count++; // increment number of accounts input 47 } // end while 48 } // end method calculatebalance 49 } // end class Credit 1 // Lab 1: CreditTest.java 2 // Test application for class Credit 3 public class CreditTest 5 public static void main(string args[]) 6 { 7 Credit application = new Credit(); 8 application.calculatebalance(); 9 } // end main 10 } // end class CreditTest

29 Chapter 4 Control Statements: Part Lab Exercises Lab Exercise 1 Credit Enter Account Number: 1 Enter Balance: 100 Enter Charges: 80 Enter Credits: 25 Enter Credit Limit: 200 New balance is 155 Enter Account Number: 2 Enter Balance: 450 Enter Charges: 240 Enter Credits: 300 Enter Credit Limit: 600 New balance is 390 Enter Account Number: 3 Enter Balance: 500 Enter Charges: 300 Enter Credits: 125 Enter Credit Limit: 400 New balance is 675 Credit limit exceeded Enter Account Number: 4 Enter Balance: 0 Enter Charges: 350 Enter Credits: 0 Enter Credit Limit: 375 New balance is 350 Enter Account Number: 5 Enter Balance: 200 Enter Charges: 300 Enter Credits: 200 Enter Credit Limit: 250 New balance is 300 Credit limit exceeded Enter Account Number: 8 Enter Balance: 250 Enter Charges: 50 Enter Credits: 200 Enter Credit Limit: 250 New balance is 100 Enter Account Number: 9 Enter Balance: 500 Enter Charges: 100 Enter Credits: 300 Enter Credit Limit: 300 New balance is 300

30 126 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 1 Credit Enter Account Number: 10 Enter Balance: 75 Enter Charges: 240 Enter Credits: 125 Enter Credit Limit: 200 New balance is Modify the program to use counter-controlled repetition to process the number of accounts specified by the user. The number of accounts should be input before processing any account information. Solution 1 // Lab 1: Credit.java 2 // Program monitors accounts. 3 import java.util.scanner; 4 5 public class Credit 6 { 7 // calculates the balance on several credit accounts 8 public void calculatebalance() 9 { 10 Scanner input = new Scanner( System.in ); int account; // account number 13 int oldbalance; // starting balance 14 int charges; // total charges 15 int credits; // total credits 16 int creditlimit; // allowed credit limit 17 int newbalance; // new balance 18 int count = 0 ; // number of accounts entered 19 int number; // number of accounts for user to enter System.out.print( "Enter Number of Accounts: " ); 22 account = input.nextint(); // read in number of accounts // exit if the input is -1 otherwise, proceed with the program 25 while ( count < number ) 26 { 27 System.out.print( "Enter Account Number: " ); 28 account = input.nextint(); // read in account number System.out.print( "Enter Balance: " ); 31 oldbalance = input.nextint(); // read in original balance System.out.print( "Enter Charges: " ); 34 charges = input.nextint(); // read in charges System.out.print( "Enter Credits: " ); 37 credits = input.nextint(); // read in credits System.out.print( "Enter Credit Limit: " ); 40 creditlimit = input.nextint(); // read in credit limit // calculate and display new balance

31 Chapter 4 Control Statements: Part Lab Exercises Lab Exercise 1 Credit 43 newbalance = oldbalance + charges - credits; 44 System.out.printf( "New balance is %d\n", newbalance ); // display a warning if the user has exceed the credit limit 47 if ( newbalance > creditlimit ) 48 System.out.println( "Credit limit exceeded" ); count++; // increment number of accounts input 51 } // end while 52 } // end method calculatebalance 53 } // end class Credit 1 // Lab 1: CreditTest.java 2 // Test application for class Credit 3 public class CreditTest 5 public static void main(string args[]) 6 { 7 Credit application = new Credit(); 8 application.calculatebalance(); 9 } // end main 10 } // end class CreditTest Enter Number of Accounts: 3 Enter Account Number: 1 Enter Balance: 100 Enter Charges: 80 Enter Credits: 25 Enter Credit Limit: 200 New balance is 155 Enter Account Number: 2 Enter Balance: 450 Enter Charges: 240 Enter Credits: 300 Enter Credit Limit: 600 New balance is 390 Enter Account Number: 3 Enter Balance: 500 Enter Charges: 300 Enter Credits: 125 Enter Credit Limit: 400 New balance is 675 Credit limit exceeded

32 128 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 1 Credit

33 Chapter 4 Control Statements: Part Lab Exercises Lab Exercise 2 Palindromes Lab Exercise 2 Palindromes Date: Section: The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 4.3 and Fig. L 4.4) 5. Problem Solving Tips 6. Follow-Up Question and Activity The program template represents a complete working Java program with one or more key lines of code replaced with comments. Read the problem description and examine the sample output, then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up question. The source code for the template is available at and Lab Objectives This lab was designed to reinforce programming concepts from Chapter 4 of Java How to Program: Seventh Edition. In this lab you will practice: Using selection statements. Using sentinel-controlled repetition. Using if else selection statements. The follow-up question and activity will also give you practice: Modifying existing code to perform a similar task. Description of the Problem A palindrome is a sequence of characters that reads the same backward as forward. For example, each of the following five-digit integers is a palindrome: 12321, 55555, and Write an application that reads in a five-digit integer and determines whether it is a palindrome. If the number is not five digits long, display an error message and allow the user to enter a new value. Sample Output Enter a 5-digit number: 1234 Number must be 5 digits Enter a 5-digit number: Number must be 5 digits Enter a 5-digit number: is a palindrome!!!

34 130 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 2 Palindromes Program Template 1 // Lab 2: Palindrome.java 2 // Program tests for a palindrome 3 import java.util.scanner; 4 5 public class Palindrome 6 { 7 // checks if a 5-digit number is a palindrome 8 public void checkpalindrome() 9 { 10 Scanner input = new Scanner( System.in ); int number; // user input number 13 int digit1; // first digit 14 int digit2; // second digit 15 int digit4; // fourth digit 16 int digit5; // fifth digit 17 int digits; // number of digits in input number = 0 ; 20 digits = 0 ; /* Write code that inputs a five-digit number. Display an error message 23 if the number is not five digits. Loop until a valid input is received. */ /* Write code that separates the digits in the five digit number. Use 26 division to isolate the left-most digit in the number, use a remainder 27 calculation to remove that digit from the number. Then repeat this 28 process. */ /* Write code that determines whether the first and last digits are 31 identical and the second and Fourth digits are identical. Output 32 whether or not the original string is a palindrome. */ } // end method checkpalindrome 35 } // end class Palindrome Fig. L 4.3 Palindrome.java. 1 // Lab 2: PalindromeTest.java 2 // Test application for class Palindrome 3 public class PalindromeTest 5 public static void main( String args[] ) 6 { 7 Palindrome application = new Palindrome(); 8 application.checkpalindrome(); 9 } // end main 10 } // end class PalindromeTest Fig. L 4.4 PalindromeTest.java

35 Chapter 4 Control Statements: Part Lab Exercises Lab Exercise 2 Palindromes Solution 1 // Lab 2: Palindrome.java 2 // Program tests for a palindrome 3 import java.util.scanner; 4 5 public class Palindrome 6 { 7 // checks if a 5-digit number is a palindrome 8 public void checkpalindrome() 9 { 10 Scanner input = new Scanner( System.in ); int number; // user input number 13 int digit1; // first digit 14 int digit2; // second digit 15 int digit4; // fourth digit 16 int digit5; // fifth digit 17 int digits; // number of digits in input number = 0 ; 20 digits = 0 ; // Ask for a number until it is five digits 23 while ( digits!= 5 ) 2 25 System.out.print( "Enter a 5-digit number: " ); 26 number = input.nextint(); if ( number < ) 29 { 30 if ( number > 9999 ) 31 digits = 5 ; 32 else 33 System.out.println( "Number must be 5 digits" ); 34 } // end if 35 else 36 System.out.println( "Number must be 5 digits" ); 37 } // end while loop // get the digits 40 digit1 = number / 10000; 41 digit2 = number % / 1000; 42 digit4 = number % % 1000 % 100 / 10; 43 digit5 = number % % 1000 % 100 % 10; // print whether the number is a palindrome 46 System.out.print( number ); if ( digit1 == digit5 ) 49 { 50 if ( digit2 == digit4 ) 51 System.out.println( " is a palindrome!!!" ); 52 else 53 System.out.println( " is not a palindrome." ); 54 }

36 132 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 2 Palindromes 55 else 56 System.out.println( " is not a palindrome." ); 57 } // end method checkpalindrome 58 } // end class Palindrome 1 // Lab 2: PalindromeTest.java 2 // Test application for class Palindrome 3 public class PalindromeTest 5 public static void main( String args[] ) 6 { 7 Palindrome application = new Palindrome(); 8 application.checkpalindrome(); 9 } // end main 10 } // end class PalindromeTest Problem-Solving Tips 1. Determine the number of digits in the value input by the user and assign the result to digits. Use a while loop to determine whether the user input contains the proper number of digits. In the condition, determine whether digits is equal to five. If not, input a new value from the user and determine whether the new value contains the proper number of digits. When the number of digits is five, the loop should terminate. 2. Use division and remainder calculations to obtain the separate digits. For a five-digit number to be a palindrome, the first and fifth digits must be the same and the second and fourth digits must be the same. 3. Be sure to follow the spacing and indentation conventions mentioned in the text. 4. If you have any questions as you proceed, ask your lab instructor for assistance. Follow-Up Question and Activity 1. Modify the program to determine whether a seven-digit number is a palindrome. Solution 1 // Lab 2: Palindrome.java 2 // Program tests for a palindrome 3 import java.util.scanner; 4 5 public class Palindrome 6 { 7 // checks if a 5-digit number is a palindrome 8 public void checkpalindrome() 9 { 10 Scanner input = new Scanner( System.in ); int number; // user input number 13 int digit1; // first digit 14 int digit2; // second digit 15 int digit3; // third digit 16 int digit5; // fifth digit 17 int digit6; // sixth digit

37 Chapter 4 Control Statements: Part Lab Exercises Lab Exercise 2 Palindromes 18 int digit7; // seventh digit 19 int digits; // number of digits in input number = 0 ; 22 digits = 0 ; // Ask for a number until it is seven digits 25 while ( digits!= 7 ) 26 { 27 System.out.print( "Enter a 7-digit number: " ); 28 number = input.nextint(); if ( number < ) 31 { 32 if ( number > ) 33 digits = 7 ; 34 else 35 System.out.println( "Number must be 7 digits" ); 36 } // end if 37 else 38 System.out.println( "Number must be 7 digits" ); 39 } // end while loop // get the digits 42 digit1 = number / ; 43 digit2 = number % / ; 44 digit3 = number % / 10000; 45 digit5 = number % 1000 / 100; 46 digit6 = number % 100 / 10; 47 digit7 = number % 10; // print whether the number is a palindrome 50 System.out.print( number ); if ( digit1 == digit7 ) 53 { 54 if ( digit2 == digit6 ) 55 { 56 if ( digit3 == digit5 ) 57 System.out.println( " is a palindrome!!!" ); 58 else 59 System.out.println( " is not a palindrome." ); 60 } 61 else 62 System.out.println( " is not a palindrome." ); 63 } 64 else 65 System.out.println( " is not a palindrome." ); 66 } // end method checkpalindrome 67 } // end class Palindrome 1 // Lab 2: PalindromeTest.java 2 // Test application for class Palindrome 3 public class PalindromeTest 5 public static void main( String args[] ) 6 {

38 134 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 2 Palindromes 7 Palindrome application = new Palindrome(); 8 application.checkpalindrome(); 9 } // end main 10 } // end class PalindromeTest Enter a 7-digit number: is a palindrome!!! Enter a 7-digit number: is not a palindrome.

39 Chapter 4 Control Statements: Part Lab Exercises Lab Exercise 3 Largest Number Lab Exercise 3 Largest Number Date: Section: The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 4.5 and Fig. L 4.6) 5. Problem-Solving Tips 6. Follow-Up Question and Activity The program template represents a complete working Java program with one or more key lines of code replaced with comments. Read the problem description and examine the sample output, then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up question. The source code for the template is available at and Lab Objectives This lab was designed to reinforce programming concepts from Chapter 4 of Java How to Program: Seventh Edition. In this lab you will practice: Using while statements Using counter-controlled repetition Using if statements The follow-up question and activity also will give you practice: Using if else statements. Description of the Problem The process of finding the largest value (i.e., the maximum of a group of values) is used frequently in computer applications. For example, a program that determines the winner of a sales contest would input the number of units sold by each salesperson. The salesperson who sells the most units wins the contest. Write a pseudocode program and then a Java application that inputs a series of 10 integers and determines and prints the largest integer. Your program should use at least the following three variables: a) counter: A counter to count to 10 (i.e., to keep track of how many numbers have been input and to determine when all 10 numbers have been processed). b) number: The integer most recently input by the user. c) largest: The largest number found so far.

40 136 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 3 Largest Number Sample Output Enter number: 56 Enter number: -10 Enter number: 200 Enter number: 25 Enter number: 8 Enter number: 500 Enter number: -20 Enter number: 678 Enter number: 345 Enter number: 45 Largest number is 678 Program Template 1 // Lab 3: Largest.java 2 // Program determines and prints the largest of ten numbers. 3 import java.util.scanner; 4 5 public class Largest 6 { 7 // determine the largest of 10 numbers 8 public void determinelargest() 9 { 10 Scanner input = new Scanner( System.in ); int largest; // largest number 13 int number; // user input 14 int counter; // number of values entered /* write code to get the first integer and store it in variable largest */ /* write code to initialize the number of integers entered */ /* write code to loop until 10 numbers are entered */ /* write code to prompt the user to enter a number and read tat number */ /* write code to test whether the number entered is greater than the largest 25 if so, replace the value of largest with the entered number */ /* write code to increment the number of integers entered */ System.out.printf( "Largest number is %d\n", largest ); 30 } // end method determinelargest 31 } // end class Largest Fig. L 4.5 Largest.java

41 Chapter 4 Control Statements: Part Lab Exercises Lab Exercise 3 Largest Number 1 // Lab 3: LargestTest.java 2 // Test application for class Largest 3 public class LargestTest 5 public static void main( String args[] ) 6 { 7 Largest application = new Largest(); 8 application.determinelargest(); 9 } // end main 10 } // end class LargestTest Fig. L 4.6 LargestTest.java Problem-Solving Tips Solution 1. Remember to initialize the count of the number of integers entered. 2. Use an if statement to test whether the number input from the user is larger than the largest number you have stored. 3. Be sure to follow the spacing and indentation conventions mentioned in the text. 4. If you have any questions as you proceed, ask your lab instructor for assistance. 1 // Lab 3: Largest.java 2 // Program determines and prints the largest of ten numbers. 3 import java.util.scanner; 4 5 public class Largest 6 { 7 // determine the largest of 10 numbers 8 public void determinelargest() 9 { 10 Scanner input = new Scanner( System.in ); int largest; // largest number 13 int number; // user input 14 int counter; // number of values entered / / get first number and assign it to variable largest 17 System.out.print( "Enter number: " ); 18 largest = input.nextint(); counter = 1 ; // get rest of the numbers and find the largest 23 while ( counter < 10 ) 2 25 System.out.print( "Enter number: " ); 26 number = input.nextint(); if ( number > largest ) 29 largest = number; counter++; 32 } // end while loop

42 138 Control Statements: Part 1 Chapter4 Lab Exercises Lab Exercise 3 Largest Number System.out.printf( "Largest number is %d\n", largest ); 35 } // end method determinelargest 36 } // end class Largest 1 // Lab 3: LargestTest.java 2 // Test application for class Largest 3 public class LargestTest 5 public static void main( String args[] ) 6 { 7 Largest application = new Largest(); 8 application.determinelargest(); 9 } // end main 10 } // end class LargestTest Follow-Up Question and Activity 1. Modify the program to find the two largest values of the 10 values entered. Solution 1 // Lab 3: TwoLargest.java 2 // Program determines and prints the two largest of ten numbers. 3 import java.util.scanner; 4 5 public class TwoLargest 6 { 7 // determine the two largest of 10 integers 8 public void determinetwolargest() 9 { 10 Scanner input = new Scanner( System.in ); int largest; // largest number 13 int nextlargest; // second largest number 14 int number; // user input 15 int counter; // number of values entered // get first number and assign it to variable largest 18 System.out.print( "Enter number: " ); 19 largest = input.nextint(); // get second number and compare it with first number 22 System.out.print( "Enter number: " ); 23 number = input.nextint(); if ( number > largest ) 26 { 27 nextlargest = largest; 28 largest = number; 29 } // end if 30 else 31 nextlargest = number; 32

43 Chapter 4 Control Statements: Part Lab Exercises Lab Exercise 3 Largest Number 33 counter = 2 ; // get rest of the numbers and find the largest and nextlargest 36 while ( counter < 10 ) 37 { 38 System.out.print( "Enter number: " ); 39 number = input.nextint(); if ( number > largest ) { 42 nextlargest = largest; 43 largest = number; 44 } // end if 45 else if ( number > nextlargest ) 46 nextlargest = number; counter++; 49 } // end while loop System.out.printf( "Largest number is %d\nsecond largest number is %d\n", 52 largest, nextlargest ); 53 } // end method determinetwolargest 54 } // end class TwoLargest 1 // Lab 3: TwoLargestTest.java 2 // Test application for class TwoLargest 3 public class TwoLargestTest 5 public static void main( String args[] ) 6 { 7 TwoLargest application = new TwoLargest(); 8 application.determinetwolargest(); 9 } // end main 10 } // end class TwoLargestTest Enter number: 56 Enter number: -10 Enter number: 200 Enter number: 25 Enter number: 8 Enter number: 500 Enter number: -20 Enter number: 678 Enter number: 345 Enter number: 45 Largest number is 678

44

45 Chapter 4 Control Statements: Part Lab Exercises Debugging Debugging Date: Section: The program in this section does not run properly. Fix all the compilation errors, so that the program will compile successfully. Once the program compiles, compare the output to the sample output, and eliminate any logic errors that exist. The sample output demonstrates what the program s output should be once the program s code is corrected. The file is available at and at Sample Output 1 for Fahrenheit to Celsius 2 for Celsius to Fahrenheit 3 to quit: 1 Enter the degrees in Fahrenheit: 212 The temp in Celsius is for Fahrenheit to Celsius 2 for Celsius to Fahrenheit 3 to quit: 2 Enter the degrees in Celsius: 100 The temp in Fahrenheit is for Fahrenheit to Celsius 2 for Celsius to Fahrenheit 3 to quit: 3 Broken Code 1 // Chapter 4 of Java How To Program 2 // Debugging Problem 3 import java.util.scanner; 4 5 public class Temperature 6 { 7 public static void main( String args[] ) 8 { 9 int option; 10 int degree1; 11 int celsius1; 12 int fahrenheit1; Scanner input = new Scanner( System.in ); option = 0 ; 17 Fig. L 4.7 Temperature.java. (Part 1 of 2.)

46 142 Control Statements: Part 1 Chapter4 Lab Exercises Debugging 18 While ( option!= 3 ) System.out.printf( "%s\n%s\n%s\n", "1 for Fahrenheit to Celsius", 21 "2 for Celsius to Fahrenheit", "3 to quit:" ); 22 option = input.nextdouble(); System.out.println( "Enter the degrees in Fahrenheit: " ); 25 degree1 = input.nextdouble(); celsius1 = ( degree1-32 ) * 5 / 9 ; 28 System.out.printf( "The temp in Celsius is %d\n", celsius1 ); if ( option == 2 ); System.out.println( "Enter the degrees in Celsius: " ); 33 degree1 = input.nextdouble(); fahrenheit1 = ( degree1 * 9 / 5 ) + 32; 36 System.out.printf( "The temp in Fahrenheit is %d\n", fahrenheit1 ); 37 } // end while loop 38 } // end method Main 39 } // end class Temperature Fig. L 4.7 Temperature.java. (Part 2 of 2.) Solution 1 // Chapter 4 of Java How To Program 2 // Debugging Problem 3 import java.util.scanner; 4 5 public class Temperature 6 { 7 public static void main( String args[] ) 8 { 9 int option; 10 int degree1; 11 int celsius1; 12 int fahrenheit1; Scanner input = new Scanner( System.in ); option = 0 ; while ( option!= 3 ) 19 { 20 System.out.printf( "%s\n%s\n%s\n", "1 for Fahrenheit to Celsius", 21 "2 for Celsius to Fahrenheit", "3 to quit:" ); 22 option = input. nextint() ; if ( option == 1 ) { System.out.println( "Enter the degrees in Fahrenheit: " ); 27 degree1 = input. nextint() ; celsius1 = ( degree1-32 ) * 5 / 9 ; 30 System.out.printf( "The temp in Celsius is %d\n", celsius1 ); 31 }

47 Chapter 4 Control Statements: Part Lab Exercises Debugging 32 else if ( option == 2 ) 33 { 34 System.out.println( "Enter the degrees in Celsius: " ); 35 degree1 = input. nextint() ; fahrenheit1 = ( degree1 * 9 / 5 ) + 32; 38 System.out.printf( "The temp in Fahrenheit is %d\n", fahrenheit1 ); } } // end while loop 41 } // end method Main 42 } // end class Temperature List of Errors Keyword while is spelled with a an uppercase W on line 18, which is compilation error. The while statement is missing an opening brace on line 19. An if else statement testing for option equal to 1 is omitted. It has been added to line 24 and the else part has been added to the beginning of line 30. Opening (lines 23 and 31) and closing (lines 29 and 37) braces are left out in the if else statement which leads to either a compilation or logic error. The if statement (line 30) has a semicolon after the condition which leads to a logic error. The program should use Scanner method nextint instead of method nextdouble on lines 25 and 33 to input an integer from the user.

48

49 Chapter 4 Control Statements: Part Postlab Activities Coding Exercises Date: Section: These coding exercises reinforce the lessons learned in the lab and provide additional programming experience outside the classroom and laboratory environment. They serve as a review after you have successfully completed the Prelab Activities and Lab Exercises. For each of the following problems, write a program or a program segment that performs the specified action. 1. Write a Java application that inputs an integer and uses an if statement to determine whether the integer is even and, if it is, prints that number. 1 public class Test2 2 { 3 public static void main( String args[] ) 5 Scanner input = new Scanner( System.in ); 6 int number1; 7 8 System.out.print( "Enter an integer: " ); 9 number1 = input.nextint(); if ( number1 % 2 == 0 ) 12 System.out.println( number1 ); 13 } // end main 14 } // end class Test2 Enter an integer: Write a Java application that inputs an integer and uses an if else statement to determine whether the integer is odd or even. If it is odd, print the number followed by "is odd"; if it is even, print the number followed by "is even". 1 public class Test2 2 { 3 public static void main( String args[] ) 5 Scanner input = new Scanner( System.in ); 6 int number1; 7 8 System.out.print( "Enter an integer: " ); 9 number1 = input.nextint(); if ( number1 % 2 == 0 ) 12 System.out.printf( "%d is even\n", number1 ); 13 else 14 System.out.printf( "%d is odd\n", number1 ); 15 } // end main 16 } // end class Test2

### Introduction to Java Applications

2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

### Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

7 Arrays Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then

### Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M Control Structures Intro. Sequential execution Statements are normally executed one

### Introduction to Classes and Objects

3 Nothing can have value without being an object of utility. Karl Marx Your public servants serve you right. Adlai E. Stevenson Knowing how to answer one who speaks, To reply to one who sends a message.

### Arrays OBJECTIVES. In this chapter you will learn:

7 Arrays Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then

### [Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";

Page 1 of 10 [Page 177 (continued)] Exercises 4.11 Identify and correct the error(s) in each of the following: a. if ( age >= 65 ); cout

### AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

AL GHURAIR UNIVERSITY College of Computing CSC 209 JAVA I week 3- Control Statements: Part I Objectives: To use the if and if...else selection statements to choose among alternative actions. To use the

### AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

AL GHURAIR UNIVERSITY College of Computing CSC 209 JAVA I week 2- Arithmetic and Decision Making: Equality and Relational Operators Objectives: To use arithmetic operators. The precedence of arithmetic

2 Introduction to Java Applications: Solutions What s in a name? That which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would

### Introduction to Classes and Objects

3 Introduction to Classes and Objects OBJECTIVES In this chapter you will learn: What classes, objects, methods and instance variables are. How to declare a class and use it to create an object. How to

### Introduction to Java Applications

2 What s in a name? that which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the most fun? Peggy Walker Take some more

### Programming with Java

Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

### Control Statements. Musa M. Ameen Computer Engineering Dept.

2 Control Statements Musa M. Ameen Computer Engineering Dept. 1 OBJECTIVES In this chapter you will learn: To use basic problem-solving techniques. To develop algorithms through the process of topdown,

### 2.8. Decision Making: Equality and Relational Operators

Page 1 of 6 [Page 56] 2.8. Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. This section introduces a simple version of Java's if statement

### Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2

### 12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

### In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 2: Sentinel-Controlled Repetition In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability.

### COMP 202 Java in one week

CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

### Chapter 3 Structured Program Development

1 Chapter 3 Structured Program Development Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 - Structured Program Development Outline 3.1 Introduction

### Lab 2: Structured Program Development in C

Lab 2: Structured Program Development in C (Part A: Your first C programs - integers, arithmetic, decision making, Part B: basic problem-solving techniques, formulating algorithms) Learning Objectives

### Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M tutor Isam M. Al Jawarneh, PhD student isam.aljawarneh3@unibo.it Mobile Middleware

### Full file at

Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

1 7 JavaScript: Control Statements I 2 Let s all move one place on. Lewis Carroll The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert

### Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

### CS111: PROGRAMMING LANGUAGE II

1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

### Java Coding 3. Over & over again!

Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

### Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

Assoc. Prof. Dr. Marenglen Biba Before writing a program to solve a problem, have a thorough understanding of the problem and a carefully planned approach to solving it. Understand the types of building

### Fundamentals of Programming Session 7

Fundamentals of Programming Session 7 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

C How to Program, 6/e Before writing a program to solve a particular problem, it s essential to have a thorough understanding of the problem and a carefully planned approach to solving the problem. The

### CEN 414 Java Programming

CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang WEEK 2 ELEMENTARY PROGRAMMING 2 Computing the Area of a Circle public class ComputeArea

### Course Outline. Introduction to java

Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

### COMP 202. Java in one week

COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language

### o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Last Time Let s all Repeat Together 10/3/05 CS150 Introduction to Computer Science 1 1 We covered o Counter and sentinel controlled loops o Formatting output Today we will o Type casting o Top-down, stepwise

### 3 The L oop Control Structure

3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

### Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Chapter 5: Control Structures II Java Programming: Program Design Including Data Structures Chapter Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled,

### CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 5&6: Loops Lecture Contents Why loops?? While loops for loops do while loops Nested control structures Motivation Suppose that you need

### Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester

Lecture Notes 1. Comments a. /* */ b. // 2. Program Structures a. public class ComputeArea { public static void main(string[ ] args) { // input radius // compute area algorithm // output area Actions to

### Introduction to Java Unit 1. Using BlueJ to Write Programs

Introduction to Java Unit 1. Using BlueJ to Write Programs 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

### Structured Program Development in C

1 3 Structured Program Development in C 3.2 Algorithms 2 Computing problems All can be solved by executing a series of actions in a specific order Algorithm: procedure in terms of Actions to be executed

### Elementary Programming

Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal

### Structured Program Development

Structured Program Development Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline Introduction The selection statement if if.else switch The

### Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM Let s get some practice creating programs that repeat commands inside of a loop in order to accomplish a particular task. You may

### LEC03: Decisions and Iterations

LEC03: Decisions and Iterations Q1. Identify and correct the errors in each of the following statements: a) if ( c < 7 ); System.out.println( "c is less than 7" ); b) if ( c => 7 ) System.out.println(

### Instructor: Eng.Omar Al-Nahal

Faculty of Engineering & Information Technology Software Engineering Department Computer Science [2] Lab 6: Introduction in arrays Declaring and Creating Arrays Multidimensional Arrays Instructor: Eng.Omar

### 2.5 Another Application: Adding Integers

2.5 Another Application: Adding Integers 47 Lines 9 10 represent only one statement. Java allows large statements to be split over many lines. We indent line 10 to indicate that it s a continuation of

### CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

CSE123 LECTURE 3-1 Program Design and Control Structures Repetitions (Loops) 1-1 The Essentials of Repetition Loop Group of instructions computer executes repeatedly while some condition remains true Counter-controlled

### AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

### Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of

Basic Problem solving Techniques Top Down stepwise refinement If & if.. While.. Counter controlled and sentinel controlled repetition Usage of Assignment increment & decrement operators 1 ECE 161 WEEK

### Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will

### Fundamentals of Programming Data Types & Methods

Fundamentals of Programming Data Types & Methods By Budditha Hettige Overview Summary (Previous Lesson) Java Data types Default values Variables Input data from keyboard Display results Methods Operators

### Chapter 3 Structured Program Development in C Part II

Chapter 3 Structured Program Development in C Part II C How to Program, 8/e, GE 2016 Pearson Education, Ltd. All rights reserved. 1 3.7 The while Iteration Statement An iteration statement (also called

### Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition 5.2 Q1: Counter-controlled repetition requires a. A control variable and initial value. b. A control variable

### Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #3

### AP Computer Science Unit 1. Programs

AP Computer Science Unit 1. Programs Open DrJava. Under the File menu click on New Java Class and the window to the right should appear. Fill in the information as shown and click OK. This code is generated

### Section 2.2 Your First Program in Java: Printing a Line of Text

Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two

### Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Chapter 4 Lab Loops and Files Lab Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write an do-while loop Be able to write a for loop

### AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

### Chapter 2. Elementary Programming

Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,

### Object-Oriented Programming

Object-Oriented Programming Java Syntax Program Structure Variables and basic data types. Industry standard naming conventions. Java syntax and coding conventions If Then Else Case statements Looping (for,

### CS141 Programming Assignment #6

CS141 Programming Assignment #6 Due Sunday, Nov 18th. 1) Write a class with methods to do the following output: a) 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 b) 1 2 3 4 5 4 3 2 1 1 2 3 4 * 4 3 2 1 1 2 3 * * * 3 2 1

### COMP 202 Java in one week

COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

### Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()

### Chapter Goals. Contents LOOPS

CHAPTER 4 LOOPS Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30, 2011 Chapter Goals To implement while, for, and do loops To hand-trace the execution of a program To become familiar with common

### Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional

### Full file at

Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

### Chapter 3. Selections

Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

### COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 Announcements Midterm Exams on 4 th of June (12:35 14:35) Room allocation will be announced soon

### Repe\$\$on CSC 121 Spring 2017 Howard Rosenthal

Repe\$\$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

### St. Edmund Preparatory High School Brooklyn, NY

AP Computer Science Mr. A. Pinnavaia Summer Assignment St. Edmund Preparatory High School Name: I know it has been about 7 months since you last thought about programming. It s ok. I wouldn t want to think

### Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 45 Obtained Marks:

كلية الحاسبات وتقنية المعلوما Exam 1 Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: October 18, 2015 Student Name: Student ID: Total Marks: 45 Obtained Marks: Instructions: Do not open this

### Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

### Object Oriented Programming. Java-Lecture 1

Object Oriented Programming Java-Lecture 1 Standard output System.out is known as the standard output object Methods to display text onto the standard output System.out.print prints text onto the screen

### Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks:

Mid Term Exam 1 Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Student Name: Total Marks: 50 Obtained Marks: Instructions: Do not open this exam booklet until you

### Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

### PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

PRIMITIVE VARIABLES CS302 Introduction to Programming University of Wisconsin Madison Lecture 3 By Matthew Bernstein matthewb@cs.wisc.edu Variables A variable is a storage location in your computer Each

### COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 Announcements Slides will be posted before the class. There might be few

### JavaScript: Control Statements I

7 JavaScript: Control Statements I OBJECTIVES In this chapter you will learn: Basic problem-solving techniques. To develop algorithms through the process of top-down, stepwise refinement. To use the if

Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All for repetition statement do while repetition statement switch multiple-selection statement break statement continue statement Logical

### Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

### Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Lab 4 Functions Introduction: A function : is a collection of statements that are grouped together to perform an operation. The following is its format: type name ( parameter1, parameter2,...) { statements

### Introduction to the Java Basics: Control Flow Statements

Lesson 3: Introduction to the Java Basics: Control Flow Statements Repetition Structures THEORY Variable Assignment You can only assign a value to a variable that is consistent with the variable s declared

### REPETITION CONTROL STRUCTURE LOGO

CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

### Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Program Development Java Program Statements Selim Aksoy Bilkent University Department of Computer Engineering saksoy@cs.bilkent.edu.tr The creation of software involves four basic activities: establishing

### CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

### Introduction to Java Applications; Input/Output and Operators

www.thestudycampus.com Introduction to Java Applications; Input/Output and Operators 2.1 Introduction 2.2 Your First Program in Java: Printing a Line of Text 2.3 Modifying Your First Java Program 2.4 Displaying

### Repe\$\$on CSC 121 Fall 2015 Howard Rosenthal

Repe\$\$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

### Example: Monte Carlo Simulation 1

Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149

### Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1 Motivation In the programs we have written thus far, statements are executed one after the other, in the order in which they appear. Programs often

### Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

كلية الحاسبات وتقنية المعلوما Exam 2 Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: November 22, 2015 Student Name: Student ID: Total Marks: 40 Obtained Marks: Instructions: Do not open this

### Unit 1 Lesson 4. Introduction to Control Statements

Unit 1 Lesson 4 Introduction to Control Statements Essential Question: How are control loops used to alter the execution flow of a program? Lesson 4: Introduction to Control Statements Objectives: Use

### Data Conversion & Scanner Class

Data Conversion & Scanner Class Quick review of last lecture August 29, 2007 ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor: Alexander Stoytchev Numeric Primitive Data Storing

### 4 WORKING WITH DATA TYPES AND OPERATIONS

WORKING WITH NUMERIC VALUES 27 4 WORKING WITH DATA TYPES AND OPERATIONS WORKING WITH NUMERIC VALUES This application will declare and display numeric values. To declare and display an integer value in

### Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

### CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

CSE101-lec#12 Designing Structured Programs Introduction to Functions Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Designing structured programs in C: Counter-controlled repetition