Arrays
Arrays
C Programming Arrays:
In C programming, one of the frequently arising problem is to
handle similar types of data.
For example: If the user wants to store marks of 100 students.
This can be done by creating 100 variables individually but, this
process is rather tedious and impracticable. These types of
problem can be handled in C programming using arrays.
An array is a sequence of data item of homogeneous values(same
type).
Arrays are of two types:
One-dimensional arrays
Multidimensional arrays
Declaration of one-dimensional array:
data_type array_name[array_size];
For example:
int age[5];
Here, the name of array is age. The size of array is 5 ,i.e., there are 5
items(elements) of array age. All the elements in an array are of the
same type (int, in this case).
Array elements:
Size of array defines the number of elements in an array. Each element
of array can be accessed and used by user according to the need of
program. For example:
int age[5];
scanf("%d",&n);
for(i=0;i<n;++i){
printf("Enter marks of student%d: ",i+1);
scanf("%d",&marks[i]);
sum+=marks[i];
}
printf("Sum= %d",sum);
return 0;
}
Output:
Enter number of students: 3
Enter marks of student1: 12
Enter marks of student2: 31
Enter marks of student3: 2
sum=45
Important thing to remember in C arrays
Suppose, you have declared the array of 10 students. For example:
arr[10]. You can use array members from arr[0] to arr[9]. But, what if
you want to use element arr[10], arr[13] etc. Compiler may not show
error using these elements but, may cause fatal error during program
execution.
4
Description
Example
arr
*arr
51
*(arr+0)
51
*(arr+1)
32
Consider 2000
Output :
51 51 51 51
32 32 32 32
43 43 43 43
24 24 24 24
5555
26 26 26 26
C Array Limitations:
Static Data:
o Array is Static data Structure.
o Memory Allocated during Compile time.
o Once Memory is allocated at Compile Time it cannot be
changed during Run-time.
Can hold data belonging to same Data types
Elements belonging to different data types cannot be stored
in array because array data structure can hold data belonging
to same data type.
Example : Character and Integer values can be stored inside
separate array but cannot be stored in single array.
10