C examples for Array:Introduction
An array is a data structure storing a collection of values with the same data type.
The following code defines an array with 3 values for int type.
#include <stdio.h> int main(void) { int myArray[3]; /* integer array with 3 elements */ }
To assign values to the elements, you can reference array element by element's index, starting with zero.
#include <stdio.h> int main(void) { int myArray[3]; /* integer array with 3 elements */ myArray[0] = 1;/*from w ww . j a va 2 s . c o m*/ myArray[1] = 2; myArray[2] = 3; }
You can assign values at the same time as the array is declared by enclosing them in curly brackets.
#include <stdio.h> int main(void) { int myArray[3] = { 1, 2, 3 }; }
The specified array length may optionally be left out to let the array size be decided by the number of values assigned.
#include <stdio.h> int main(void) { int myArray[] = { 1, 2, 3 }; /* alternative */ }
Once the array elements are initialized, they can be accessed by referencing the index of the element you want.
#include <stdio.h> int main(void) { int myArray[] = { 1, 2, 3 }; /* alternative */ printf("%d", myArray[0]); /* 1 */ }