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;

Get C Programming: Visual Quickstart Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.