Arrays in C:
Arrays: An array is a collection of similar types of data elements stored at contiguous memory locations. Arrays are the derived data type in C which can store primitive types of data such as int, char, float, double, etc. A specific element in an array is accessed by an index. The most common array is the string which is simply an array of characters terminated by a null.
Arrays are classified into two types:
1. Single dimensional arrays
2. Two-dimensional arrays
Single Dimensional arrays: The general form for declaring a single-dimensional array is
syntax:
data_type var_name[size];
Declaration of an array:
int arr[5];
Based on the size compiler will allocate the memory allocations. In the above declaration, the compiler will allocate 5 memory locations to arr variable.
Initialization of an Array:
We can also initialize an array using indexes as shown below.
int a[5]; // declare an array first.
a[0]=2;
a[1]=4;
a[2]=6;
a[3]=8;
a[4]=10;
The array looks like this.
Note: Array Indexing starts from 0 to n-1.
Declaration with Initialization:
1. int a[5]={1,2,3,4,5}; //integer array
(or)
int a[ ]={1,2,3,4,5}; //no need to declare size.
2. char a[5]={'h','e','l','l','o'}; //character array
3. float a[6]={1.1,2.5,3.6,4.7,5.8,6.8}; // float array
Example1: C program to declare and initialize an array.
Program:
Output:
Two Dimensional Arrays: C supports multidimensional arrays. The simplest form of the multi-dimensional array is the two-dimensional array. The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns.
syntax:
data_type array_name[rows][columns];
Declaration of a 2D array:
int arr[3][5];
The 3 represents rows and the 5 represents columns. The above declaration is represented as follows:
Example:
Output:
Properties of an array:
1. Each Element of an array is of the same data type and carries the same size.
2. Elements of an array are stored at contiguous memory locations.
3. The first value is stored at the smallest location.
4. whatever the size is given at the time of declaration is fixed size. we cannot assign the values beyond the size.
prev<---printf() & scanf() next topic--->strings in c
No comments:
Post a Comment