- In C programming language provides a data structure called as Array.
- An array is a collection of similar elements.
- Array can store a number of elements of homogeneous type store in a sequential manner.
- An array elements could be all ints, or all floats, or all chars, etc.
- Array of chars is usually called as string.
- All array elements must be are of the same data type.
- For example: if a user wants to store marks of 100 students. One way to do this is, create 100 variables for each student. So it will be difficult to manage all variables. Therefore, this type of problem can be handled by ‘Array’.
Definition of array:
Array is a collection of the homogeneous type of data stored at the continuous memory location.
Array can be an integer array or character array. A character array is also known as a string.
1 2 |
int arr[10]; //integer array char name[20]; //characte array i.e. string |
Above diagram is a basic example of an array. The first index of an array is always the first element of an array as shown in the figure. This figure represents the array:
1 |
arr[10] = {4, 10, 55, 9, 2}; |
Array Elements:
- The number of elements in an array defines the size of an array.
- Size represents the maximum number of elements.
- Array index always starts from 0.
- Till the array element value are not given, they are supposed to contain garbage values.
- Each element can be accessed by the user whenever it needed.
- Array elements can be passed to a function by calling the function by value, or by reference.
- Array elements are accessed by using array index.
12345e.g: int arr[3] = {5, 8, 1};arr[0]=5;arr[1]=8;arr[2]=1;arr[3/2]=8; //this is same as arr[1]
Types of array:
In C, an array can be:
Points to remember:
- You can calculate size of an array by using “sizeof”
- If you declare an array as constant, then you can not change the values of elements.
12const int arr[5] = {1,2,3,4,5};arr[4] = 50; // compile time error
- Array size can be defined by #define directive
1234567#include<stdio.h>#define size 5int main(){int arr[size];getchar();}
Preprocessor replace macro size with 5 during preprocessing and then compiler compiles the program with replaced values. - Array does not perform bounds checking during run-time execution.
12345678910#include<stdio.h>int main(){int arr[5] = {1, 2, 3, 4, 5};int i;for(i = 0; i <= 6; i++){printf("%d", arr[i]);}}
Output:
11 2 3 4 5 garbage_value garbage_value
“For example: if a user wants to store marks of 100 students. One way to do this is, create 100 variables for each student. ”
Nope. Should be “One way to do this is create 100 variables to represent all of the students.”
100 variables for each student would be 10000 variables, not 100.