CPSC 124, Fall 2017: Sample Answers to Quiz #7

These are sample answers only. Often, answers that are less
detailed than the ones given here can still receive full credit.

Question 1. Suppose that data is an array of type int[]. Use a for-each loop to add up all of the integers in the array named data.

Answer.

int sum = 0;
for ( int number : data ) {
    sum = sum + number;
}

Question 2. Suppose that Date is the class shown below. And suppose that dates is an array of type Date[]. Write a code segment that will print each of the dates in the array named dates, using the standard format month/day/year for a date. (For example, in this format, today's date would be printed as 12/4/2017.) You can use either a regular for loop or a for-each loop.

class Date {
    int month;
    int day;
    int year;
}

Answer.

Using a for-each loop and System.out.printf:

        for ( Date d : dates ) {
            System.out.printf("%d/%d/&d%n", d.month, d.day, d.year);
        }

    
Using a regular for loop and System.out.println:

        for ( int i = 0; i < dates.length; i++ ) {
            System.out.println( dates[i].month + "/" +
                                   dates[i].day + "/" +
                                      dates[i].year );
        }


Or, avoiding expressions like "dates[i].month":

        for ( int i = 0; i < dates.length; i++ ) {
            Date d = dates[i];
            System.out.println( d.month + "/" + d.day + "/" + d.year );
        }

Question 3. Discuss what it means to say that a GUI program is event-driven. (For example: What are events? Where do they come from? How do they "drive" a program. An example of an "event" would be useful.)

Answer.

An event is anything that can occur asynchronously, not under the control of the program, to which the program might want to respond. GUI programs are said to be "event-driven" because for the most part, such programs simply wait for events and respond to them when they occur. Things happen in the program because the program "listens" for events, and does things when the events occur. In many (but not all) cases, an event is the result of a user action, such as when the user uses the mouse, types a character, or clicks a button. For example, a program might respond to a click on a button by clearing the screen in a drawing program, and it might respond to mouse events by adding shapes to the drawing. More generally, a programmer can set up any desired response to an event by writing an event-handling routine for that event.