This article is for C programming learner, With this series of articles we will explain you to what is array and how they works, How they resides in memory and How to use arrays in c programming.
What is an Array ?
An array is a collection of similar data-type elements stored sequentially in memory. Array size is defined on the time of declaration and can’t be altered that after. All the array must have an unique name and elements of array references with an unique index number, this index number start with 0.
An simple array memory allocation takes continuous locations in memory. for example below screencast showing memory allocated to an array. If there are no free memory remains in contiguous locations as size of array. the declaration of array will failed.
Array Declaration –
While declaring an array, we must have 3 things a. Array datatype, b. Array name and c. Array size. Always try to define only that size which is required, because we can’t increase size of these array after declaration. Also there there are free space remains, that means waste of memory. Lets find the syntax of array, This is example for single dimension array.
<data_type> <array_name>[<size of array>]
For example we need to store numbers 1-20 in an array, To define array use following syntax –
int arr[20];
Similarly if we want to save a-z characters in an array, define it as following
char arr[26];
Array Initialization –
Initialize array means to save data in array. Keep remembers that you can’t store other data_type value to array by which its defined, except if that supports other. There are two way of array initialization –
1. Initialize array at time of declaration – means save all the values in array columns during declaration like below.
int arr[5] = {'1','2','3','4','5'};
2. Initialize array during program execution – means all array elements will be fill at time of execution programs, It has a benefit that we can save elements from user input.
int arr[5]; int i; for(i=0;i<5;i++) { printf("Enter a number: "); scanf("%d", &num); arr[i] = num; }
Accessing Array Elements -
In array we can access any element by specifying their index number. For example if we want to access the element stored on index 2 in array named arr. Use following
int value; value = arr[2];
Or we can fetch and print entire array elements using for or while loop
int i; for(i=0;i<5; i++) { printf("%dn", arr[i] ); }