You are on page 1of 56

Unit V - Arrays

- group of elements of same type is called array

Outline
Array definition Characteristics of an array One-dimensional array Two- dimensional array Multi-dimensional array Operations on array
Insertion Deletion Merging Searching Sorting

Array - Introduction
Definition:
Array is a collection of similar data types in which each element is located in separate memory locations.

Properties:
Stores data elements in successive memory locations Homogeneous data structure all elements are of the same data type.

Declaration:
Eg:
int a[5]; - creates an array with name a that can hold 5 integers Char ch[10]; Float b[10]; Long num[2];

Example 1
int scores[9];

Example 2

Array Initialization

Characteristics of an array
int a[5]; - instead of creating 5 different variables for five different integers , one array can be created. All elements of the array have the same name Each element is differentiated using the element number or index. Any particular element can be modified separately without disturbing other elements.
Eg: int a[5] = {1,2,3,4,5}; a[4] =10;

Any element of an array can be assigned/equated to another ordinary/array variable of its type.
Eg: b = a[5]; a[2] = a[3];

Note
One array cannot be copied to another using assignment. Total bytes = sizeof(data type)* number of array elements

One Dimensional Array


int a[5];
Suppose the starting memory location is 2000. Each integer element requires 2 bytes.
Integer Data types and their memory locations Element a[0] Address 2000 a[1] 2002 a[2] 2004 a[3] 2006 a[4] 2008

Character arrays
also called strings. A null (\0) character is added at the end to mark the end of string.

Example: Initialize an array

Output:

Example: Initialize using initializer list

Output

Example: Prompts the user to enter the values and then print the same on screen

Output

Exercise
Write a program to initialize two integer arrays od size 10 and then add the corresponding elements and store it in another array.

Sorting the array by comparison method

Output

Two-Dimensional array
A two-dimensional array can be thought of as a rectangular display of elements with rows and columns. Declaration:
<datatype> <name> [rows][col];

Eg: int x[3][3];


Col1 Row1 Row2 Row3 x[0][0] x[1][0] x[2][0] Col2 x[0][1] x[1][1] x[2][1] Col3 x[0][2] x[1][2] x[2][2]

Note: the above representation is for understanding. Physically, the array elements are stored one after the the other.

Initialization of a two dimensional array


The number of subscripts determines the dimensionality of an array x[i] refers to an element of one dimensional array, x y[i][j] refers to an element of two dimensionalarray, y int a[3][2] = { 1,1, 2,4, 3,8 }; int b[3][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12} }; The same effect is achieved by int b[3][4] = { 1,2,3,4,5,6,7,8,9,10,11,12 }; Note: uninitialized element values are set default to 0 or garbage depending upon the compiler.

Example
Write a program to display the elements of a two dimensional array

Example:Transpose of a matrix

Program to find the transpose of a matrix

Output:

Exercise
Write a program to perform addition and subtraction of two matrices.

Multi-dimensional arrays
C program allows array of two or multi dimensions Declaration: <data type> <array name> [S1][S2][S3][Sn]; Eg: int mat[3][3][3] = { { {1,2,3}, {4,5,6},{7,8,9} } { {1,4,7}, {4,9,5},{6,2,3} } { {2,3,9}, {5,9,5},{3,5,2} } };

Operations on arrays
Insertion Deletion Merging Searching Sorting

Deletion
Involves deleting specified elements from the array
5 4 1 2 5 4 1 2 b. Shifting one element up 5 4 2

a. Original array

c. After deletion

program to delete a specific element


void main() { int Num[20] = {0},j,n,p; printf(\nEnter number of elements); scanf(%d,&n); printf(\nEnter elements:); for(j=0;j<n;j++) scanf(%d,&Num[j]); printf(\nEnter the element number to delete:); scanf(%d,&p); p--; for(j=0;j<n;j++) { if(j>=p) Num[j] = Num[j+1]; }

n=n-1; for(j=0;j<n;j++) { if Num[j]!=0) printf(\nNum[%d] = %d,j,Num[j]); }

Output: Enter the number of elements: 5 Enter elements: 7 8 6 5 4 Enter element number to delete:3 Num[0] = 7 Num[1] = 8 Num[2] = 5 Num[3] = 4

Insertion
Used to insert an element at a specified position in the array.
1 2 3 4 a. Original array 2 3 4 b. Insert element 1 1 9 2 3 4 c. After insertion

Merging
Easiest way is to merge two arrays is
1) copy all elememts of 1st array into the 3rd array. 2)copy all elements of 2nd array into the 3rd array.
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8

Searching
The process of seeking specified elements in an array is called searching. Two types:
Linear search Binary search

Linear Search
Task is to find a particular element(key) in the array Search the array from the beginning, element by element, until the key is found or the end of the list is reached. If found, print the corresponding array position else display the message

Example: Find 62 in the given list

Successful Search

Unsuccessful Search

Linear Search - Program

Binary Search
Look at the middle element of the list If it is value being searched, then the job is done If the value that is being searched is smaller than the middle, then continue with the bottom half of the list If the value that is being searched is larger than the middle, then continue with the top half of the list

Example: Find 22 in the given list

Successful search

Unsuccessful Search

Binary Search - Program


#include <stdio.h> main( ) { int a[30], n, i, target, first, mid, last, found=0; printf(\nEnter the number of elements in the array: ); scanf(%d,&n); for ( i = 0; i < n; i++ ) { printf( "\n Enter the number: ); scanf(%d,&a[i]); } printf(\nEnter the key to be searched: ); scanf(%d,&target); first=0; last=n-1; while(first<=last) { mid=(first+last)/2;

if (a[mid]==target) { found=1; break; } else if (target<a[mid]) last = mid-1; else first = mid+1; } /*end of while*/ if (found==0) printf(\n NOT FOUND); else printf("\n Found at %d, mid); } /*end of main*/

Sorting
Arranging elements in a specific order, either ascending or descending is known as sorting Three types:
Selection sort Bubble sort Insertion sort

Selection sort
The list is divided into two sub-lists, sorted and unsorted, which we will separate with an imaginary wall Initially, the entire array constitutes the unsorted list Algorithm
1. go through the unsorted list and find the smallest element 2. then swap that element with the element at the beginning of the

unsorted data

Selection sort
Once we find the smallest element in the unsorted list and move it to the front (near k) we then move the wall one to the right
1. This adds one to the sorted list and takes one away from the unsorted list 2. Each time we complete such a swap we say we have completed a sort pass 3. With n elements in an array we need n-1 sort passes to properly sort the data

Example Selection sort

Selection sort - Program

Bubble Sort
Algorithm:
1. Compare adjacent array elements, swap if they are out of order 2. Repeat step 1 until n-1 passes for an array of n elements 3. After each pass, the smallest element bubbles towards left side

Example- Bubble Sort

Bubble sort - Program

Insertion Sort
Algorithm:
1. Select the first element in the unsorted list. 2. Place that element in the appropriate place in the sorted list. Moving elements in the sorted list as necessary. 3. Repeat step 1.

Example- Insertion Sort

Insertion Sort - Program

University Ques:
Display array elements and their addresses(jun 2007) ( Soln: USE & BEFORE VARIABLE NAME FOR ADDRESS) Matrix operations: Transpose and adding diagonal elements(Dec 2007) Print the number of occurrences of a given element with their position(dec 2007) Merge two sorted array into a single sorted array( may 2008) Print first and second biggest element of an array(june 2009) - Students,Try to solve all the programs and let me know if you have any problem in solving . -- D. Kokila,AP/CSE

You might also like