O'Reilly logo

C Programming: Visual Quickstart Guide by Marc Liyanage, Larry Ullman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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;

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required