access array elements or values in C programming Language

  Access Array elements in C programming.
Let understand how to access array elements from the Given Diagram .
To access any element of an array in C program use the [ ] subscript operator and index value of the element.
One thing we need to note is that array index always start with 0, i.e. the first element in the array is at index 0 and the last element is at the size-1 where size is the number of element in the array.
Following are some examples to access array elements.
Accessing First element in array: i.e 3500 can be accessed using salary[0]
Accessing Second element in array: i.e 4300 can be accessed using salary[1]
.
.
Accessing Last element in array: i.e 5690 can be accessed using salary[4]

Access array elements using subscript [] operator.

Syntax:
array_name [index];
array_name: is the name of of the array variable.
[index]: is the index of the array element to be accessed from array_name.

From the given figure One thing we can note is that the array variable salary is declared and initialize with some values.The first element at index 0 is 3500 which can be accessed using salary[0].and the last element 5690 is at index 4 and can be accessed using salary[4]

1. Accessing Array Elements using Array Subscript Operator []:

Example of Accessing Array Elements using Array Subscript Operator[]
// C Program to illustrate access array elements
#include <stdio.h>
int main()
{
  // declaration and initialization of salary array
 int salary[] = { 3500, 4300, 7200,1250, 5690 };
 // accessing third element or salary at index 2
 printf("Third salary at index 2 is=: %d\n", salary[2]);
 // accessing fifth element or salary at index 4
 printf(" Fifth salary at index 4 is=: %d\n", salary[4]);
 // accessing first element or salary at index 0
 printf("First salary at index 0 is=: %d", salary[0]);
 return 0;
}
output:
Third salary at index 2 is=: 7200
Fifth salary at index 4 is=: 5690
First salary at index 0 is=: 3500


2. Accessing Array Elements using for loop(C array Traversal):

For loop is used to traversal array elements.
Traversal is the process of visiting every element of the array. For traversing or accessing arrays we use loops to iterate each elements of the array.

Accessing Array Elements using for loop(C array Traversal):

/ C Program to demonstrate access array elements
#include <stdio.h>
int main()
 {
   // array declaration and initialization
  int salary[5] = { 3500,4300, 7200, 1250, 5690 };
   // change or modify salary at index 2
   arr[2] = 7900;
   // traversing array using for loop
   printf("\n All salaries in Array: ");
   for (int j = 0; j < 5; j++)
   {
    printf(" %d ", salary[j]);
   }
   return 0;
 }
Output:
All Salaries in Array:  3500  4300  7900  1250  5690


Previous Topic:-->> Initialize 1D array in C || Next topic:-->>Read and Display 1D array.