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

Open quiz2.c (Script 6.2) in your text editor or IDE, if it is not already open.
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 live online training, plus books, videos, and digital content from nearly 200 publishers.