You are on page 1of 35

ARRAY

Definition of Array
• An array is defined as the collection of similar type of data items stored at
contiguous memory locations
• Arrays are the derived data type in C programming language which can
store the primitive type of data such as int, char, double, float, etc.
• The array is the simplest data structure where each data element can be
randomly accessed by using its index number.
• It also has the capability to store the collection of derived data types, such
as pointers, structure, etc.
Representation of array
Why do we need arrays?
• Consider a scenario where you need to find out the average of 100 integer
numbers entered by user.
• In C, you have two ways to do this:
1) Define 100 variables with int data type and then perform 100 scanf()
operations to store the entered values in the variables and then at last calculate
the average of them.
2) Have a single integer array to store all the values, loop the array to store all
the entered values in array and later calculate the average.
Advantage of C Array

1) Code Optimization: Less code to the access the data.


2) Ease of traversing: By using the for loop, we can retrieve the elements of
an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of
code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array

• Fixed Size: Whatever size, we define at the time of declaration of the array,
we can't exceed the limit. So, it doesn't grow the size dynamically
• We must know in advance that how many elements are to be stored in array.
• Only elements of same data types can be stored in an array. We cannot store
elements of multiple data types in a single array.
• As Array elements are stored in consecutive memory locations. So, insertions
and deletions of an element is time consuming as we have to shift other
elements one position ahead or back respectively.
Types of Array
One Dimensional Array (1-D)

Two Dimensional Array (2-D)

Multidimensional Array
One Dimensional Array (1-D)

• Conceptually you can think of a one-dimensional array as a row, where


elements are stored one after another.
Declaration of Array

Syntax: datatype array_name[size];
datatype: It denotes the type of the elements in the array.
array_name: Name of the array. It must be a valid identifier.
size: Number of elements an array can hold.
Here are some example of array declarations:

1
int num[100];
float temp[20];
2
char ch[50];
3
Initialization of Array
• The different types of initializing arrays:
1. At Compile time
(i) Initializing all specified memory locations.
(ii) Partial array initialization
(iii)Initialization without size
(iv)String initialization
2. At Run time
Initializing all specified memory
locations
• Arrays can be initialized at the time of declaration when their initial
values are known in advance.
• Array elements can be initialized with data items of type int, char etc.
• Ex:- int a[5]={10,15,1,3,20};
• During compilation, 5 contiguous memory locations are reserved by the
compiler for the variable a and all these locations are initialized
• Ex:- int a[3]={9,2,4,5,6}; //error: no. of initial vales are more than the size
of array.
Partial array initialization
• Partial array initialization is possible in c language.
• If the number of values to be initialized is less than the size of the array,
then the elements will be initialized to zero automatically.
• Ex:- int a[5]={10,15};
• Even though compiler allocates 5 memory locations, using this declaration
statement; the compiler initializes first two locations with 10 and 15, the
next set of memory locations are automatically initialized to 0's by
compiler
• Initialization with all zeros:-
Ex:- int a[5]={0};

• Initialization without size:-


• Consider the declaration along with the initialization.
Ex:- char b[ ]={'C','O','M','P','U','T','E','R'};
Char b[8]={'C','O','M','P','U','T','E','R'};
• In this declaration, even though we have not specified exact number of elements to be
used in array b, the array size will be set of the total number of initial values specified.
• So, the array size will be set to 8 automatically
Array initialization with a string
• Consider the declaration with string initialization.
Ex:- char b[ ]="COMPUTER";
• Even though the string "COMPUTER" contains 8 characters, because it is
a string, it always ends with null character. (\0)
• So, the array size is 9 bytes (i.e., string length 1 byte for null character).
• Ex:- char b[9]="COMPUTER"; // correct
• char b[8]="COMPUTER"; // wrong
Run Time Initialization
• An array can be explicitly initialized at run time.
• This approach is usually applied for initializing large arrays.
• Ex:- scanf can be used to initialize an array.
• int x[3];
• scanf(“%d%d%d”, &x[0],&x[1],&x[2]);
• The above statements will initialize array elements with the values entered
through the key board.
Accessing Array Elements
You can use array subscript (or index) to access any element stored in array.
Subscript starts with 0, which means arr[0] represents the first element in the array
arr.
In general arr[n-1] can be used to access nth element of an array. where n is any
integer number
Declaration, assignment and accessing
#include <stdio.h>
arrays
int main () Element[0] = 100
{
Element[1] = 101
int n[ 10 ]; /* n is an array of 10 integers */
int i, j; Element[2] = 102
for ( i = 0; i < =9; i++ ) /* initialize elements of array n to 0 */
{
Element[3] = 103
//scanf(“%d”,&n[i]); Element[4] = 104
n[ i ] = i + 100; /* set element at location i to i + 100 */
} Element[5] = 105
Element[6] = 106
for (j = 0; j < 10; j++ )
{ Element[7] = 107
printf("Element[%d] = %d\n", j, n[j] ); /* output each array element's value */
Element[8] = 108
} Element[9] =
return 0; 109
}
Input and Output Array Elements
Here's how you can take input from the user and store it in an array element.
// take input and store it in the 3rd element
​scanf("%d", &mark[2]);

// take input and store it in the ith element


scanf("%d", &mark[i-1]);
printf(“%d”, marks[2]);//display
int main()
{ Output:
int values[5]; Enter 5 integers:
printf("Enter 5 integers: "); 1
for(int i = 0; i < 5; i++)
-3
{
34
0
scanf(“%d", &values[i]);
3
}
Displaying integers:
printf("Displaying integers: ");
1
for(int i = 0; i < 5; ++i)
-3
{ 34
printf("%d\n", values[i]); 0
}
3
return 0;
}
No Index Out of Bound Checking
In case one attempts to access the element out of bounds of the array, no error is shown
by compiler instead it generates a warning. And also gives an unexpected output.

Example

int a[4] ={2,3,4,5};

If we write printf(“%d”, a[4]);


The output will be 225263545 – Unexpected
#include<stdio.h> Output:
main.c: In function ‘main’:
int main() main.c:4:19: warning: excess elements in array initializer
int arr[2]={10,22,56,32,45,89} ;
{ ^~
main.c:4:19: note: (near initialization for ‘arr’)
int arr[2]={10,22,56,32,45,89} ; main.c:4:22: warning: excess elements in array initializer
int arr[2]={10,22,56,32,45,89} ;
int i; ^~
main.c:4:22: note: (near initialization for ‘arr’)
printf("Elements of array are:"); main.c:4:25: warning: excess elements in array initializer
int arr[2]={10,22,56,32,45,89} ;
for(i=0;i<3;i++) ^~
main.c:4:25: note: (near initialization for ‘arr’)
{ main.c:4:28: warning: excess elements in array initializer
int arr[2]={10,22,56,32,45,89} ;
printf("%d\n",arr[i]); ^~
main.c:4:28: note: (near initialization for ‘arr’)
} $main
return 0; Elements of array are : 10
22
}
Applications illustrating use of arrays to store
ordered and unordered sequences
• Searching Methods
1. Linear Search
2. Binary Search
• Sorting Methods
1. Bubble Sort
2. Selection Sort
3. Insertion Sort
Linear Search Method

• In this type of search, a sequential search is made over all items one by
one.
• Every item is checked and if a match is found then that particular item is
returned, otherwise the search continues till the end of the data collection.
Program
for (i = 0; i < num ; i++)
{ if (keynum == array[i] )
int num,i, keynum, found = 0; {
 
printf("Enter the number of elements ");
found = 1;
scanf("%d", &num); break;
int array[num];
printf("Enter the elements one by one \n"); }
for (i = 0; i < num; i++) }
{
scanf("%d", &array[i]);
if (found == 1)
} printf("Element is present in the array at position
  printf("Enter the element to be searched "); %d",i+1);
scanf("%d", &keynum); else
printf("Element is not present in the array\n");
}
return 0;
Binary Search Method
• Binary Search is a search algorithm that is used to find the position of an element in a sorted
array. The array should be sorted prior to applying a binary search.
• Working
The binary search algorithm works by comparing the element to be searched by the middle
element of the array and based on this comparison follows the required procedure.
Case 1 − element = middle, the element is found return the index.
Case 2 − element > middle, search for the element in the sub-array starting from middle+1 index
to n.
Case 3 − element < middle, search for element in the sub-array starting from 0 index to middle -1.
1. Let x = 4 be the element to be
searched.

2. Set two pointers low and high at the lowest


and the highest positions respectively

3. Find the middle element mid of the array


ie. (arr [low + high]) / 2 = 6.
4. If x == mid, then return mid.
Else, compare the element to be searched with m.
5. If x > mid, compare x with the middle element of the elements on the right side of mid.
This is done by setting low to low = mid + 1.
6. Else, compare x with the middle element of the elements on the left side of mid.
This is done by setting high to high = mid - 1.

8. x = 4 is found.
7. Repeat steps 3 to 6 until low meets high
Sorting Methods: Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements
if they are in wrong order.
Two Dimensional Array
• An array of arrays is known as 2D array.
• The 2D array is organized as matrices which can be represented as the
collection of rows and columns
• In 2D arrays ,we have to define at least the second dimension of the array.
Declaration of two dimensional Array in C
data_type array_name[rows][columns]; 
int abc[5][4];
Initialization of 2D Arrays

int disp[ 2 ][4] = { {10, 11, 12, 13}, {14, 15, 16, 17}
};
OR
int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
Representation of array in memory
• Let a be a two dimensional m x n array. Though a is pictured as a
rectangular pattern with m rows and n columns, it is represented in
memory by a block of m*n sequential memory locations.
• However the sequence can be stored in two different ways:
• Column Major Order
• Row Major Order
Column Major and Row Major Order

• In the column major order,


the elements are stored
column by column. First
column, second column and
so on
• In row major order the
elements are stored row by
row. First row, second row
and so on.
Multidimensional Array
● In C programming, you can create an array of arrays. These arrays are known
as multidimensional arrays
● Data in multidimensional arrays are stored in tabular form
● Total number of elements that can be stored in a multidimensional array can
be calculated by multiplying the size of all the dimensions.
For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
Declaration of Multidimensional Array
data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array.
array_name: Name of the array
size1, size2,... ,sizeN: Sizes of the dimensions

e.g.[3][3][3];

You might also like