Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to access an array element in C language?
An array is a group of related data items that share a common name. A particular value in an array is identified by using its "index number" or "subscript". The advantage of an array is the ability to use a single name to represent a collection of items and to refer to an item by specifying the item number, enabling the development of concise and efficient programs.
Syntax
datatype array_name[size]; array_name[index] = value; // Assigning value variable = array_name[index]; // Accessing value
Where index starts from 0 and goes up to (size-1).
For example:
float height[50]; // Array of 50 float elements int group[10]; // Array of 10 integer elements
Individual elements are identified using "array subscripts". While complete set of values are referred to as an array, individual values are called "elements". Accessing the array elements is done by using an array index within square brackets.
Example: Accessing Array Elements
Following is the C program for accessing an array −
#include <stdio.h>
int main() {
int array[5], i;
// Assigning values to specific array elements
array[0] = 46;
array[1] = 35;
array[2] = 28;
array[3] = 12;
array[4] = 67;
printf("Array elements are: ");
for (i = 0; i < 5; i++) {
printf("%d ", array[i]);
}
printf("<br>");
// Accessing individual elements
printf("First element: %d<br>", array[0]);
printf("Third element: %d<br>", array[2]);
printf("Last element: %d<br>", array[4]);
return 0;
}
Array elements are: 46 35 28 12 67 First element: 46 Third element: 28 Last element: 67
Key Points
- Array indices start from 0 and go up to (size-1).
- Accessing an out-of-bounds index leads to undefined behavior.
- Uninitialized array elements contain garbage values.
Conclusion
Array element access in C is straightforward using square bracket notation with zero-based indexing. Always ensure indices are within valid range to avoid undefined behavior and initialize all elements before use.
