Accessing Array Values

Once you've declared and initialized an array, you'll want to be able to access those array values. For the most part, doing so is much like referring to any other variable except that now you must use the square brackets and indicate to which element you are referring:

int num;
int grades[] = {94, 82, 87};
num = grades[0]; // num is 94.
printf ("The third element in grades has a value of %d.", grades[2]);

To demonstrate this, let's flesh out the quiz application so that it compares a user-submitted answer to the correct one.

To access array values

1.
Open quiz2.c (Script 6.2) in your text editor or IDE, if it is not already open.

2.
Add three new variables (Script 6.3):

char input[10];
int user_answer;
char junk;

Script 6.3. The (mostly) completed quiz application reads in user input and compares that to the correct answers stored in an array.


These three variables will be used to handle all of the standard input. What the user types will first be read into the input character string (which happens to be a character array). This will then be assigned to the user_answer variable. Finally, the junk variable will be used to discard extraneous user input.

3.
After the variable declarations, prompt the user with the first question:

printf ("How many NBA championships
 have the Chicago Bulls won? ");

This is the first question; the correct answer is stored as the first element in the answers array.

4.
Retrieve the user's answer:

fgets (input, sizeof(input), stdin);
sscanf (input, "%d", &user_answer);

Using the techniques covered in Chapter 5, “Standard Input and Ouput, ” what the user types in after the prompt is first read and then an integer value from that input is assigned to the user_answer variable. See Chapter 5 for a detailed discussion of this syntax.

5.
Compare the user's answer to the right answer:

if (user_answer == answers[0]) {
    printf ("You are correct!
");
} else {
   printf ("You are incorrect! The
 Bulls have won a total of %d NBA
 championships.
", answers[0]);
}

The right answer is stored in answers[0]. The user's answer is in user_answer. By seeing if these two values are equal, this conditional indicates whether the user provided the correct answer. The array value is also used in the context of a printf() statement, which has the %d signifier for an integer, because the array is an integer type.

6.
Discard any extra input using a do... while loop:

do {
   junk = getchar();
} while (junk != '
' );

Again, this structure was introduced at the end of the previous chapter. It reads in and does nothing with all extra input until it reaches a newline ( ). While not obligatory, this feature keeps the execution of this application tidy.

7.
Repeat Steps 3 through 6 for the next two questions.

In order to save space and time, the next two questions are not part of the listed code. But you can repeat Steps 3 through 6 (prompt the user, read in the input, compare against the right answer, delete extraneous input) for them if you want. The proper questions (corresponding to the right answers) would be: What was the last year in which the Chicago Cubs won the World Series? and When did the Chicago Bears win the Super Bowl? Of course, you can use your own questions and answers as you see fit.

8.
Call the getchar() function to halt the execution of the application until the user presses Return or Enter.

This is only required on Windows and other environments where the console window will automatically close after successful execution.

9.
Save the file as quiz3.c, compile, and debug as necessary.

10.
Run the application, entering different values (Figures 6.3 and 6.4) to see the results.

Figure 6.3. Answering the first question correctly gives this result.


Figure 6.4. Answering the first question with anything other than 6 (including words, decimals, or letters) gives this result.


✓ Tips

  • The quiz example could be improved in many ways, including adding the ability to track the number of correct answers. You could accomplish this by incrementing an integer variable for each correct response.

  • There is no printf() signifier for printing an array in its entirety. Therefore, you cannot do something like

    printf ("This is an array: %d.",
     my_array);
    

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset