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

Size: px
Start display at page:

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

Transcription

1 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 stop. Lewis Carroll OBJECTIVES In this chapter you will learn: What arrays are. To use arrays to store data in and retrieve data from lists and tables of values. To declare an array, initialize an array and refer to individual elements of an array. To use the enhanced for statement to iterate through arrays. To pass arrays to methods. To declare and manipulate multidimensional arrays. To write methods that use variable-length argument lists. To read command-line arguments into a program.

2 Chapter 7 Arrays 3 Assignment Checklist Date: Section: Exercises Assigned: Circle assignments Date Due Prelab Activities Matching YES NO Fill in the Blank 13, 14, 15, 16, 17, 18, 19, 20, 21 Short Answer 22, 23, 24, 25, 26 Programming Output 27, 28, 29, 30, 31, 32 Correct the Code 33, 34, 35, 36, 37, 38 Lab Exercises Exercise 1 Duplicate Elimination YES NO Follow-Up Questions and Activities 1, 2, 3 Exercise 2 Craps Game YES NO Debugging YES NO Labs Provided by Instructor Postlab Activities Coding Exercises 1, 2, 3, 4, 5, 6 Programming Challenges 1, 2

3 Chapter 7 Arrays 5 Prelab Activities Matching Date: Section: After reading Chapter 7 of Java How to Program: Sixth Edition, answer the given questions. The questions are intended to test and reinforce your understanding of key concepts. You may answer the questions before or during the lab. For each term in the left column, write the letter for the description from the right column that best matches the term. Term 1. pass by value 2. a[ i ][ j ] 3. index 4. new int[ 12 ] pass by reference 7. array 8. enhanced for statement 9. int c[] 10. tables of values 11. length 12. command-line arguments Description a) Indicates that a method receives a variable number of arguments. b) Declares an array of type int. c) A collection of variables that contain values of the same type. d) Iterates through an array without using a counter. e) Information passed to an application when it executes. f) A copy of the argument s value is made and passed to the called method. g) Represented by an array with two dimensions. h) A calling method gives a called method the ability to access and potentially modify the caller s data directly. i) One element of an array with two dimensions. j) Specifies a particular element in an array. k) Creates an array of integers. l) An array member that contains the number of elements in an array.

4 Chapter 7 Arrays 7 Prelab Activities Fill in the Blank Fill in the Blank Date: Section: Fill in the blanks for each of the following statements: 13. Every array has a(n) member that specifies the number of elements in the array. 14. When an argument is, a copy of the argument s value is made and passed to the called method. 15. To pass an array to a method, you must specify the of the array as an argument in the method call. 16. An array may be an integer or an integer expression. 17. The first element in every array has index. 18. A(n) argument list is treated as an array within the method declaration s body. 19. Arrays are entities they remain the same length once they are created. 20. must be initialized before they are used and cannot be modified thereafter. 21. To pass one row of a two-dimensional array to a method that receives a one-dimensional array, you specify the array s followed by only the.

5 Chapter 7 Arrays 9 Prelab Activities Short Answer Short Answer Date: Section: Answer the following questions in the space provided. Your answers should be as concise as possible; aim for two or three sentences. 22. What is an off-by-one error? 23. What benefits does the enhanced for statement provide for array processing? What are its limitations? 24. Why are command-line arguments passed to the main method as Strings? What problems would arise if command-line arguments were passed using an array of doubles?

6 10 Arrays Chapter 7 Prelab Activities Short Answer 25. Describe how two-dimensional arrays represent a table of data. 26. Differentiate between pass-by-value and pass-by-reference.

7 Chapter 7 Arrays 11 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.] Unless specified otherwise, for the following questions assume that the code segments are contained within the main method of a Java application. 27. What is the output of the following code segment? 1 int array[] = { 8, 6, 9, 7, 6, 4, 4, 5, 8, 10 }; 2 System.out.println( "Index Value" ); 3 4 for ( int i = 0 ; i < array.length; i++ ) 5 System.out.printf( "%d %d\n", i, array[ i ] ); Your answer: 28. What is the output of the following code segment? 1 char sentence[] = { 'H', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u' }; 2 String output = " The sentence is: "; 3 4 for ( int i = 0 ; i < sentence.length; i++ ) 5 System.out.printf( "%c ", sentence[ i ] ); 6 7 System.out.println(); Your answer:

8 12 Arrays Chapter 7 Prelab Activities Programming Output 29. What is the output of the following code segment? 1 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 2 3 for ( int i = 0 ; i < array.length; i++ ) 4 { 5 for ( int j = 0 ; j < array [ i ]; j++ ) 6 System.out.print( "*" ); 7 8 System.out.println(); 9 } Your answer: 30. What is the output of the following code segment? 1 int array[] = { 3, 2, 5 }; 2 3 for ( int i = 0 ; i < 3 ; i++ ) 4 array[ i ] *= 2 ; 5 6 for ( int j : array ) 7 System.out.print( "%d ", j ); 8 9 System.out.println(); Your answer:

9 Chapter 7 Arrays 13 Prelab Activities Programming Output Given the following declaration of a method 1 public int method1( int... values ) 2 { 3 int mystery = 1 ; 4 5 for ( int i : values ) 6 mystery *= i; 7 8 return mystery; 9 } 31. What is the output of the following code segment? 1 System.out.println( method1( 1, 2, 3, 4, 5 ) ); Your answer: Given the following declaration of a method 1 public int method1( int values[][] ) 2 { 3 int mystery = 1 ; 4 5 for ( int i[] : values ) 6 for ( int j : i ) 7 mystery *= j; 8 9 return mystery; 10 } 32. What is the output of the following code segment? 1 int array[][] = { { 3, 2, 5 }, { 2, 2, 4, 5, 6 }, { 1, 1 } }; 2 3 System.out.println( mystery( array ) );

10 14 Arrays Chapter 7 Prelab Activities Programming Output Your answer:

11 Chapter 7 Arrays 15 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.] 33. The following code segment should assign 8 to the element of integer array with index array( 10 ) = 8 ; Your answer: 34. The for statement that follows should initialize all of array s elements to int array[] = new int [ 10 ]; 2 3 for ( int i = 0 ; i < 9 ; i++ ) 4 array[ i ] = -1; Your answer:

12 16 Arrays Chapter 7 Prelab Activities Correct the Code 35. Array a should contain all the integers from 0 through 10, inclusive. 1 int a[] = new int [ 10 ]; 2 3 for ( int i = 0 ; i < 10 ; i++ ) 4 a[ i ] = i; Your answer: 36. The following code segment should allocate two arrays containing five and six elements, respectively. 1 final int arraysize = 5 ; 2 3 int a[] = new int [ arraysize ]; 4 5 arraysize = 6 ; 6 7 int b[] = new int [ arraysize ]; Your answer:

13 Chapter 7 Arrays 17 Prelab Activities Correct the Code 37. The following code segment should initialize a two-dimensional array, then print its values. 1 int a[][] = new int [ 10 ][ 5 ]; 2 3 for ( int i = 0 ; i < a.length; i++ ) 4 for ( int j = 0 ; j < a[ i ].length; j++ ) 5 a[ j ][ i ] = j; 6 7 for ( int i = 0 ; i < a.length; i++ ) 8 { 9 for ( int j = 0 ; j < a[ i ].length; j++ ) 10 System.out.printf( "%d ", a[ j ][ i ] ); System.out.println(); 13 } Your answer: 38. The following code segment should assign the value 10 to the array element that corresponds to the third row and the fourth column. 1 int a[] = new int [ 10 ][ 5 ]; 2 3 a[ 2 ][ 3 ] = 10 ; Your answer:

14 Chapter 7 Arrays 19 Lab Exercises Lab Exercise 1 Duplicate Elimination Date: Section: This 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 Problem 3. Sample Output 4. Program Template (Fig. L 7.1 and Fig. L 7.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 7 of Java How to Program: Sixth Edition. In this lab, you will practice: Declaring and initializing arrays. Comparing input to array elements. Preventing array out-of-bounds errors. The follow-up questions and activities will also give you practice: Initializing array sizes during program execution. Generalizing programs. Problem Description Use a one-dimensional array to solve the following problem: Write an application that inputs five numbers, each of which is between 10 and 100, inclusive. As each number is read, display it only if it is not a duplicate of a number already read. Provide for the worst case, in which all five numbers are different. Use the smallest possible array to solve this problem. Display the complete set of unique values input after the user inputs each new value.

15 20 Arrays Chapter 7 Lab Exercises Lab Exercise 1 Duplicate Elimination Sample Output Enter number: Enter number: Enter number: Enter number: has already been entered Enter number: Program Template 1 // Lab 1: Unique.java 2 // Reads in 5 unique numbers. 3 import java.util.scanner; 4 5 public class Unique 6 { 7 // gets 5 unique numbers from the user 8 public void getnumbers() 9 { 10 Scanner input = new Scanner( System.in ); /* Create an array of five elements*/ 13 int count = 0 ; // number of uniques read 14 int entered = 0 ; // number of entered numbers while( entered < numbers.length ) 17 { 18 System.out.print( "Enter number: " ); 19 /* Write code here to retrieve the input from the user */ // validate the input 22 /* Write an if statement that validates the input */ 23 { 24 // flags whether this number already exists 25 boolean containsnumber = false ; // increment number of entered numbers 28 entered++; /* Compare the user input to the unique numbers in the array using a for 31 statement. If the number is unique, store new number */ /* add the user input to the array only if the number is not already 34 in the array */ 35 if (!containsnumber ) 36 { 37 /* Write code to add the number to the array and increment 38 unique items input */ 39 } // end if Fig. L 7.1 Unique.java. (Part 1 of 2.)

16 Chapter 7 Arrays 21 Lab Exercises Lab Exercise 1 Duplicate Elimination 40 else 41 System.out.printf( "%d has already been entered\n", 42 number ); 43 } // end if 44 else 45 System.out.println( "number must be between 10 and 100" ); // print the list of unique values 48 /* Write code to output the contents of the array */ 49 } // end while 50 } // end method getnumbers 51 } // end class Unique Fig. L 7.1 Unique.java. (Part 2 of 2.) 1 // Lab 1: UniqueTest.java 2 // Test application for class Unique 3 public class UniqueTest 4 { 5 public static void main( String args[] ) 6 { 7 Unique application = new Unique(); 8 application.getnumbers(); 9 } // end main 10 } // end class UniqueTest Fig. L 7.2 UniqueTest.java. Problem-Solving Tips 1. Initialize the integer array numbers to hold five elements. This is the maximum number of values the program must store if all values input are unique. 2. Remember to validate the input and display an error message if the user inputs invalid data. 3. If the number entered is not unique, display a message to the user; otherwise, store the number in the array and display the list of unique numbers entered so far. 4. If you have any questions as you proceed, ask your lab instructor for assistance. Follow-Up Questions and Activities 1. Modify the program in Lab Exercise 1 to input 30 numbers, each of which is between 10 to 500, inclusive. 2. Modify the program in Follow-Up Question 1 to allow the user to enter numbers until the array is full. 3. Modify your solution to Follow-Up Question 2 to allow the user to enter the size of the array as the application begins execution.

17 Chapter 7 Arrays 23 Lab Exercises Lab Exercise 2 Craps Game Lab Exercise 2 Craps Game Date: Section: This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into five parts: 1. Lab Objectives 2. Description of Problem 3. Sample Output 4. Program Template (Fig. L 7.3 and Fig. L 7.4) 5. Problem-Solving Tips 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. The source code for the template is available at and Lab Objectives This lab was designed to reinforce programming concepts from Chapter 7 of Java How to Program: Sixth Edition. In this lab you will practice: Declaring and initializing arrays. Using arrays to store sets of data. Problem Description Write an application that runs 1000 games of craps and answers the following questions: a) How many games are won on the first roll, second roll,, twentieth roll and after the twentieth roll? b) How many games are lost on the first roll, second roll,, twentieth roll and after the twentieth roll? c) What are the chances of winning at craps? [ Note: You should discover that craps is one of the fairest casino games. What do you suppose this means?] d) What is the average length of a game of craps?

18 24 Arrays Chapter 7 Lab Exercises Lab Exercise 2 Craps Game Sample Output 224 games won and 99 games lost on roll #1 74 games won and 119 games lost on roll #2 50 games won and 96 games lost on roll #3 33 games won and 54 games lost on roll #4 23 games won and 47 games lost on roll #5 22 games won and 37 games lost on roll #6 18 games won and 13 games lost on roll #7 8 games won and 18 games lost on roll #8 7 games won and 14 games lost on roll #9 5 games won and 6 games lost on roll #10 5 games won and 6 games lost on roll #11 4 games won and 3 games lost on roll #12 1 games won and 3 games lost on roll #13 1 games won and 0 games lost on roll #14 0 games won and 4 games lost on roll #15 1 games won and 0 games lost on roll #16 0 games won and 0 games lost on roll #17 0 games won and 1 games lost on roll #18 0 games won and 0 games lost on roll #19 0 games won and 0 games lost on roll #20 3 games won and 1 games lost on rolls after the 20th roll The chances of winning are 479 / 1000 = 47.90% The average game length is 3.37 rolls. Program Template 1 // Lab 2: Craps.java 2 // Program plays 1000 games of craps and displays winning 3 // and losing statistics. 4 import java.util.random; 5 6 public class Craps 7 { 8 // create random number generator for use in method rolldice 9 private Random randomnumbers = new Random(); // enumeration with constants that represent the game status 12 private enum Status { CONTINUE, WON, LOST }; /* Declare array to store the number of games won by number of rolls in the game */ 15 /* Declare array to store the number of games lost by number of rolls in the game */ 16 int winsum = 0 ; // total number of wins 17 int losesum = 0 ; // total number of losses // plays one game of craps 20 public void play() 21 { 22 int sumofdice = 0 ; // sum of the dice 23 int mypoint = 0 ; // point if no win or loss on first roll 24 Fig. L 7.3 Craps.java. (Part 1 of 3.)

19 Chapter 7 Arrays 25 Lab Exercises Lab Exercise 2 Craps Game 25 Status gamestatus; // can contain CONTINUE, WON or LOST int roll; // number of rolls for the current game /* Create the array to store the number of games won */ 30 /* Create the array to store the number of games lost */ for ( int i = 1 ; i <= 1000; i++ ) 33 { 34 sumofdice = rolldice(); // first roll of the dice 35 roll = 1 ; // determine game status and point based on sumofdice 38 switch ( sumofdice ) 39 { 40 case 7 : // win with 7 on first roll 41 case 11: // win with 11 on first roll 42 gamestatus = Status.WON; 43 break ; 44 case 2 : // lose with 2 on first roll 45 case 3 : // lose with 3 on first roll 46 case 12 : // lose with 12 on first roll 47 gamestatus = Status.LOST; 48 break ; 49 default : // did not win or lose, so remember point 50 gamestatus = Status.CONTINUE; // game is not over 51 mypoint = sumofdice; // store the point 52 break ; // optional for default case at end of switch 53 } // end switch // while game is not complete while ( gamestatus == Status.CONTINUE ) 57 { 58 sumofdice = rolldice(); // roll dice again 59 roll++; // determine game status 62 if ( sumofdice == mypoint ) // win by making point 63 gamestatus = Status.WON; 64 else if ( sumofdice == 7 ) // lose by rolling 7 65 gamestatus = Status.LOST; 66 } // end while // all roll results after 20th roll placed in last element 69 /* Write an if statement to test whether the number of rolls is greater than and, if true, set number of rolls to 21 */ // increment number of wins in that roll 73 if ( gamestatus == Status.WON ) 74 { 75 /* Write code to increment the number of games won for a 76 specific number of rolls */ 77 /* Write code to increment the overall number of games won */ 78 } // end if 79 else // increment number of losses in that roll 80 { Fig. L 7.3 Craps.java. (Part 2 of 3.)

20 26 Arrays Chapter 7 Lab Exercises Lab Exercise 2 Craps Game 81 /* Write code to increment the number of games lost for a 82 specific number of rolls */ 83 /* Write code to increment the overall number of games lost */ 84 } // end else 85 } // end for printstats(); 88 } // end method play // print win/loss statistics 91 public void printstats() 92 { 93 int totalgames = winsum + losesum; // total number of games 94 int length = 0 ; // total length of the games // display number of wins and losses on all rolls 97 for ( int i = 1 ; i <= 21 ; i++ ) 98 { 99 /* Write an if statement to test whether i is equal to 21 */ 100 /* Output number of games won and lost after the 20th roll */ 101 else 102 /* Output number of games won and lost after each roll less than 20 */ // calculate total number of rolls to win/lose all games 105 // add number of wins by number of rolls needed to win 106 // add number of losses by number of rolls needed to lose 107 /* Write code to calculate total length of games */ 108 } // end for // calculate chances of winning 111 System.out.printf( "\n%s %d / %d = %.2f%%\n", 112 "The chances of winning are", winsum, totalgames, 113 ( * winsum / totalgames ) ); System.out.printf( "The average game length is %.2f rolls.\n", 117 ( ( double ) length / totalgames ) ); 118 } // end method printstats // roll dice, calculate sum and display results 121 public int rolldice() 122 { 123 // pick random die values 124 int die1 = 1 + randomnumbers.nextint( 6 ); 125 int die2 = 1 + randomnumbers.nextint( 6 ); 126 int sum = die1 + die2; // sum die values return sum; // return sum of dice 129 } // end method rolldice 130 } // end class Craps Fig. L 7.3 Craps.java. (Part 3 of 3.)

21 Chapter 7 Arrays 27 Lab Exercises Lab Exercise 2 Craps Game 1 // Lab 2: CrapsTest.java 2 // Test application for class Craps 3 public class CrapsTest 4 { 5 public static void main( String args[] ) 6 { 7 Craps game = new Craps(); 8 game.play(); 9 } // end main 10 } // end class CrapsTest Fig. L 7.4 CrapsTest.java Problem-Solving Tips 1. The arrays to hold the number of wins and losses by number of rolls should have 22 elements. We are keeping track of the number of wins and losses decided on the first through twentieth roll along with games decided after the twentieth roll. That requires 21 elements. The extra element is because arrays begin with element zero. This element will not hold any information in the program. 2. To calculate the total number of rolls, multiply each index in the arrays by the value of that element in the array. 3. If you have any questions as you proceed, ask your lab instructor for assistance.

22 Chapter 7 Arrays 29 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 Enter sales person number (-1 to end): 1 Enter product number: 4 Enter sales amount: 1082 Enter sales person number (-1 to end): 2 Enter product number: 3 Enter sales amount: 998 Enter sales person number (-1 to end): 3 Enter product number: 1 Enter sales amount: 678 Enter sales person number (-1 to end): 4 Enter product number: 1 Enter sales amount: 1554 Enter sales person number (-1 to end): -1 Product Salesperson 1 Salesperson 2 Salesperson 3 Salesperson 4 Total Total Broken Code 1 // Debugging Problem Chapter 7: Sales2.java 2 // Program totals sales for salespeople and products. 3 import java.util.scanner; 4 5 public class Sales2 6 { 7 public void calculatesales() 8 { 9 Scanner input = new Scanner( System.in ); 10 // sales array holds data on number of each product sold 11 // by each salesman 12 double sales = new double[ 5 ][ 4 ]; System.out.print( "Enter sales person number (-1 to end): " ); 15 int person = input.nextint(); Fig. L 7.5 Sales2.java. (Part 1 of 2.)

23 30 Arrays Chapter 7 Lab Exercises Debugging while ( person!= -1 ) 18 { 19 System.out.print( "Enter product number: " ); 20 int product = input.next(); 21 System.out.print( "Enter sales amount: " ); 22 double amount = input.nextdouble(); // error-check the input 25 if ( person < 1 && person > 5 && 26 product >= 1 && product < 6 && amount >= 0 ) 27 sales[ product - 1 ][ person - 1 ] += amount; 28 else 29 System.out.println( "Invalid input!" ); System.out.print( "Enter sales person number (-1 to end): " ); 32 person = input.nextint(); 33 } // end while // total for each salesperson 36 double salespersontotal[][] = new double[ 4 ]; // display the table 39 for ( int column = 0 ; column < 4 ; column++ ) 40 salespersontotal[ column ][ row ] = 0 ; System.out.printf( "%7s%14s%14s%14s%14s%10s\n", 43 "Product", "Salesperson 1", "Salesperson 2", 44 "Salesperson 3", "Salesperson 4", "Total" ); // for each column of each row, print the appropriate 47 // value representing a person's sales of a product 48 for ( int row = 0 ; row < 5 ; row++ ) 49 { 50 double producttotal = 0.0 ; 51 System.out.printf( "%7d", ( row + 1 ) ); for ( int column = 0 ; column < 4 ; column++ ) { 54 System.out.printf( "%14.2f", sales[ column ][ row ] ); 55 producttotal += sales[ column ][ row ]; 56 salespersontotal[ column ] += sales[ column ][ row ]; 57 } // end for System.out.printf( "%10.2f\n", producttotal ); 60 } // end for System.out.printf( "%7s", "Total" ); for ( int column = 0 ; column < 4 ; column++ ) 65 System.out.printf( "%14.2f", salespersontotal[ column ] ); System.out.println(); 68 } // end method calculatesales 69 } // end class Sales2 Fig. L 7.5 Sales2.java. (Part 2 of 2.)

24 Chapter 7 Arrays 31 Lab Exercises Debugging 1 // Debugging Problem Chapter 7: Sales2Test.java 2 // Test application for class Sales2 3 public class Sales2Test 4 { 5 public static void main( String args[] ) 6 { 7 Sales2 application = new Sales2(); 8 application.calculatesales(); 9 } // end main 10 } // end class Sales2Test Fig. L 7.6 Sales2Test.java

25 Chapter 7 Arrays 33 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 line of code that declares and creates a 100-element array of int s. 2. Initialize all the elements in the array of Coding Exercise 1 to Write a line of code that accesses the seventh element of the array in Coding Exercise 2 and sets its value to 7.

26 34 Arrays Chapter 7 Postlab Activities Coding Exercises 4. Write a method printarray that displays the contents of the array created in Coding Exercise 1. Assume that the method receives array1 as an argument in a method call. Display the contents of the array with each number separated by a space. In addition, start a new line after every 20 elements. 5. Create a char array and use an array initializer to initialize the array with the characters in the string "Hi there". Display the contents of the array using a for statement. Separate each character in the array with a space. 6. Write a for statement that prints only "Hi" from the array you created in Coding Exercise 5.

27 Chapter 7 Arrays 35 Postlab Activities Programming Challenges Programming Challenges Date: Section: The Programming Challenges are more involved than the Coding Exercises and may require a significant amount of time to complete. Write a Java program for each of the problems in this section. The answers to these problems are available at and Pseudocode, hints or sample outputs are provided for each problem to aid you in your programming. 1. ( Dice Rolling) Write an application to simulate the rolling of two dice. The application should use an object of class Random once to roll the first die and again to roll the second die. The sum of the two values should then be calculated. Each die can show an integer value from 1 to 6, so the sum of the values will vary from 2 to 12, with 7 being the most frequent sum and 2 and 12 being the least frequent sums. Figure L 7.7 shows the 36 possible combinations of the two dice. Your application should roll the dice 36,000 times. Use a onedimensional array to keep track of the number of times each possible sum appears. Display the results in tabular format. Determine whether the totals are reasonable (e.g., there are six ways to roll a 7, so approximately one-sixth of the rolls should be 7) Fig. L 7.7 The 36 possible outcomes of rolling two dice. Hints: Keep track of how many times each total (2 through 12) occurs. This total is used to calculate the percentage of the time that each total occurs. Define a loop that iterates 36,000 times. During each iteration, roll the dice, calculate the total and update the count for the particular total in the array. Create an array large enough that you can use the sum of the dice as the index into the array.

28 36 Arrays Chapter 7 Postlab Activities Programming Challenges Your output should appear as follows: Sum Frequency Percentage (Airline Reservations System) A small airline has just purchased a computer for its new automated reservations system. You have been asked to develop the new system. You are to write an application to assign seats on each flight of the airline s only plane (capacity: 10 seats). Your application should display the following alternatives: Please type 1 for First Class and Please type 2for Economy. If the user types 1, your application should assign a seat in the first-class section (seats 1 5). If the user types 2, your application should assign a seat in the economy section (seats 6 10). Your application should then display a boarding pass indicating the person s seat number and whether it is in the first-class or economy section of the plane. Use a one-dimensional array of primitive type boolean to represent the seating chart of the plane. Initialize all the elements of the array to false to indicate that all the seats are empty. As each seat is assigned, set the corresponding elements of the array to true to indicate that the seat is no longer available. Your application should never assign a seat that has already been assigned. When the economy section is full, your application should ask the person if it is acceptable to be placed in the first-class section (and vice versa). If yes, make the appropriate seat assignment. If no, display the message "Next flight leaves in Hints: 3hours." Use an array of boolean s to represent the seats on the airplane. Use int s to keep track of the next available seat for each of the seat types.

29 Chapter 7 Arrays 37 Postlab Activities Programming Challenges Your output should appear as follows: Please type 1 for First Class Please type 2 for Economy choice: 1 First Class. Seat #1 Please type 1 for First Class Please type 2 for Economy choice: 2 Economy Class. Seat #6... Please type 1 for First Class Please type 2 for Economy choice: 1 First Class is full, Economy Class? 1. Yes, 2. No. Your choice: 1 Economy Class. Seat #7

Arrays OBJECTIVES. In this chapter you will learn:

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

More information

Arrays OBJECTIVES. In this chapter you will learn:

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

More information

Control Statements: Part 1

Control Statements: Part 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

More information

Introduction to Java Applications

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

More information

Introduction to Classes and Objects

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.

More information

COMP 110 Programming Exercise: Simulation of the Game of Craps

COMP 110 Programming Exercise: Simulation of the Game of Craps COMP 110 Programming Exercise: Simulation of the Game of Craps Craps is a game of chance played by rolling two dice for a series of rolls and placing bets on the outcomes. The background on probability,

More information

Introduction to Classes and Objects

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

More information

Instructor: Eng.Omar Al-Nahal

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

More information

Methods: A Deeper Look

Methods: A Deeper Look www.thestudycampus.com Methods: A Deeper Look 6.1 Introduction 6.2 Program Modules in Java 6.3 static Methods, static Fields and ClassMath 6.4 Declaring Methods with Multiple Parameters 6.5 Notes on Declaring

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

Methods: A Deeper Look Pearson Education, Inc. All rights reserved.

Methods: A Deeper Look Pearson Education, Inc. All rights reserved. 1 6 Methods: A Deeper Look 2 The greatest invention of the nineteenth century was the invention of the method of invention. Alfred North Whitehead Call me Ishmael. Herman Melville When you call me that,

More information

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly

More information

Object Oriented Programming. Java-Lecture 6 - Arrays

Object Oriented Programming. Java-Lecture 6 - Arrays Object Oriented Programming Java-Lecture 6 - Arrays Arrays Arrays are data structures consisting of related data items of the same type In Java arrays are objects -> they are considered reference types

More information

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times } Rolling a Six-Sided Die face = 1 + randomnumbers.nextint( 6 ); The argument 6 called the scaling factor represents the number of unique values that nextint should produce (0 5) This is called scaling

More information

EAS230: Programming for Engineers Lab 1 Fall 2004

EAS230: Programming for Engineers Lab 1 Fall 2004 Lab1: Introduction Visual C++ Objective The objective of this lab is to teach students: To work with the Microsoft Visual C++ 6.0 environment (referred to as VC++). C++ program structure and basic input

More information

Function Call Stack and Activation Records

Function Call Stack and Activation Records 71 Function Call Stack and Activation Records To understand how C performs function calls, we first need to consider a data structure (i.e., collection of related data items) known as a stack. Students

More information

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

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

More information

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Outline 12.1 Test-Driving the Craps Game Application 12.2 Random Number Generation 12.3 Using an enum in the Craps

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

More information

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. Functions Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 5.1 Introduction 5.3 Math Library Functions 5.4 Functions 5.5

More information

RANDOM NUMBER GAME PROJECT

RANDOM NUMBER GAME PROJECT Random Number Game RANDOM NUMBER GAME - Now it is time to put all your new knowledge to the test. You are going to build a random number game. - The game needs to generate a random number between 1 and

More information

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous Assignment 3 Methods Review CSC 123 Fall 2018 Notes: All homework must be submitted via e-mail. All parts of assignment must be submitted in a single e-mail with multiple attachments when required. Notes:

More information

CSE123. Program Design and Modular Programming Functions 1-1

CSE123. Program Design and Modular Programming Functions 1-1 CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.

More information

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. 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

More information

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved. Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create

More information

2.8. Decision Making: Equality and Relational Operators

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

More information

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips Lab6 Array I Objectivities 1. Using rand to generate random numbers and using srand to seed the random-number generator. 2. Declaring, initializing and referencing arrays. 3. The follow-up questions and

More information

Programming with Java

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

More information

Midterm Examination (MTA)

Midterm Examination (MTA) M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and

More information

Introduction to the Java Basics: Control Flow 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

More information

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18 Assignment Lecture 9 Logical Operations Formatted Print Printf Increment and decrement Read through 3.9, 3.10 Read 4.1. 4.2, 4.3 Go through checkpoint exercise 4.1 Logical Operations - Motivation Logical

More information

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 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

More information

JAVASCRIPT LESSON 4: FUNCTIONS

JAVASCRIPT LESSON 4: FUNCTIONS JAVASCRIPT LESSON 4: FUNCTIONS 11.1 Introductio n Programs that solve realworld programs More complex than programs from previous chapters Best way to develop & maintain large program: Construct from small,

More information

Q5. What values are stored in the array at the comment in main? Note that the incrementall returns void, but does take an int[] parameter.

Q5. What values are stored in the array at the comment in main? Note that the incrementall returns void, but does take an int[] parameter. Q1. Which of the following choices is the correct syntax for declaring/initializing an array of integers? 1. int[] a = new int[10]; 2. int a[10] = new int[10]; 3. []int a = [10]int; 4. int a[10]; 5. int[10]

More information

Final Exam. COMP Summer I June 26, points

Final Exam. COMP Summer I June 26, points Final Exam COMP 14-090 Summer I 2000 June 26, 2000 200 points 1. Closed book and closed notes. No outside material allowed. 2. Write all answers on the test itself. Do not write any answers in a blue book

More information

Fundamentals of Programming Session 25

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

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

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.

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

More information

STUDENT LESSON A14 Boolean Algebra and Loop Boundaries

STUDENT LESSON A14 Boolean Algebra and Loop Boundaries STUDENT LESSON A14 Boolean Algebra and Loop Boundaries Java Curriculum for AP Computer Science, Student Lesson A14 1 STUDENT LESSON A14 Boolean Algebra and Loop Boundaries INTRODUCTION: Conditional loops

More information

Introduction to Java Applications

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

More information

Introduction to Computer Science Unit 4B. Programs: Classes and Objects

Introduction to Computer Science Unit 4B. Programs: Classes and Objects Introduction to Computer Science Unit 4B. Programs: Classes and Objects This section must be updated to work with repl.it 1. Copy the Box class and compile it. But you won t be able to run it because it

More information

Introduction to Java Programs for Packet #4: Classes and Objects

Introduction to Java Programs for Packet #4: Classes and Objects Introduction to Java Programs for Packet #4: Classes and Objects Note. All of these programs involve writing and using more than one class file. 1. Copy the Box class and compile it. But you won t be able

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

download instant at

download instant at 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

More information

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question Page 1 of 6 Template no.: A Course Name: Computer Programming1 Course ID: Exam Duration: 2 Hours Exam Time: Exam Date: Final Exam 1'st Semester Student no. in the list: Exam pages: Student's Name: Student

More information

Assignment 2.4: Loops

Assignment 2.4: Loops Writing Programs that Use the Terminal 0. Writing to the Terminal Assignment 2.4: Loops In this project, we will be sending our answers to the terminal for the user to see. To write numbers and text to

More information

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen CSCI 136 Data Structures & Advanced Programming Fall 2018 Instructors Bill Lenhart & Bill Jannen Administrative Details Lab 1 handout is online Prelab (should be completed before lab): Lab 1 design doc

More information

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module

More information

Introduction to Java & Fundamental Data Types

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

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

More information

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

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

More information

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING INPUT AND OUTPUT Input devices Keyboard Mouse Hard drive Network Digital camera Microphone Output devices.

More information

Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program.

Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program. 1 Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program. public class Welcome1 // main method begins execution of Java application System.out.println( "Welcome to Java Programming!" ); } //

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

Chapter 9 Introduction to Arrays. Fundamentals of Java

Chapter 9 Introduction to Arrays. Fundamentals of Java Chapter 9 Introduction to Arrays Objectives Write programs that handle collections of similar items. Declare array variables and instantiate array objects. Manipulate arrays with loops, including the enhanced

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University 9/5/6 CS Introduction to Computing II Wayne Snyder Department Boston University Today: Arrays (D and D) Methods Program structure Fields vs local variables Next time: Program structure continued: Classes

More information

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Review what an array is Review how to declare arrays Review what reference variables are Review how to pass arrays to methods Review

More information

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS These are sample pages from Kari Laitinen s book "A Natural Introduction to Computer Programming with Java". For more information, please visit http://www.naturalprogramming.com/javabook.html CHAPTER 5

More information

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 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

More information

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

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

More information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

More information

Manipulating One-dimensional Arrays

Manipulating One-dimensional Arrays Manipulating One-dimensional Arrays Mitsu Ogihara Department of Computer Science University of Miami 1 / 30 Table of Contents 1 For each 2 Exchanging Values 3 Reversing 2 / 30 For-each iteration For enumerating

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

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 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

More information

Introduction to Software Development (ISD) Week 3

Introduction to Software Development (ISD) Week 3 Introduction to Software Development (ISD) Week 3 Autumn term 2012 Aims of Week 3 To learn about while, for, and do loops To understand and use nested loops To implement programs that read and process

More information

Programming Assignment #4 Arrays and Pointers

Programming Assignment #4 Arrays and Pointers CS-2301, System Programming for Non-majors, B-term 2013 Project 4 (30 points) Assigned: Tuesday, November 19, 2013 Due: Tuesday, November 26, Noon Abstract Programming Assignment #4 Arrays and Pointers

More information

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper

More information

Chapter Goals. Contents LOOPS

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

More information

Introduction to Computer Science Unit 3. Programs

Introduction to Computer Science Unit 3. Programs Introduction to Computer Science Unit 3. Programs This section must be updated to work with repl.it Programs 1 to 4 require you to use the mod, %, operator. 1. Let the user enter an integer. Your program

More information

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal Repetition CSC 121 Fall 2014 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

More information

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm CIS 110 Introduction To Computer Programming February 29, 2012 Midterm Name: Recitation # (e.g. 201): Pennkey (e.g. bjbrown): My signature below certifies that I have complied with the University of Pennsylvania

More information

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) In this lecture, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of

More information

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals Arrays Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals Can we solve this problem? Consider the following program

More information

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

6.5 Function Prototypes and Argument Coercion

6.5 Function Prototypes and Argument Coercion 6.5 Function Prototypes and Argument Coercion 32 Function prototype Also called a function declaration Indicates to the compiler: Name of the function Type of data returned by the function Parameters the

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A

More information

Full file at

Full file at Chapter 2 Introduction to Java Applications Section 2.1 Introduction ( none ) Section 2.2 First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler

More information

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

More information

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

CS111: PROGRAMMING LANGUAGE II

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

More information

Due Date: Two Program Demonstrations (Testing and Debugging): End of Lab

Due Date: Two Program Demonstrations (Testing and Debugging): End of Lab CSC 111 Fall 2005 Lab 6: Methods and Debugging Due Date: Two Program Demonstrations (Testing and Debugging): End of Lab Documented GameMethods file and Corrected HighLow game: Uploaded by midnight of lab

More information

Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen)

Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen) Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen) 1 Lesson 9: Introduction Objectives: To Arrays Write programs that handle collections of similar items. Declare

More information

Computer Science is...

Computer Science is... Computer Science is... Machine Learning Machine learning is the study of computer algorithms that improve automatically through experience. Example: develop adaptive strategies for the control of epileptic

More information

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes Entry Point of Execution: the main Method Elementary Programming EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG For now, all your programming exercises will be defined within the

More information

University of Massachusetts Amherst, Electrical and Computer Engineering

University of Massachusetts Amherst, Electrical and Computer Engineering University of Massachusetts Amherst, Electrical and Computer Engineering ECE 122 Midterm Exam 1 Makeup Answer key March 2, 2018 Instructions: Closed book, Calculators allowed; Duration:120 minutes; Write

More information

Object-Oriented Programming

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,

More information

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 Announcements Check the calendar on the course webpage regularly for updates on tutorials and office hours.

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number Generation

More information

Comp 170 Test 1 SAMPLE June 8, 2000

Comp 170 Test 1 SAMPLE June 8, 2000 Dr. John G. Del Greco Comp 170 Test 1 SAMPLE June 8, 2000 Name Instructions. There are no special instructions for this sample test. 1. True or False? (a) (b) (c) (d) type int. The integer data type long

More information

LAB: WHILE LOOPS IN C++

LAB: WHILE LOOPS IN C++ LAB: WHILE LOOPS IN C++ MODULE 2 JEFFREY A. STONE and TRICIA K. CLARK COPYRIGHT 2014 VERSION 4.0 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 2 Introduction This lab will provide students with an introduction

More information

Repetition, Looping. While Loop

Repetition, Looping. While Loop Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

More information

More non-primitive types Lesson 06

More non-primitive types Lesson 06 CSC110 2.0 Object Oriented Programming Ms. Gnanakanthi Makalanda Dept. of Computer Science University of Sri Jayewardenepura More non-primitive types Lesson 06 1 2 Outline 1. Two-dimensional arrays 2.

More information

Chapter 6 - Methods Prentice Hall. All rights reserved.

Chapter 6 - Methods Prentice Hall. All rights reserved. Chapter 6 - Methods 1 Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math Class Methods 6.4 Methods 6.5 Method Definitions 6.6 Argument Promotion 6.7 Java API Packages 6.8 Random-Number Generation

More information

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice CONTENTS: Arrays Strings COMP-202 Unit 5: Loops in Practice Computing the mean of several numbers Suppose we want to write a program which asks the user to enter several numbers and then computes the average

More information

Java Coding 3. Over & over again!

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

More information

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++ Chapter 3 - Functions 1 Chapter 3 - Functions 2 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3. Functions 3.5 Function Definitions 3.6 Function Prototypes 3. Header Files 3.8

More information

Final Exam Practice. Partial credit will be awarded.

Final Exam Practice. Partial credit will be awarded. Please note that this problem set is intended for practice, and does not fully represent the entire scope covered in the final exam, neither the range of the types of problems that may be included in the

More information

Chapter 3 Lab Decision Structures

Chapter 3 Lab Decision Structures Chapter 3 Lab Decision Structures Lab Objectives Be able to construct boolean expressions to evaluate a given condition Be able to compare String objects Be able to use a flag Be able to construct if and

More information

Classwork 7: Craps. N. Duong & R. Rodriguez, Java Crash Course January 6, 2015

Classwork 7: Craps. N. Duong & R. Rodriguez, Java Crash Course January 6, 2015 Classwork 7: Craps N. Duong & R. Rodriguez, Java Crash Course January 6, 2015 For this classwork, you will be writing code for the game Craps. For those of you who do not know, Craps is a dice-rolling

More information