SlideShare a Scribd company logo
1 of 31
CPCS 203                                                                                   Lab sheet 1
Student Name:_____________________________                                                 Section:__




                                King Abdulaziz University
                     Faculty of Computing and Information Systems
                                 Spring Term 2012/1433

Course Code: CPCS-203                      Course Name: Programming II
______________________________________________________________________

                                           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.
CPCS 203                                                                                  Lab sheet 1
Student Name:_____________________________                                                Section:__

Prelab Activity:

                                           Matching
The questions are intended to test and reinforce your understanding of key concepts. You may
answer the questions before the lab.

For each term in the left column, write the letter for the description from the right column that
best matches theterm.

          Term                                                       Description

_1. pass by value                                  a) Indicates that a method receives a variable
                                                   number
                                                   of arguments.

_2. a[ i ][ j ]                                    b) Declares an array of type int.

_3. index                                          c) A collection of variables that contain values
                                                   of thesame type.

_4. new int[ 12 ]                                  d) Iterates through an array without using a
                                                   counter.

_5. ...                                            e) Information passed to an application when it
                                                   executes.

_6. pass by reference                              f) A copy of the argument’s value is made and
                                                   passedto the called method.

_7. array                                          g) Represented by an array with two
                                                   dimensions.

_8. enhanced for statement                         h) A calling method gives a called method the
                                                   ability to access and potentially modify the
                                                   caller’s data directly.

_9. int c[]                                        i) One element of an array with two
                                                   dimensions.

_10. tables of values                              j) Specifies a particular element in an array.

_11. length                                        k) Creates an array of integers.

_12. command-line arguments                        l) An array member that contains the number
                                                   of elements in an array.
CPCS 203                                                                             Lab sheet 1
Student Name:_____________________________                                           Section:__

Prelab Activity:

                                     Fill in the Blank

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 specifythe array’s ________ followed by only the row ________




Prelab Activity:
CPCS 203                                                                             Lab sheet 1
Student Name:_____________________________                                           Section:__

                                     Short Answers
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 ifcommand-line arguments were passed using an array of doubles?




25. Describe how two-dimensional arrays represent a table of data.




26. Differentiate between pass-by-value and pass-by-reference.




Prelab Activity:
CPCS 203                                                                                Lab sheet 1
Student Name:_____________________________                                              Section:__

                                                 Program Output
For each of the given program segments, read the code, and write the output in the space
provided below eachprogram. [Note: Do not execute these programs on a computer.]
Unless specified otherwise, for the following questions assume that the code segments are
contained within themain 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 ( inti = 0; i < array.length; i++ )
       5 System.out.printf("%d %dn", 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 ( inti = 0; i < sentence.length; i++ )
       5 System.out.printf("%c ", sentence[ i ] );
       6
       7 System.out.println();

Your answer:




29. What is the output of the following code segment?

       1 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
CPCS 203                                                   Lab sheet 1
Student Name:_____________________________                 Section:__

       2
       3 for ( inti = 0; i < array.length; i++ )
       4{
       5 for ( intj = 0; j < array [ i ]; j++ )
       6 System.out.print("*" );
       7
       8System.out.println();
       9}

Your answer:




30. What is the output of the following code segment?

       1 int array[] = { 3, 2, 5 };
       2
       3 for ( inti = 0; i <3; i++ )
       4 array[ i ] *= 2;
       5
       6for ( intj : array )
       7 System.out.print("%d ", j );
       8
       9System.out.println();

Your answer:




Given the following declaration of a method

       1 public int method1(int... values )
       2{
       3 int mystery = 1;
       4
       5for ( inti : values )
       6 mystery *= i;
       7
       8return mystery;
       9}

31. What is the output of the following code segment?
       1 System.out.println( method1( 1, 2, 3, 4, 5 ) );

Your answer:
CPCS 203                                                                         Lab sheet 1
Student Name:_____________________________                                       Section:__




Given the following declaration of a method

               1 public int method1(int values[][] )
               2{
               3 int mystery = 1;
               4
               5for ( inti[] : values )
               6 for ( intj : i )
               7 mystery *= j;
               8
               9return 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
               3System.out.println( mystery( array ) );

Your answer:




Prelab Activity:
CPCS 203                                                                                 Lab sheet 1
Student Name:_____________________________                                               Section:__

                                            Correct the Code
Determine if there is an error in each of the following program segments. If there is an error,
specify whether itis a logic error or a compilation error, circle the error in the program and write
the corrected code in the spaceprovided after each problem. If the code does not contain an error,
write “no error.” [Note: There may be morethan one error in each program segment.]

33. The following code segment should assign 8 to the element of integer array with index 10.

               1 array(10 ) = 8;

Your answer:




34. The forstatement that follows should initialize all of array’s elements to -1.

               1 int array[] = new int[ 10 ];
               2
               3 for ( inti = 0; i <9; i++ )
               4 array[ i ] = -1;

Your answer:




35. Array a should contain all the integers from 0 through 10, inclusive.

               1 int a[] = new int[ 10 ];
CPCS 203                                                                               Lab sheet 1
Student Name:_____________________________                                             Section:__

               2
               3 for ( inti = 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
               5arraySize = 6;
               6
               7 int b[] = new int[ arraySize ];

Your answer:




37. The following code segment should initialize a two-dimensional array, then print its values.

               1 int a[][] = new int[ 10 ][ 5 ];
CPCS 203                                                                             Lab sheet 1
Student Name:_____________________________                                           Section:__

               2
               3 for ( inti = 0; i < a.length; i++ )
               4 for ( intj = 0; j < a[ i ].length; j++ )
               5 a[ j ][ i ] = j;
               6
               7 for ( inti = 0; i < a.length; i++ )
               8{
               9 for ( intj = 0; j < a[ i ].length; j++ )
               10 System.out.printf("%d ", a[ j ][ i ] );
               11
               12 System.out.println();
               13 }

Your answer:




38. The following code segment should assign the value 10 to the array element that corresponds
    to the thirdrow and the fourth column.

               1 int a[] = new int[ 10 ][ 5 ];
               2
               3 a[2 ][ 3 ] = 10;

Your answer:




Lab Exercises:
CPCS 203                                                                                Lab sheet 1
Student Name:_____________________________                                              Section:__

                  Lab Exercise 1 — Duplicate Elimination


This problem is intended to be solved in a closed-lab session with a teaching assistant or
instructor present. Theproblem is divided into six parts:
1. Lab Objectives
2. Description of Problem
3. Sample Output
4. Program Template (Figure 1: )
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 replacedwith 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 thesource code for the template is available at www.pearsonhighered.com/deitel


Lab Objectives
In thislab, 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.


Description of the Problem
Use a one-dimensional array to solve the following problem: Write an application that inputs five
numbers, eachof which is between 10 and 100, inclusive. As each number is read, display it only
if it is not a duplicate of a numberalready read. Provide for the “worst case,” in which all five
numbers are different. Use the smallest possiblearray to solve this problem. Display the complete
set of unique values input after the user inputs each new value.




Sample Output

 Enter number: 11
 11
 Enter number: 85
 11 85
 Enter number: 26
 11 85 26
 Enter number: 11
 11 has already been entered
CPCS 203                                                                                   Lab sheet 1
Student Name:_____________________________                                                 Section:__




Program Template
              1 // Lab 1: Unique.java
              2 // Reads in 5 unique numbers.
              3 import java.util.Scanner;
              4
              5 public classUniqueTest
              6{
              7 public static void main( String args[] )
              8{
              9         getNumbers();
              11} // end main
              12
              13// gets 5 unique numbers from the user
              14public void getNumbers()
              15 {
              16Scanner input = new Scanner( System.in );
              17
              18/* Create an array of five elements*/
              19int count = 0; // number of uniques read
              20int entered = 0; // number of entered numbers
              21
              22while( entered < numbers.length )
              23{
              24        System.out.print("Enter number: " );
              25        /* Write code here to retrieve the input from the user */
              26
              27        // validate the input
              28        /* Write an if statement that validates the input */
              29        {
              30        // flags whether this number already exists
              31                  booleancontainsNumber = false;
              32
              33                  // increment number of entered numbers
              34                  entered++;
              35
              36/* Compare the user input to the unique numbers in the array using a for
              37statement. If the number is unique, store new number */
              38
              39/* add the user input to the array only if the number is not already
              40in the array */
              41if ( !containsNumber )
CPCS 203                                                                              Lab sheet 1
Student Name:_____________________________                                            Section:__

                42{
                43/* Write code to add the number to the array and increment
                44unique items input */
                45}// end if
                46else
                47System.out.printf("%d has already been enteredn",
                48number );
                49}// end if
                50else
                51System.out.println("number must be between 10 and 100" );
                52
                53// print the list of unique values
                54/* Write code to output the contents of the array */
                55}// end while
                56}// end method getNumbers
                57}// end class UniqueTest

Figure 1: Unique.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.
CPCS 203                                                                                Lab sheet 1
Student Name:_____________________________                                              Section:__




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.




Lab Exercises:

                          Lab Exercise 2 — Craps Game
This problem is intended to be solved in a closed-lab session with a teaching assistant or
instructor present. Theproblem is divided into five parts:
    1. Lab Objectives
    2. Description of Problem
CPCS 203                                                                             Lab sheet 1
Student Name:_____________________________                                           Section:__

   3. Sample Output
   4. Program Template (Figure 2)
   5. Problem-Solving Tips

The program template represents a complete working Java program, with one or more key lines
of code replacedwith 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 theprogram. Compare your output with the sample output provided. The source code
for the template is availableat www.pearsonhighered.com/deitel


Lab Objectives
In thislab you will practice:
        Declaring and initializing arrays.
        Using arrays to store sets of data.


Description of the Problem
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?




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
CPCS 203                                                                                    Lab sheet 1
Student Name:_____________________________                                                  Section:__




Program Template
              1 // Lab 2: CrapsTest.java
              2 // Program plays 1000 games of craps and displays winning
              3 // and losing statistics.
              4 import java.util.Random;
              5
              6public classCrapsTest
              7{
              8public static void main( String args[] )
              9{
              10       // create random number generator for use in method rollDice
              11       private static Random randomNumbers = new Random();
              12
              13       // enumeration with constants that represent the game status
              14       private enum Status { CONTINUE, WON, LOST };
              15
              16       /* Declare array to store the number of games won by number of rolls in the
              17       game */
              18       /* Declare array to store the number of games lost by number of rolls in the game
              19       */
              20       int winSum = 0; // total number of wins
              21       int loseSum = 0; // total number of losses
              22
              23       // plays one game of craps
              24       `play();
              25}// end main
              26
              27
              28public void play()
              29{
              30int sumOfDice = 0; // sum of the dice
              31int myPoint = 0; // point if no win or loss on first roll
              32
              33Status gameStatus; // can contain CONTINUE, WON or LOST
              34
              35int roll; // number of rolls for the current game
              36
              37/* Create the array to store the number of games won */
CPCS 203                                                                                       Lab sheet 1
Student Name:_____________________________                                                     Section:__

              38/* Create the array to store the number of games lost */
              39
              40for ( inti = 1; i <= 1000; i++ )
              41{
              42sumOfDice = rollDice(); // first roll of the dice
              43roll = 1;
              44
              45// determine game status and point based on sumOfDice
              46switch ( sumOfDice )
              47{
              48case 7: // win with 7 on first roll
              49case 11: // win with 11 on first roll
              50gameStatus = Status.WON;
              51break;
              52case 2: // lose with 2 on first roll
              53case 3: // lose with 3 on first roll
              54case 12: // lose with 12 on first roll
              55gameStatus = Status.LOST;
              56break;
              57default: // did not win or lose, so remember point
              58gameStatus = Status.CONTINUE; // game is not over
              59myPoint = sumOfDice; // store the point
              60break; // optional for default case at end of switch
              61}// end switch
              62
              63// while game is not complete ...
              64while ( gameStatus == Status.CONTINUE )
              65{
              66sumOfDice = rollDice(); // roll dice again
              67roll++;
              68
              69// determine game status
              70if ( sumOfDice == myPoint ) // win by making point
              71gameStatus = Status.WON;
              72else if ( sumOfDice == 7 ) // lose by rolling 7
              73gameStatus = Status.LOST;
              74}// end while
              75
              76// all roll results after 20th roll placed in last element
              77/* Write an if statement to test whether the number of rolls is greater than
              7821 and, if true, set number of rolls to 21 */
              79
              80// increment number of wins in that roll
              81if ( gameStatus == Status.WON )
              82{
              83/* Write code to increment the number of games won for a
              84specific number of rolls */
              85/* Write code to increment the overall number of games won */
              86}// end if
              87else // increment number of losses in that roll
              88{
              89/* Write code to increment the number of games lost for a
              90specific number of rolls */
              91/* Write code to increment the overall number of games lost */
              92}// end else
              93}// end for
CPCS 203                                                                                  Lab sheet 1
Student Name:_____________________________                                                Section:__

              94
              95printStats();
              96}// end method play
              97
              98// print win/loss statistics
              99public void printStats()
              100{
              101int totalGames = winSum + loseSum; // total number of games
              102int length = 0; // total length of the games
              103
              104// display number of wins and losses on all rolls
              105for ( inti = 1; i <= 21; i++ )
              106{
              107/* Write an if statement to test whether i is equal to 21 */
              108/* Output number of games won and lost after the 20th roll */
              109else
              110/* Output number of games won and lost after each roll less than 20 */
              111
              112// calculate total number of rolls to win/lose all games
              113// add number of wins by number of rolls needed to win
              114// add number of losses by number of rolls needed to lose
              115/* Write code to calculate total length of games */
              116}// end for
              117
              118// calculate chances of winning
              119System.out.printf("n%s %d / %d = %.2f%%n",
              120"The chances of winning are", winSum, totalGames,
              121( 100.0* winSum / totalGames ) );
              122
              123
              124System.out.printf("The average game length is %.2f rolls.n",
              125( (double ) length / totalGames ) );
              126}// end method printStats
              127
              128// roll dice, calculate sum and display results
              129public int rollDice()
              130{
              131// pick random die values
              132int die1 = 1 + randomNumbers.nextInt(6 );
              133int die2 = 1 + randomNumbers.nextInt(6 );
              134int sum = die1 + die2; // sum die values
              135
              136return sum; // return sum of dice
              137}// end method rollDice
              138} // end class CrapsTest




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.
CPCS 203                                                                               Lab sheet 1
Student Name:_____________________________                                             Section:__

   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.




Lab Exercises:

                                         Debugging
The program in this section does not run properly. Fix all the compilation errors, so that the
program will compilesuccessfully. Once the program compiles, compare the output to the sample
output, and eliminate any logicerrors that exist. The sample output demonstrates what the
CPCS 203                                                                                  Lab sheet 1
Student Name:_____________________________                                                Section:__

program’s output should be once the program’s codeis corrected. The file is available at
www.deitel.com/books/jhtp8/ and at www.pearsonhighered.com/deitel.



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
 1         0.00      0.00     678.00 1554.00 2232.00
 2         0.00      0.00     0.00       0.00   0.00
 3         0.00      998.00 0.00         0.00   998.00
 4         1082.00 0.00       0.00       0.00   1082.00
 5         0.00      0.00     0.00       0.00   0.00
 Total     1082.00 998.00 678.00 1554.00




Broken Code
                 1 // Debugging Problem Chapter 7: Sales2.java
                 2 // Program totals sales for salespeople and products.
                 3 import java.util.Scanner;
                 4
                 5// Debugging Problem Chapter 7: Sales2Test.java
                 6// Test application for class Sales2
                 7public classSales2Test
                 8{
                 9public static void main( String args[] )
                 10{
                 11       calculateSales();
                 12}// end main
                 13
                 14       Scanner input = new Scanner( System.in );
                 15       // sales array holds data on number of each product sold
                 16       // by each salesman
                 17       double sales = new double[5 ][ 4 ];
                 18
                 19       System.out.print("Enter sales person number (-1 to end): " );
                 20       int person = input.nextInt();
                 21
                 22       while ( person != -1 )
                 23       {
                 24       System.out.print("Enter product number: " );
CPCS 203                                                                                  Lab sheet 1
Student Name:_____________________________                                                Section:__

              25       int product = input.next();
              26       System.out.print("Enter sales amount: " );
              27       double amount = input.nextDouble();
              28
              29       // error-check the input
              30       if ( person<1 && person >5 &&
              31       product >= 1 && product <6 && amount >= 0 )
              32                  sales[ product - 1 ][ person - 1 ] += amount;
              33       else
              34                  System.out.println("Invalid input!" );
              35
              36       System.out.print("Enter sales person number (-1 to end): " );
              37       person = input.nextInt();
              38       } // end while
              39
              40       // total for each salesperson
              41       double salesPersonTotal[][] = new double[ 4 ];
              42
              43       // display the table
              44       for ( intcolumn = 0; column <4; column++ )
              45       salesPersonTotal[ column ][ row ] = 0;
              46
              47       System.out.printf("%7s%14s%14s%14s%14s%10sn",
              48       "Product", "Salesperson 1", "Salesperson 2",
              49       "Salesperson 3", "Salesperson 4", "Total" );
              50
              51       // for each column of each row, print the appropriate
              52       // value representing a person's sales of a product
              53       for ( introw = 0; row <5; row++ )
              54       {
              55                  double productTotal = 0.0;
              56                  System.out.printf("%7d", ( row + 1 ) );
              57
              58                  for ( intcolumn = 0; column <4; column++ ) {
              59                  System.out.printf("%14.2f", sales[ column ][ row ] );
              60                  productTotal += sales[ column ][ row ];
              61                  salesPersonTotal[ column ] += sales[ column ][ row ];
              62       } // end for
              63
              64       System.out.printf("%10.2fn", productTotal );
              65} // end for
              66
              67System.out.printf("%7s", "Total" );
              68
              69for ( intcolumn = 0; column <4; column++ )
              70System.out.printf("%14.2f", salesPersonTotal[ column ] );
              71
              72System.out.println();
              73}// end method calculateSales
              64}// end class Sales2Test
CPCS 203                                                      Lab sheet 1
Student Name:_____________________________                    Section:__




Postlab Activities


Topics
                                             Lab Exercises

One-Dimensional Arrays                       Tracking Sales
CPCS 203                                                                               Lab sheet 1
Student Name:_____________________________                                             Section:__

                                                  Grading Quizzes
                                                  Reversing an Array
                                                  Adding To and Removing From an Integer List

Command Line Arguments                            Averaging Numbers

Variable Length Parameter Lists                   Exploring Variable Length Parameter Lists

Two-Dimensional Arrays                            Matrix Inverse




                                   Coding Exercise 1
                                        Tracking Sales
File Sales.java contains a Java program that prompts for and reads in the sales for each of 5
salespeople in a company. It thenprints out the id and amount of sales for each salesperson and
the total sales. Study the code, then compile and run theprogram to see how it works. Now
modify the program as follows:
1. Compute and print the average sale. (You can compute this directly from the total; no loop is
    necessary.)
2. Find and print the maximum sale. Print both the id of the salesperson with the max sale and
    the amount of the sale, e.g., “Salesperson 3 had the highest sale with $4500.” Note that you
    don’t need another loop for this; you can do it in the same loop where the values are read and
    the sum is computed.
3. Do the same for the minimum sale.
4. After the list, sum, average, max and min have been printed; ask the user to enter a value.
    Then print the id of each salesperson who exceeded that amount, and the amount of their
    sales. Also print the total number of salespeople whose sales exceeded the value entered.
5. The salespeople are objecting to having an id of 0—no one wants that designation. Modify
    your program so that the ids run from 1-5 instead of 0-4. Do not modify the array—just
    make the information for salesperson 1 resides in array location 0, and so on.
6. Instead of always reading in 5 sales amounts, at the beginning ask the user for the number of
    sales people and then createan array that is just the right size. The program can then proceed
    as before.

// ***************************************************************
// Sales.java
//
// Reads in and stores sales for each of 5 salespeople. Displays
// sales entered by salesperson id and total sales for all salespeople.
//
// ***************************************************************
import java.util.Scanner;
public class Sales
CPCS 203                                                                Lab sheet 1
Student Name:_____________________________                              Section:__

{
public static void main(String[] args)
    {
final int SALESPEOPLE = 5;
int[] sales = new int[SALESPEOPLE];
int sum;
      Scanner scan = new Scanner(System.in);
for (int i=0; i<sales.length; i++)
       {
         System.out.print("Enter sales for salesperson " + i + ": ");
         sales[i] = scan.nextInt();
       }
System.out.println("nSalesperson Sales");
System.out.println(" ------------------ ");
sum = 0;
for (int i=0; i<sales.length; i++)
       {
         System.out.println(" " + i + " " + sales[i]);
         sum += sales[i];
       }
System.out.println("nTotal sales: " + sum);
  }
}




Postlab Activities

                                  Coding Exercise 2
                                      Grading Quizzes
Write a program that grades arithmetic quizzes as follows:
CPCS 203                                                                              Lab sheet 1
Student Name:_____________________________                                            Section:__

1. Ask the user how many questions are in the quiz.
2. Ask the user to enter the key (that is, the correct answers). There should be one answer for
   each question in the quiz, and each answer should be an integer. They can be entered on a
   single line, e.g., 34 7 13 100 81 3 9 10 321 12 might be the key for a 10-question quiz. You
   will need to store the key in an array.
3. Ask the user to enter the answers for the quiz to be graded. As for the key, these can be
   entered on a single line. Again there needs to be one for each question. Note that these
   answers do not need to be stored; each answer can simply be compared to the key as it is
   entered.
4. When the user has entered all of the answers to be graded, print the number correct and the
   percent correct.

When this works, add a loop so that the user can grade any number of quizzes with a single key.
After the results have been printed for each quiz, ask “Grade another quiz? (y/n).”




Postlab Activities

                                   Coding Exercise 3
                                    Reversing an Array
CPCS 203                                                                                Lab sheet 1
Student Name:_____________________________                                              Section:__

Write a program that prompts the user for an integer, and then asks the user to enter that many
values. Store these values in anarray and print the array. Then reverse the array elements so that
the first element becomes the last element, the secondelement becomes the second to last
element, and so on, with the old last element now first. Do not just reverse the order inwhich
they are printed; actually change the way they are stored in the array. Do not create a second
array; just rearrange theelements within the array you have. (Hint: Swap elements that need to
change places.) When the elements have beenreversed, print the array again.




Postlab Activities

                                   Coding Exercise 4

                                     Averaging Numbers
CPCS 203                                                                                Lab sheet 1
Student Name:_____________________________                                              Section:__

When you run a Java program called Foo, anything typed on the command lineafter “java Foo”
is passed to the main method in the args parameter as an array of strings.
1. Write a program Average.java that just prints the strings that it is given at the command line,
    one per line. If nothingis given at the command line, print “No arguments”.
2. Modify your program so that it assumes the arguments given at the command line are
    integers. If there are noarguments, print a message. If there is at least one argument, compute
    and print the average of the arguments. Notethat you will need to use the parseInt method of
    the Integer class to extract integer values from the strings that arepassed in. If any non-
    integer values are passed in, your program will produce an error, which is unavoidable at
    thispoint.




Postlab Activities

                                   Coding Exercise 5
                      Exploring Variable Length Parameter Lists
CPCS 203                                                                                  Lab sheet 1
Student Name:_____________________________                                                Section:__

The file Parameters.java contains a program to test the variable length method average from
Section 7.5 of the text. Notethat average must be a static method since it is called from the static
method main.
1. Compile and run the program. You must use the -source 1.5 option in your compile
    command.
2. Add a call to find the average of a single integer, say 13. Print the result of the call.
3. Add a call with an empty parameter list and print the result. Is the behavior what you
    expected?
4. Add an interactive part to the program. Ask the user to enter a sequence of at most 20
    nonnegative integers. Yourprogram should have a loop that reads the integers into an array
    and stops when a negative is entered (the negativenumber should not be stored). Invoke the
    average method to find the average of the integers in the array (send thearray as the
    parameter). Does this work?
5. Add a method minimum that takes a variable number of integer parameters and returns the
    minimum of theparameters. Invoke your method on each of the parameter lists used for the
    average function.

//*******************************************************
// Parameters.java
//
// Illustrates the concept of a variable parameter list.
//*******************************************************
import java.util.Scanner;
public class Parameters
{
//-----------------------------------------------
// Calls the average and minimum methods with
// different numbers of parameters.
//-----------------------------------------------
public static void main(String[] args)
{
double mean1, mean2;
mean1 = average(42, 69, 37);
mean2 = average(35, 43, 93, 23, 40, 21, 75);
System.out.println ("mean1 = " + mean1);
System.out.println ("mean2 = " + mean2);
}
//----------------------------------------------
// Returns the average of its parameters.
//----------------------------------------------
public static double average (int ... list)
{
double result = 0.0;
if (list.length != 0)
{
int sum = 0;
for (int num: list)
sum += num;
result = (double)sum / list.length;
}
return result;
}
}
CPCS 203                                              Lab sheet 1
Student Name:_____________________________            Section:__




Postlab Activities

                                Coding Exercise 6
                                     Matrix Inverse
CPCS 203                                                                                                                Lab sheet 1
Student Name:_____________________________                                                                              Section:__

The inverse of a square matrix A is denoted A-1, such that A×A-1 = I, where I is the identity
matrix with all1’s on the diagonal and 0 on all other cells.
                        1 2 1                          2 0.5     0.5
                        2 3 1                        1      0.5   0.5
                        4 5 3                        1       1.5 0.5
The inverse of matrix             , for example, is

that is,

 1 2 1                2          0.5    0.5        1 0 0
 2 3 1                1          0.5     0.5       0 1 0
 4 5 3                1          1.5    0.5        0 0 1

The inverse of a 3 × 3 matrix
     a11 a12 a13
A a 21 a 22 a 23
     a 31 a 32 a 33
can be obtained using the following formula if | A | 0 :

             a 22 a 33 a 23a 32          a13a 32   a12 a 33   a12 a 23 a13a 22
    1     1
A            a 23a 31 a 21a 33           a11a 33 a13 a 31     a13a 21 a11a 23
        | A|
             a 21a 32 a 22 a 31          a12 a 31 a11a 32     a11a 22   a12 a 21

        a11    a12        a13
| A | a 21     a 22       a 23     a11a 22 a 33 a 31a12 a 23 a13a 21a 32    a13 a 22 a 31 a11a 23 a 32   a 33 a 21a12
        a 31   a 32       a 33
                                                                                                                        .

Implement the following function to obtain an inverse of the matrix:

public static double[][] inverse(double[][] A)

                                                               a                  a a a a
Write a test program that prompts the user to enter a11 , a12 , 13 , a 21 , a 21 , 23 , 31 , 32 , 33 for
a matrix and displays its inverse matrix. Here are the sample runs:


Sample 1
Enter a11, a12, a13, a21, a22, a23, a31, a32, a33: 1 2 1 2 3 1 4 5 3
-2 0.5 0.5
1 0.5 -0.5
1 -1.5 0.5

Sample 2
Enter a11, a12, a13, a21, a22, a23, a31, a32, a33: 1 4 2 2 5 8 2 1 8
CPCS 203                                     Lab sheet 1
Student Name:_____________________________   Section:__

2.0 -1.875 1.375
0.0 0.25 -0.25
-0.5 0.4375 -0.1875

More Related Content

What's hot

C programming session 05
C programming session 05C programming session 05
C programming session 05Vivek Singh
 
Computer Science(083) Python Pre Board Exam 1 Sample Paper Class 12
Computer Science(083) Python Pre Board Exam 1 Sample Paper Class 12Computer Science(083) Python Pre Board Exam 1 Sample Paper Class 12
Computer Science(083) Python Pre Board Exam 1 Sample Paper Class 12chinthala Vijaya Kumar
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guidecritter13
 
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsLecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsSyed Afaq Shah MACS CP
 
GVKCV Computer Science(083) Pre board sample paper 2 Class 12 (20-21) with so...
GVKCV Computer Science(083) Pre board sample paper 2 Class 12 (20-21) with so...GVKCV Computer Science(083) Pre board sample paper 2 Class 12 (20-21) with so...
GVKCV Computer Science(083) Pre board sample paper 2 Class 12 (20-21) with so...chinthala Vijaya Kumar
 
C programming session 02
C programming session 02C programming session 02
C programming session 02Dushmanta Nath
 
Bis 311 final examination answers
Bis 311 final examination answersBis 311 final examination answers
Bis 311 final examination answersRandalHoffman
 
Ch6 pointers (latest)
Ch6 pointers (latest)Ch6 pointers (latest)
Ch6 pointers (latest)Hattori Sidek
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guidemonsterr20
 
GSP 125 Entire Course NEW
GSP 125 Entire Course NEWGSP 125 Entire Course NEW
GSP 125 Entire Course NEWshyamuopten
 
C basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kellaC basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kellaManoj Kumar kothagulla
 

What's hot (17)

Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
 
Java execise
Java execiseJava execise
Java execise
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
Icom4015 lecture4-f16
Icom4015 lecture4-f16Icom4015 lecture4-f16
Icom4015 lecture4-f16
 
Computer Science(083) Python Pre Board Exam 1 Sample Paper Class 12
Computer Science(083) Python Pre Board Exam 1 Sample Paper Class 12Computer Science(083) Python Pre Board Exam 1 Sample Paper Class 12
Computer Science(083) Python Pre Board Exam 1 Sample Paper Class 12
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guide
 
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsLecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
 
GVKCV Computer Science(083) Pre board sample paper 2 Class 12 (20-21) with so...
GVKCV Computer Science(083) Pre board sample paper 2 Class 12 (20-21) with so...GVKCV Computer Science(083) Pre board sample paper 2 Class 12 (20-21) with so...
GVKCV Computer Science(083) Pre board sample paper 2 Class 12 (20-21) with so...
 
Gsp 125 final exam guide
Gsp 125 final exam guideGsp 125 final exam guide
Gsp 125 final exam guide
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
Icom4015 lecture3-f16
Icom4015 lecture3-f16Icom4015 lecture3-f16
Icom4015 lecture3-f16
 
Bis 311 final examination answers
Bis 311 final examination answersBis 311 final examination answers
Bis 311 final examination answers
 
Ch6 pointers (latest)
Ch6 pointers (latest)Ch6 pointers (latest)
Ch6 pointers (latest)
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guide
 
GSP 125 Entire Course NEW
GSP 125 Entire Course NEWGSP 125 Entire Course NEW
GSP 125 Entire Course NEW
 
C basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kellaC basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kella
 
CBSE 12 ip 2018 sample paper
CBSE 12 ip 2018 sample paperCBSE 12 ip 2018 sample paper
CBSE 12 ip 2018 sample paper
 

Viewers also liked

Investing in Africa CPCS Slides - 1
Investing in Africa CPCS Slides - 1Investing in Africa CPCS Slides - 1
Investing in Africa CPCS Slides - 1Stephanie Kam
 
Panda, Penguin, Rabid CPC’s: The Zookeeper’s Guide to Search Marketing 2013
Panda, Penguin, Rabid CPC’s:  The Zookeeper’s Guide to Search Marketing 2013Panda, Penguin, Rabid CPC’s:  The Zookeeper’s Guide to Search Marketing 2013
Panda, Penguin, Rabid CPC’s: The Zookeeper’s Guide to Search Marketing 2013ISA Marketing & Sales Summit
 
CPCS SalesPostcard
CPCS SalesPostcardCPCS SalesPostcard
CPCS SalesPostcardJulie Davis
 
Un maniac sexuel déballe toute son intimité
Un maniac sexuel déballe toute son intimitéUn maniac sexuel déballe toute son intimité
Un maniac sexuel déballe toute son intimitéusedstudent1973
 
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods EncapsulationOCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods Encapsulationİbrahim Kürce
 
What Makes Great Infographics
What Makes Great InfographicsWhat Makes Great Infographics
What Makes Great InfographicsSlideShare
 
Masters of SlideShare
Masters of SlideShareMasters of SlideShare
Masters of SlideShareKapost
 
STOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
STOP! VIEW THIS! 10-Step Checklist When Uploading to SlideshareSTOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
STOP! VIEW THIS! 10-Step Checklist When Uploading to SlideshareEmpowered Presentations
 
10 Ways to Win at SlideShare SEO & Presentation Optimization
10 Ways to Win at SlideShare SEO & Presentation Optimization10 Ways to Win at SlideShare SEO & Presentation Optimization
10 Ways to Win at SlideShare SEO & Presentation OptimizationOneupweb
 
How To Get More From SlideShare - Super-Simple Tips For Content Marketing
How To Get More From SlideShare - Super-Simple Tips For Content MarketingHow To Get More From SlideShare - Super-Simple Tips For Content Marketing
How To Get More From SlideShare - Super-Simple Tips For Content MarketingContent Marketing Institute
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksSlideShare
 

Viewers also liked (12)

Investing in Africa CPCS Slides - 1
Investing in Africa CPCS Slides - 1Investing in Africa CPCS Slides - 1
Investing in Africa CPCS Slides - 1
 
Panda, Penguin, Rabid CPC’s: The Zookeeper’s Guide to Search Marketing 2013
Panda, Penguin, Rabid CPC’s:  The Zookeeper’s Guide to Search Marketing 2013Panda, Penguin, Rabid CPC’s:  The Zookeeper’s Guide to Search Marketing 2013
Panda, Penguin, Rabid CPC’s: The Zookeeper’s Guide to Search Marketing 2013
 
CPCS SalesPostcard
CPCS SalesPostcardCPCS SalesPostcard
CPCS SalesPostcard
 
Un maniac sexuel déballe toute son intimité
Un maniac sexuel déballe toute son intimitéUn maniac sexuel déballe toute son intimité
Un maniac sexuel déballe toute son intimité
 
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods EncapsulationOCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
 
What Makes Great Infographics
What Makes Great InfographicsWhat Makes Great Infographics
What Makes Great Infographics
 
Masters of SlideShare
Masters of SlideShareMasters of SlideShare
Masters of SlideShare
 
STOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
STOP! VIEW THIS! 10-Step Checklist When Uploading to SlideshareSTOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
STOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
 
You Suck At PowerPoint!
You Suck At PowerPoint!You Suck At PowerPoint!
You Suck At PowerPoint!
 
10 Ways to Win at SlideShare SEO & Presentation Optimization
10 Ways to Win at SlideShare SEO & Presentation Optimization10 Ways to Win at SlideShare SEO & Presentation Optimization
10 Ways to Win at SlideShare SEO & Presentation Optimization
 
How To Get More From SlideShare - Super-Simple Tips For Content Marketing
How To Get More From SlideShare - Super-Simple Tips For Content MarketingHow To Get More From SlideShare - Super-Simple Tips For Content Marketing
How To Get More From SlideShare - Super-Simple Tips For Content Marketing
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & Tricks
 

Similar to Cpcs 203 -array-problems

Lab exp declaring arrays)
Lab exp declaring arrays)Lab exp declaring arrays)
Lab exp declaring arrays)Daman Toor
 
CS 192 test questions 1-441. Global variables are known to the e.docx
CS 192 test questions 1-441. Global variables are known to the e.docxCS 192 test questions 1-441. Global variables are known to the e.docx
CS 192 test questions 1-441. Global variables are known to the e.docxfaithxdunce63732
 
SE-IT JAVA LAB SYLLABUS
SE-IT JAVA LAB SYLLABUSSE-IT JAVA LAB SYLLABUS
SE-IT JAVA LAB SYLLABUSnikshaikh786
 
Computer Science CS Project Matrix CBSE Class 12th XII .pdf
Computer Science CS Project Matrix CBSE Class 12th XII .pdfComputer Science CS Project Matrix CBSE Class 12th XII .pdf
Computer Science CS Project Matrix CBSE Class 12th XII .pdfPranavAnil9
 
CIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.comCIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.comKeatonJennings91
 
Cs141 mid termexam v1
Cs141 mid termexam v1Cs141 mid termexam v1
Cs141 mid termexam v1Fahadaio
 
Data Structures 2004
Data Structures 2004Data Structures 2004
Data Structures 2004Sanjay Goel
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaSandesh Sharma
 
A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...
A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...
A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...ijaia
 
A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...
A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...
A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...gerogepatton
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)Jay Patel
 
C programming session 08
C programming session 08C programming session 08
C programming session 08Vivek Singh
 
C programming session 04
C programming session 04C programming session 04
C programming session 04Dushmanta Nath
 
Building Java Programas
Building Java ProgramasBuilding Java Programas
Building Java Programasssuser4df5ef
 

Similar to Cpcs 203 -array-problems (20)

Lab exp declaring arrays)
Lab exp declaring arrays)Lab exp declaring arrays)
Lab exp declaring arrays)
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
 
C# p9
C# p9C# p9
C# p9
 
C data_structures
C  data_structuresC  data_structures
C data_structures
 
CS 192 test questions 1-441. Global variables are known to the e.docx
CS 192 test questions 1-441. Global variables are known to the e.docxCS 192 test questions 1-441. Global variables are known to the e.docx
CS 192 test questions 1-441. Global variables are known to the e.docx
 
SE-IT JAVA LAB SYLLABUS
SE-IT JAVA LAB SYLLABUSSE-IT JAVA LAB SYLLABUS
SE-IT JAVA LAB SYLLABUS
 
Computer Science CS Project Matrix CBSE Class 12th XII .pdf
Computer Science CS Project Matrix CBSE Class 12th XII .pdfComputer Science CS Project Matrix CBSE Class 12th XII .pdf
Computer Science CS Project Matrix CBSE Class 12th XII .pdf
 
CIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.comCIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.com
 
Cs141 mid termexam v1
Cs141 mid termexam v1Cs141 mid termexam v1
Cs141 mid termexam v1
 
E3
E3E3
E3
 
AJP
AJPAJP
AJP
 
Data Structures 2004
Data Structures 2004Data Structures 2004
Data Structures 2004
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...
A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...
A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...
 
A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...
A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...
A BI-OBJECTIVE MODEL FOR SVM WITH AN INTERACTIVE PROCEDURE TO IDENTIFY THE BE...
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
 
17515
1751517515
17515
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 
Building Java Programas
Building Java ProgramasBuilding Java Programas
Building Java Programas
 

Cpcs 203 -array-problems

  • 1. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ King Abdulaziz University Faculty of Computing and Information Systems Spring Term 2012/1433 Course Code: CPCS-203 Course Name: Programming II ______________________________________________________________________ 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. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ Prelab Activity: Matching The questions are intended to test and reinforce your understanding of key concepts. You may answer the questions before the lab. For each term in the left column, write the letter for the description from the right column that best matches theterm. Term Description _1. pass by value a) Indicates that a method receives a variable number of arguments. _2. a[ i ][ j ] b) Declares an array of type int. _3. index c) A collection of variables that contain values of thesame type. _4. new int[ 12 ] d) Iterates through an array without using a counter. _5. ... e) Information passed to an application when it executes. _6. pass by reference f) A copy of the argument’s value is made and passedto the called method. _7. array g) Represented by an array with two dimensions. _8. enhanced for statement h) A calling method gives a called method the ability to access and potentially modify the caller’s data directly. _9. int c[] i) One element of an array with two dimensions. _10. tables of values j) Specifies a particular element in an array. _11. length k) Creates an array of integers. _12. command-line arguments l) An array member that contains the number of elements in an array.
  • 3. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ Prelab Activity: Fill in the Blank 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 specifythe array’s ________ followed by only the row ________ Prelab Activity:
  • 4. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ Short Answers 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 ifcommand-line arguments were passed using an array of doubles? 25. Describe how two-dimensional arrays represent a table of data. 26. Differentiate between pass-by-value and pass-by-reference. Prelab Activity:
  • 5. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ Program Output For each of the given program segments, read the code, and write the output in the space provided below eachprogram. [Note: Do not execute these programs on a computer.] Unless specified otherwise, for the following questions assume that the code segments are contained within themain 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 ( inti = 0; i < array.length; i++ ) 5 System.out.printf("%d %dn", 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 ( inti = 0; i < sentence.length; i++ ) 5 System.out.printf("%c ", sentence[ i ] ); 6 7 System.out.println(); Your answer: 29. What is the output of the following code segment? 1 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  • 6. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ 2 3 for ( inti = 0; i < array.length; i++ ) 4{ 5 for ( intj = 0; j < array [ i ]; j++ ) 6 System.out.print("*" ); 7 8System.out.println(); 9} Your answer: 30. What is the output of the following code segment? 1 int array[] = { 3, 2, 5 }; 2 3 for ( inti = 0; i <3; i++ ) 4 array[ i ] *= 2; 5 6for ( intj : array ) 7 System.out.print("%d ", j ); 8 9System.out.println(); Your answer: Given the following declaration of a method 1 public int method1(int... values ) 2{ 3 int mystery = 1; 4 5for ( inti : values ) 6 mystery *= i; 7 8return mystery; 9} 31. What is the output of the following code segment? 1 System.out.println( method1( 1, 2, 3, 4, 5 ) ); Your answer:
  • 7. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ Given the following declaration of a method 1 public int method1(int values[][] ) 2{ 3 int mystery = 1; 4 5for ( inti[] : values ) 6 for ( intj : i ) 7 mystery *= j; 8 9return 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 3System.out.println( mystery( array ) ); Your answer: Prelab Activity:
  • 8. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ Correct the Code Determine if there is an error in each of the following program segments. If there is an error, specify whether itis a logic error or a compilation error, circle the error in the program and write the corrected code in the spaceprovided after each problem. If the code does not contain an error, write “no error.” [Note: There may be morethan one error in each program segment.] 33. The following code segment should assign 8 to the element of integer array with index 10. 1 array(10 ) = 8; Your answer: 34. The forstatement that follows should initialize all of array’s elements to -1. 1 int array[] = new int[ 10 ]; 2 3 for ( inti = 0; i <9; i++ ) 4 array[ i ] = -1; Your answer: 35. Array a should contain all the integers from 0 through 10, inclusive. 1 int a[] = new int[ 10 ];
  • 9. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ 2 3 for ( inti = 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 5arraySize = 6; 6 7 int b[] = new int[ arraySize ]; Your answer: 37. The following code segment should initialize a two-dimensional array, then print its values. 1 int a[][] = new int[ 10 ][ 5 ];
  • 10. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ 2 3 for ( inti = 0; i < a.length; i++ ) 4 for ( intj = 0; j < a[ i ].length; j++ ) 5 a[ j ][ i ] = j; 6 7 for ( inti = 0; i < a.length; i++ ) 8{ 9 for ( intj = 0; j < a[ i ].length; j++ ) 10 System.out.printf("%d ", a[ j ][ i ] ); 11 12 System.out.println(); 13 } Your answer: 38. The following code segment should assign the value 10 to the array element that corresponds to the thirdrow and the fourth column. 1 int a[] = new int[ 10 ][ 5 ]; 2 3 a[2 ][ 3 ] = 10; Your answer: Lab Exercises:
  • 11. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ Lab Exercise 1 — Duplicate Elimination This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. Theproblem is divided into six parts: 1. Lab Objectives 2. Description of Problem 3. Sample Output 4. Program Template (Figure 1: ) 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 replacedwith 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 thesource code for the template is available at www.pearsonhighered.com/deitel Lab Objectives In thislab, 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. Description of the Problem Use a one-dimensional array to solve the following problem: Write an application that inputs five numbers, eachof which is between 10 and 100, inclusive. As each number is read, display it only if it is not a duplicate of a numberalready read. Provide for the “worst case,” in which all five numbers are different. Use the smallest possiblearray to solve this problem. Display the complete set of unique values input after the user inputs each new value. Sample Output Enter number: 11 11 Enter number: 85 11 85 Enter number: 26 11 85 26 Enter number: 11 11 has already been entered
  • 12. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ Program Template 1 // Lab 1: Unique.java 2 // Reads in 5 unique numbers. 3 import java.util.Scanner; 4 5 public classUniqueTest 6{ 7 public static void main( String args[] ) 8{ 9 getNumbers(); 11} // end main 12 13// gets 5 unique numbers from the user 14public void getNumbers() 15 { 16Scanner input = new Scanner( System.in ); 17 18/* Create an array of five elements*/ 19int count = 0; // number of uniques read 20int entered = 0; // number of entered numbers 21 22while( entered < numbers.length ) 23{ 24 System.out.print("Enter number: " ); 25 /* Write code here to retrieve the input from the user */ 26 27 // validate the input 28 /* Write an if statement that validates the input */ 29 { 30 // flags whether this number already exists 31 booleancontainsNumber = false; 32 33 // increment number of entered numbers 34 entered++; 35 36/* Compare the user input to the unique numbers in the array using a for 37statement. If the number is unique, store new number */ 38 39/* add the user input to the array only if the number is not already 40in the array */ 41if ( !containsNumber )
  • 13. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ 42{ 43/* Write code to add the number to the array and increment 44unique items input */ 45}// end if 46else 47System.out.printf("%d has already been enteredn", 48number ); 49}// end if 50else 51System.out.println("number must be between 10 and 100" ); 52 53// print the list of unique values 54/* Write code to output the contents of the array */ 55}// end while 56}// end method getNumbers 57}// end class UniqueTest Figure 1: Unique.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.
  • 14. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ 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. Lab Exercises: Lab Exercise 2 — Craps Game This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. Theproblem is divided into five parts: 1. Lab Objectives 2. Description of Problem
  • 15. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ 3. Sample Output 4. Program Template (Figure 2) 5. Problem-Solving Tips The program template represents a complete working Java program, with one or more key lines of code replacedwith 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 theprogram. Compare your output with the sample output provided. The source code for the template is availableat www.pearsonhighered.com/deitel Lab Objectives In thislab you will practice: Declaring and initializing arrays. Using arrays to store sets of data. Description of the Problem 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? 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
  • 16. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ Program Template 1 // Lab 2: CrapsTest.java 2 // Program plays 1000 games of craps and displays winning 3 // and losing statistics. 4 import java.util.Random; 5 6public classCrapsTest 7{ 8public static void main( String args[] ) 9{ 10 // create random number generator for use in method rollDice 11 private static Random randomNumbers = new Random(); 12 13 // enumeration with constants that represent the game status 14 private enum Status { CONTINUE, WON, LOST }; 15 16 /* Declare array to store the number of games won by number of rolls in the 17 game */ 18 /* Declare array to store the number of games lost by number of rolls in the game 19 */ 20 int winSum = 0; // total number of wins 21 int loseSum = 0; // total number of losses 22 23 // plays one game of craps 24 `play(); 25}// end main 26 27 28public void play() 29{ 30int sumOfDice = 0; // sum of the dice 31int myPoint = 0; // point if no win or loss on first roll 32 33Status gameStatus; // can contain CONTINUE, WON or LOST 34 35int roll; // number of rolls for the current game 36 37/* Create the array to store the number of games won */
  • 17. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ 38/* Create the array to store the number of games lost */ 39 40for ( inti = 1; i <= 1000; i++ ) 41{ 42sumOfDice = rollDice(); // first roll of the dice 43roll = 1; 44 45// determine game status and point based on sumOfDice 46switch ( sumOfDice ) 47{ 48case 7: // win with 7 on first roll 49case 11: // win with 11 on first roll 50gameStatus = Status.WON; 51break; 52case 2: // lose with 2 on first roll 53case 3: // lose with 3 on first roll 54case 12: // lose with 12 on first roll 55gameStatus = Status.LOST; 56break; 57default: // did not win or lose, so remember point 58gameStatus = Status.CONTINUE; // game is not over 59myPoint = sumOfDice; // store the point 60break; // optional for default case at end of switch 61}// end switch 62 63// while game is not complete ... 64while ( gameStatus == Status.CONTINUE ) 65{ 66sumOfDice = rollDice(); // roll dice again 67roll++; 68 69// determine game status 70if ( sumOfDice == myPoint ) // win by making point 71gameStatus = Status.WON; 72else if ( sumOfDice == 7 ) // lose by rolling 7 73gameStatus = Status.LOST; 74}// end while 75 76// all roll results after 20th roll placed in last element 77/* Write an if statement to test whether the number of rolls is greater than 7821 and, if true, set number of rolls to 21 */ 79 80// increment number of wins in that roll 81if ( gameStatus == Status.WON ) 82{ 83/* Write code to increment the number of games won for a 84specific number of rolls */ 85/* Write code to increment the overall number of games won */ 86}// end if 87else // increment number of losses in that roll 88{ 89/* Write code to increment the number of games lost for a 90specific number of rolls */ 91/* Write code to increment the overall number of games lost */ 92}// end else 93}// end for
  • 18. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ 94 95printStats(); 96}// end method play 97 98// print win/loss statistics 99public void printStats() 100{ 101int totalGames = winSum + loseSum; // total number of games 102int length = 0; // total length of the games 103 104// display number of wins and losses on all rolls 105for ( inti = 1; i <= 21; i++ ) 106{ 107/* Write an if statement to test whether i is equal to 21 */ 108/* Output number of games won and lost after the 20th roll */ 109else 110/* Output number of games won and lost after each roll less than 20 */ 111 112// calculate total number of rolls to win/lose all games 113// add number of wins by number of rolls needed to win 114// add number of losses by number of rolls needed to lose 115/* Write code to calculate total length of games */ 116}// end for 117 118// calculate chances of winning 119System.out.printf("n%s %d / %d = %.2f%%n", 120"The chances of winning are", winSum, totalGames, 121( 100.0* winSum / totalGames ) ); 122 123 124System.out.printf("The average game length is %.2f rolls.n", 125( (double ) length / totalGames ) ); 126}// end method printStats 127 128// roll dice, calculate sum and display results 129public int rollDice() 130{ 131// pick random die values 132int die1 = 1 + randomNumbers.nextInt(6 ); 133int die2 = 1 + randomNumbers.nextInt(6 ); 134int sum = die1 + die2; // sum die values 135 136return sum; // return sum of dice 137}// end method rollDice 138} // end class CrapsTest 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.
  • 19. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ 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. Lab Exercises: Debugging The program in this section does not run properly. Fix all the compilation errors, so that the program will compilesuccessfully. Once the program compiles, compare the output to the sample output, and eliminate any logicerrors that exist. The sample output demonstrates what the
  • 20. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ program’s output should be once the program’s codeis corrected. The file is available at www.deitel.com/books/jhtp8/ and at www.pearsonhighered.com/deitel. 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 1 0.00 0.00 678.00 1554.00 2232.00 2 0.00 0.00 0.00 0.00 0.00 3 0.00 998.00 0.00 0.00 998.00 4 1082.00 0.00 0.00 0.00 1082.00 5 0.00 0.00 0.00 0.00 0.00 Total 1082.00 998.00 678.00 1554.00 Broken Code 1 // Debugging Problem Chapter 7: Sales2.java 2 // Program totals sales for salespeople and products. 3 import java.util.Scanner; 4 5// Debugging Problem Chapter 7: Sales2Test.java 6// Test application for class Sales2 7public classSales2Test 8{ 9public static void main( String args[] ) 10{ 11 calculateSales(); 12}// end main 13 14 Scanner input = new Scanner( System.in ); 15 // sales array holds data on number of each product sold 16 // by each salesman 17 double sales = new double[5 ][ 4 ]; 18 19 System.out.print("Enter sales person number (-1 to end): " ); 20 int person = input.nextInt(); 21 22 while ( person != -1 ) 23 { 24 System.out.print("Enter product number: " );
  • 21. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ 25 int product = input.next(); 26 System.out.print("Enter sales amount: " ); 27 double amount = input.nextDouble(); 28 29 // error-check the input 30 if ( person<1 && person >5 && 31 product >= 1 && product <6 && amount >= 0 ) 32 sales[ product - 1 ][ person - 1 ] += amount; 33 else 34 System.out.println("Invalid input!" ); 35 36 System.out.print("Enter sales person number (-1 to end): " ); 37 person = input.nextInt(); 38 } // end while 39 40 // total for each salesperson 41 double salesPersonTotal[][] = new double[ 4 ]; 42 43 // display the table 44 for ( intcolumn = 0; column <4; column++ ) 45 salesPersonTotal[ column ][ row ] = 0; 46 47 System.out.printf("%7s%14s%14s%14s%14s%10sn", 48 "Product", "Salesperson 1", "Salesperson 2", 49 "Salesperson 3", "Salesperson 4", "Total" ); 50 51 // for each column of each row, print the appropriate 52 // value representing a person's sales of a product 53 for ( introw = 0; row <5; row++ ) 54 { 55 double productTotal = 0.0; 56 System.out.printf("%7d", ( row + 1 ) ); 57 58 for ( intcolumn = 0; column <4; column++ ) { 59 System.out.printf("%14.2f", sales[ column ][ row ] ); 60 productTotal += sales[ column ][ row ]; 61 salesPersonTotal[ column ] += sales[ column ][ row ]; 62 } // end for 63 64 System.out.printf("%10.2fn", productTotal ); 65} // end for 66 67System.out.printf("%7s", "Total" ); 68 69for ( intcolumn = 0; column <4; column++ ) 70System.out.printf("%14.2f", salesPersonTotal[ column ] ); 71 72System.out.println(); 73}// end method calculateSales 64}// end class Sales2Test
  • 22. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ Postlab Activities Topics Lab Exercises One-Dimensional Arrays Tracking Sales
  • 23. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ Grading Quizzes Reversing an Array Adding To and Removing From an Integer List Command Line Arguments Averaging Numbers Variable Length Parameter Lists Exploring Variable Length Parameter Lists Two-Dimensional Arrays Matrix Inverse Coding Exercise 1 Tracking Sales File Sales.java contains a Java program that prompts for and reads in the sales for each of 5 salespeople in a company. It thenprints out the id and amount of sales for each salesperson and the total sales. Study the code, then compile and run theprogram to see how it works. Now modify the program as follows: 1. Compute and print the average sale. (You can compute this directly from the total; no loop is necessary.) 2. Find and print the maximum sale. Print both the id of the salesperson with the max sale and the amount of the sale, e.g., “Salesperson 3 had the highest sale with $4500.” Note that you don’t need another loop for this; you can do it in the same loop where the values are read and the sum is computed. 3. Do the same for the minimum sale. 4. After the list, sum, average, max and min have been printed; ask the user to enter a value. Then print the id of each salesperson who exceeded that amount, and the amount of their sales. Also print the total number of salespeople whose sales exceeded the value entered. 5. The salespeople are objecting to having an id of 0—no one wants that designation. Modify your program so that the ids run from 1-5 instead of 0-4. Do not modify the array—just make the information for salesperson 1 resides in array location 0, and so on. 6. Instead of always reading in 5 sales amounts, at the beginning ask the user for the number of sales people and then createan array that is just the right size. The program can then proceed as before. // *************************************************************** // Sales.java // // Reads in and stores sales for each of 5 salespeople. Displays // sales entered by salesperson id and total sales for all salespeople. // // *************************************************************** import java.util.Scanner; public class Sales
  • 24. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ { public static void main(String[] args) { final int SALESPEOPLE = 5; int[] sales = new int[SALESPEOPLE]; int sum; Scanner scan = new Scanner(System.in); for (int i=0; i<sales.length; i++) { System.out.print("Enter sales for salesperson " + i + ": "); sales[i] = scan.nextInt(); } System.out.println("nSalesperson Sales"); System.out.println(" ------------------ "); sum = 0; for (int i=0; i<sales.length; i++) { System.out.println(" " + i + " " + sales[i]); sum += sales[i]; } System.out.println("nTotal sales: " + sum); } } Postlab Activities Coding Exercise 2 Grading Quizzes Write a program that grades arithmetic quizzes as follows:
  • 25. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ 1. Ask the user how many questions are in the quiz. 2. Ask the user to enter the key (that is, the correct answers). There should be one answer for each question in the quiz, and each answer should be an integer. They can be entered on a single line, e.g., 34 7 13 100 81 3 9 10 321 12 might be the key for a 10-question quiz. You will need to store the key in an array. 3. Ask the user to enter the answers for the quiz to be graded. As for the key, these can be entered on a single line. Again there needs to be one for each question. Note that these answers do not need to be stored; each answer can simply be compared to the key as it is entered. 4. When the user has entered all of the answers to be graded, print the number correct and the percent correct. When this works, add a loop so that the user can grade any number of quizzes with a single key. After the results have been printed for each quiz, ask “Grade another quiz? (y/n).” Postlab Activities Coding Exercise 3 Reversing an Array
  • 26. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ Write a program that prompts the user for an integer, and then asks the user to enter that many values. Store these values in anarray and print the array. Then reverse the array elements so that the first element becomes the last element, the secondelement becomes the second to last element, and so on, with the old last element now first. Do not just reverse the order inwhich they are printed; actually change the way they are stored in the array. Do not create a second array; just rearrange theelements within the array you have. (Hint: Swap elements that need to change places.) When the elements have beenreversed, print the array again. Postlab Activities Coding Exercise 4 Averaging Numbers
  • 27. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ When you run a Java program called Foo, anything typed on the command lineafter “java Foo” is passed to the main method in the args parameter as an array of strings. 1. Write a program Average.java that just prints the strings that it is given at the command line, one per line. If nothingis given at the command line, print “No arguments”. 2. Modify your program so that it assumes the arguments given at the command line are integers. If there are noarguments, print a message. If there is at least one argument, compute and print the average of the arguments. Notethat you will need to use the parseInt method of the Integer class to extract integer values from the strings that arepassed in. If any non- integer values are passed in, your program will produce an error, which is unavoidable at thispoint. Postlab Activities Coding Exercise 5 Exploring Variable Length Parameter Lists
  • 28. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ The file Parameters.java contains a program to test the variable length method average from Section 7.5 of the text. Notethat average must be a static method since it is called from the static method main. 1. Compile and run the program. You must use the -source 1.5 option in your compile command. 2. Add a call to find the average of a single integer, say 13. Print the result of the call. 3. Add a call with an empty parameter list and print the result. Is the behavior what you expected? 4. Add an interactive part to the program. Ask the user to enter a sequence of at most 20 nonnegative integers. Yourprogram should have a loop that reads the integers into an array and stops when a negative is entered (the negativenumber should not be stored). Invoke the average method to find the average of the integers in the array (send thearray as the parameter). Does this work? 5. Add a method minimum that takes a variable number of integer parameters and returns the minimum of theparameters. Invoke your method on each of the parameter lists used for the average function. //******************************************************* // Parameters.java // // Illustrates the concept of a variable parameter list. //******************************************************* import java.util.Scanner; public class Parameters { //----------------------------------------------- // Calls the average and minimum methods with // different numbers of parameters. //----------------------------------------------- public static void main(String[] args) { double mean1, mean2; mean1 = average(42, 69, 37); mean2 = average(35, 43, 93, 23, 40, 21, 75); System.out.println ("mean1 = " + mean1); System.out.println ("mean2 = " + mean2); } //---------------------------------------------- // Returns the average of its parameters. //---------------------------------------------- public static double average (int ... list) { double result = 0.0; if (list.length != 0) { int sum = 0; for (int num: list) sum += num; result = (double)sum / list.length; } return result; } }
  • 29. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ Postlab Activities Coding Exercise 6 Matrix Inverse
  • 30. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ The inverse of a square matrix A is denoted A-1, such that A×A-1 = I, where I is the identity matrix with all1’s on the diagonal and 0 on all other cells. 1 2 1 2 0.5 0.5 2 3 1 1 0.5 0.5 4 5 3 1 1.5 0.5 The inverse of matrix , for example, is that is, 1 2 1 2 0.5 0.5 1 0 0 2 3 1 1 0.5 0.5 0 1 0 4 5 3 1 1.5 0.5 0 0 1 The inverse of a 3 × 3 matrix a11 a12 a13 A a 21 a 22 a 23 a 31 a 32 a 33 can be obtained using the following formula if | A | 0 : a 22 a 33 a 23a 32 a13a 32 a12 a 33 a12 a 23 a13a 22 1 1 A a 23a 31 a 21a 33 a11a 33 a13 a 31 a13a 21 a11a 23 | A| a 21a 32 a 22 a 31 a12 a 31 a11a 32 a11a 22 a12 a 21 a11 a12 a13 | A | a 21 a 22 a 23 a11a 22 a 33 a 31a12 a 23 a13a 21a 32 a13 a 22 a 31 a11a 23 a 32 a 33 a 21a12 a 31 a 32 a 33 . Implement the following function to obtain an inverse of the matrix: public static double[][] inverse(double[][] A) a a a a a Write a test program that prompts the user to enter a11 , a12 , 13 , a 21 , a 21 , 23 , 31 , 32 , 33 for a matrix and displays its inverse matrix. Here are the sample runs: Sample 1 Enter a11, a12, a13, a21, a22, a23, a31, a32, a33: 1 2 1 2 3 1 4 5 3 -2 0.5 0.5 1 0.5 -0.5 1 -1.5 0.5 Sample 2 Enter a11, a12, a13, a21, a22, a23, a31, a32, a33: 1 4 2 2 5 8 2 1 8
  • 31. CPCS 203 Lab sheet 1 Student Name:_____________________________ Section:__ 2.0 -1.875 1.375 0.0 0.25 -0.25 -0.5 0.4375 -0.1875