C – Introduction to Arrays

Primitive type:

  • Variables are used to store data.
  • Primitive variable can store only one value at a time.

For example,

int main()
{
            int a=5;
            a=10;
            a=20;
            printf(“a val : %d \n”, a);   // prints – 20
            return 0;
}

Array:

  • Array is used to store more than one value but of same type.
  • For example, storing 100 students’ average marks.

Array creation:

  • In array variable declaration, we need to specify the size
  • Array variable stores base address of memory block.
  • Array elements store in consecutive memory location.

Process Array elements:

  • Array memory locations must be accessed through their index.
  • Index values starts from 0 to Size-1

How to access array elements?

  • Array consists multiple values.
  • We can simply use loops to process array locations.
ReadingPrinting
int i;
for(i=0 ; i<5 ; i++)
{
            scanf(“%d”, &marks[i]);
}
int i;
for(i=0 ; i<5 ; i++)
{
            printf(“%d”, marks[i]);
}

Array as Local variable:

  • Declare array variable inside the function.
  • If the array variable is local, all locations initialize with garbage values.
int main()
{
            int arr[5], i;
            printf(“Array elements are : \n”);
            for(i=0 ; i<5 ; i++){
                        printf(“%d \n”, arr[i]);
            }          
            return 0;
}

Array as Global variable:

  • Declare array variable outside to all functions.
  • Global array variable locations initialize with default values.
int arr[5];
int main()
{
            int i;
            printf(“Array elements are : \n”);
            for(i=0 ; i<5 ; i++){
                        printf(“%d \n”, arr[i]);
            }          
            return 0;
}
Scroll to Top