Get to know Array - C Array

C examples for Array:Introduction

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.

Demo Code

#include <stdio.h>
int main(void) {
   int myArray[3]; /* integer array with 3 elements */
}

Array Assignment

To assign values to the elements, you can reference array element by element's index, starting with zero.

Demo Code

#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.

Demo Code

#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.

Demo Code

#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.

Demo Code

#include <stdio.h>
int main(void) {
   int myArray[] = { 1, 2, 3 }; /* alternative */
   printf("%d", myArray[0]); /* 1 */
}

Result


Related Tutorials