C - Array Understanding arrays

Introduction

An array is series of variables of the same type, for example:

  • a dozen int variables,
  • two or three double variables, or
  • a string of char variables.

An array is declared like any other variable.

It's given a type and a name and then a set of square brackets. The following statement declares the myVariable array:

int myVariable[]; 

This declaration is incomplete; the compiler doesn't know how many items, or elements, are in the array.

If the myVariable array were to hold three elements, it would be declared like this:

int myVariable[3]; 

This array contains three elements, each of them its own int value. The elements are accessed like this:

myVariable[0] = 750; 
myVariable[1] = 699; 
myVariable[2] = 675; 

An array element is referenced by its index number in square brackets.

The first item is index 0.

In the preceding example, the first array element, myVariable[0], is assigned the value 750; the second element, 699; and the third, 675.

After initialization, an array variable is used like any other variable in your code:

var = myVariable[0]; 

This statement stores the value of array element myVariable[0] to variable var.

If myVariable[0] is equal to 750, var is equal to 750 after the statement executes.

Demo

#include <stdio.h>

int main()//ww  w  . j  av  a2 s .  co  m
{
    int myVariable[4];

    printf("Your highest score: ");
    scanf("%d",&myVariable[0]);
    printf("Your second highest score: ");
    scanf("%d",&myVariable[1]);
    printf("Your third highest score: ");
    scanf("%d",&myVariable[2]);
    printf("Your fourth highest score: ");
    scanf("%d",&myVariable[3]);

    puts("Here are your high scores");
    printf("#1 %d\n",myVariable[0]);
    printf("#2 %d\n",myVariable[1]);
    printf("#3 %d\n",myVariable[2]);
    printf("#4 %d\n",myVariable[3]);

    return(0);
}

Result

Related Topic