0% found this document useful (0 votes)
15 views18 pages

Arrays New

The document provides a comprehensive overview of arrays in programming, including their definitions, types (single-dimensional, two-dimensional, and multidimensional), and methods for declaration and initialization. It also includes examples of matrix addition, Fibonacci series computation, and search algorithms such as linear and binary search. Key concepts such as memory allocation and accessing elements in arrays are also discussed.

Uploaded by

Rahul Vijay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views18 pages

Arrays New

The document provides a comprehensive overview of arrays in programming, including their definitions, types (single-dimensional, two-dimensional, and multidimensional), and methods for declaration and initialization. It also includes examples of matrix addition, Fibonacci series computation, and search algorithms such as linear and binary search. Key concepts such as memory allocation and accessing elements in arrays are also discussed.

Uploaded by

Rahul Vijay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Arrays

Definition of Array: Array is the collection of similar data types or collection of similar entity
stored in contiguous memory location.

 Array of character is a string.


 Each data item of an array is called an element. And each element is unique and located
in separated memory location.
 Each of elements of an array share a variable but each element having different index no.
known as subscript.

Types of Arrays:
1. Single Dimensional Array
2. Two Dimensional Array
3. Multi Dimensional Arrays

Declaration of Single dimensional array:-


We know that all the variables are declared before they are used in the program.
Similarly, an array must be declared before it is used. During declaration, the size of the array
has to be specified. The size used during declaration of the array informs the compiler to allocate
and reserve the specified memory locations.
Syntax: - data_type array_name[n];
Where, n is the number of data items (or) index(or) dimension.
0 to (n-1) is the range of array.
Ex: int a[5];
float x[10];

Initialization of Arrays:-
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

1. Compile Time Initialization


We can initialize the elements of arrays in the same way as the ordinary variables when
they are
declared.
The general form of initialization of arrays is
Data_type array-name [size] = {list of values};
(i) 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 as shown in figure.
Index
Index
Address

Fig: Initialization of integer array a

Ex:- int a[3]={9,2,4,5,6}; //error: no. of initial vales are more than the size of array
Because size of an array is 3 but we have initialized 5 values

(ii) 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 as shown in figure

Initialization with all zeros:- Ex:- int a[5]={0};

(iii) Initialization without size:- Consider the declaration along with the initialization.
Ex:-
char b[]={'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. The array b is initialized as shown in figure.
Ex:- int ch[]={1,0,3,5} // array size is 4

(iv) Array initialization with a string: -Consider the declaration with string initialization.
Ex:-
char b[]="COMPUTER";
The array b is initialized as shown in figure.

Even though the string "COMPUTER" contains 8 characters, because it is a string, it always ends
with null character. 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

2. 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. (Or)
for(i=0;i<100;i=i+1)
{
if(i<50)
sum[i]=0.0;
else
sum[i]=1.0;
}
The first 50 elements of the array sum are initialized to 0 while the remaining 50 are initialized to
1.0 at run time.
Total size in byte for 1D array is:
Total bytes=size of (data type) * size of array.
Example :
if an array declared is:
int [20];
Total byte= 2 * 20 =40 byte.

Two-dimensional Array:
 An array consisting of two subscripts is known as two-dimensional array.
 These are often known as array of the array.
 In two dimensional arrays the array is divided into rows and columns.
 These are well suited to handle a table of data.
In 2-D array we can declare an array as:
Declaration Syntax:
data_type array_name[row_size][column_size];
Ex: - int arr [3][3];
Where first index value shows the number of the rows and second index value shows the number
of the columns in the array.

Initializing two-dimensional arrays:


Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in braces.
Ex: int a[2][3]={0,0,0,1,1,1};
Array ‘a’ initializes the elements of the first row to zero and the second row to one. The
initialization is done row by row.
 The above statement can also be written as
int a[2][3] = {{ 0,0,0},{1,1,1}};
by surrounding the elements of each row by braces.
 We can also initialize a two-dimensional array in the form of a matrix as shown below
int a[2][3]={ {0,0,0}, {1,1,1} };
 When the array is completely initialized with all values, explicitly we need not specify
the size of the first dimension.
Ex: int a[][3]={ {0,2,3}, {2,1,2} };
 If the values are missing in an initialize, they are automatically set to zero.
Ex: int a[2][3]= { {1,1}, {2} };
Above statement will initialize the first two elements of the first row to one, the first
element of the second row to two and all other elements to zero.

Total no. of elements in 2-D array is calculated as row*column


Example:-
int a[2][3];
Total no of elements=row*column is 2*3 =6
It means the matrix consist of 2 rows and 3 columns
For example:-
20 2 7
8 3 15
Positions of 2-D array elements in an array are as below
00 01 02
10 11 12

a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2]


20 2 7 8 3 15
2000 2002 2004 2006 2008 2010

Initialization of 2-d array:


2-D array can be initialized in a way similar to that of 1-D array.
for example:-
int mat[4][3]={11,12,13,14,15,16,17,18,19,20,21,22};
These values are assigned to the elements row wise, so the values of elements after this
initialization are
Mat[0][0]=11, Mat[1][0]=14, Mat[2][0]=17 Mat[3][0]=20
Mat[0][1]=12, Mat[1][1]=15, Mat[2][1]=18 Mat[3][1]=21
Mat[0][2]=13, Mat[1][2]=16, Mat[2][2]=19 Mat[3][2]=22

While initializing we can group the elements row wise using inner braces.
for example:-
int mat[4][3]={{11,12,13},{14,15,16},{17,18,19},{20,21,22}};
And while initializing, it is necessary to mention the 2nd dimension where 1 st dimension is
optional.
int mat[][3];
int mat[2][3];
int mat[][];
int mat[2][]; invalid
Memory allocation for a 2D array:
Suppose we have an array named arr having 3 rows and 3 columns then it can be stored in the
memory in the following manner:
int arr[3][3];

Accessing 2-d array /processing 2-d arrays


For processing 2-d array, we use two nested for loops. The outer for loop corresponds to the row
and the inner for loop corresponds to the column.
For example
int a[4][5];
for reading value:-
for(i=0;i<4;i++)
for(j=0;j<5;j++)
scanf(“%d”,&a[i][j]);
For displaying value:-
for(i=0;i<4;i++)
for(j=0;j<5;j++)
printf(“%d”,a[i][j]);

Multidimensional arrays
are often known as array of the arrays. In multidimensional arrays the array is divided
into rows and columns, mainly while considering multidimensional arrays we will be discussing
mainly about two dimensional arrays and a bit about three dimensional arrays.
Syntax:
data_type array_name[size1][size2][size3]------[sizeN];
In 3-D we can declare the array in the following manner:
int arr[3][3][3] = { 1, 2, 3,
4, 5, 6,
7, 8, 9,
10, 11, 12,
13, 14, 15,
16, 17, 18,

19, 20, 21,


22, 23, 24,
25, 26, 27};
/* here we have divided array into grid for sake of convenience as in above declaration we have
created 3 different grids, each have rows and columns */

If we want to access the element the in 3-D array we can do it as follows:


printf("%d",a[2][2][2]);
/* its output will be 26, as a[2][2][2] means first value in [] corresponds to the grid no. i.e. 3 and
the second value in [] means third row in the corresponding grid and last [] means third column
*/
Ex:-
int arr[3][5][12];
float table[5][4][5][3];
arr is 3D array declared to contain 180 (3*5*12) int type elements. Similarly table is a 4D array
containing 300 elements of float type.

Write a program to perform matrix addition.


#include<stdio.h>
#include<conio.h>
#include<process.h>

void main( )
{
int a[10][10],b[10][10],c[10][10];
int i,j,m,n,p,q;

printf("\n Enter the size of Matrix A:");


scanf("%d%d", &m,&n);

printf("\n Enter the size of Matrix B:");


scanf("%d%d", &p,&q);

if(m!=p || n!=q)
{
printf("Matrix addition not possible.");
exit(0);
}

printf(" Enter the Matrix A values:\n");


for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

printf(" Enter the Matrix B values:\n");


for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);

/* Addition of matrix A and B elements*/


for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];

printf(" \n The Matrix A is\n");


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(" %d ",a[i][j]);
printf("\n");
}

printf("\n The Matrix B is\n");


for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
printf(" %d ",b[i][j]);
printf("\n");
}
printf("\n Sum of matrices A and B is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(" %d ",c[i][j]);
printf("\n");
}
}
Fibonacci series is a series of numbers in which each number of the Fibonacci series is derived by
the sum of its two immediate preceding numbers.
For example: 0, 1, 1, 2, 3, 5, 8, . . .

Let f(n) be the n'th term.

f(0)=0;

f(1)=1;

f(n)=f(n-1)+f(n-2); (for n>=2)

Series is as follows
011
(1+0)
2 (1+1)
3 (1+2)
5 (2+3)
8 (3+5)
13 (5+8)
21 (8+13)
34 (13+21)
...and so on

C Program to compute n Fibonacci Series

#include<stdio.h>
#include<conio.h>

void main()
{
//array fib stores numbers of Fibonacci series
int i, fib[25],n;

printf(“Enter the value of n\n”);


scanf(%d”,&n);

//initialized first element to 0


fib[0] = 0;

//initialized second element to 1


fib[1] = 1;

//loop to generate ten elements


for (i = 2; i < =n; i++)
{
fib[i] = fib[i - 1] + fib[i - 2]; /*i'th element of series is equal to the sum of i-1'th element and
i-2'th element.*/
}
printf("The fibonacci series is as follows ");
//print all numbers in the series
for (i = 0; i < n; i++)
printf("%d\t ", fib[i]);
getch();
}

Linear search is also called as sequential search. All the elements need not be in sorted order
like binary search.
A simple approach is to do a linear search, i.e
 Start from the leftmost element of arr[] and one by one compare x with each element of
arr[]
 If x matches with an element, print position of the element
 If x doesn’t match with any of elements, print element not found

#include <stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int a[50], i, item,n;

printf("\nEnter number of elements of an array:\n");


scanf("%d",&n);

printf("\nEnter elements: \n");


for (i=0; i<n; i++)
scanf("%d", &a[i]);

printf("\nEnter item to search: ");


scanf("%d", &item);

for (i=0; i<n; i++)


if (item == a[i])
{
printf("\nItem found at location %d", i+1);
getch();
exit(0);
}
printf("\nItem does not exist.");
getch();
}

OUTPUT1:
Enter number of elements of an array:
8
Enter elements:
23578641
Enter item to search: 1
Item found at location 8

Output2:
Enter number of elements of an array:
8
Enter elements:
23578641
Enter item to search: 9
Item does not exist

Binary Search:
Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval
covering the whole array. If the value of the search key is less than the item in the middle of the
interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly
check until the value is found or the interval is empty.

Example:
/*C program to Search a key element using Binary search technique.*/

#include <stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int i, low, high, mid, n, key, array[100];
printf("Enter number of elementsn");
scanf("%d",&n);

printf("Enter %d integersn", n);


for(i = 0; i < n; i++)
scanf("%d",&array[i]);

printf("Enter value to findn");


scanf("%d", &key);

low = 0;
high = n - 1;
while (low <= high)
{
mid = (low+high)/2;

if(array[mid] == key )
{
printf("%d found at location %d.n", key, mid+1);
exit(0);
}
else if (array[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
printf("Not found! %d isn't present in the list.n", key);
getch();
}

In the program above, We declare i, low, high, mid, n, key, array[100].


 i is used for iteration through the array.
 low is used to hold the first array index.
 high is used to hold the last array index.
 mid holds the middle value calculated by adding high and low and dividing it by 2.
 n is the number of elements in the array.
 key is the element to search.
 array is the array element of size 100.
We first, take in the number of elements the user array needs and store it in n. Next, we take the
elements from the user. A for loop is used for this process. Then, we take the number to be
searched from the array and store it in the key.
Next, we assign 0 to the low variable which is the first index of an array and n-1 to the high
element, which is the last element in the array.
There is a while loop which checks if low is less then high to make sure that the array still has
elements in it. If low is greater then, high then the array is empty. Inside the while loop, mid =
(low+high)/2 to get the middle index of the array. we check whether the element at the mid is
less than the key value(array[mid] < key). If yes, then we assign low the value of mid +1
because the key value is greater than mid and is more towards the higher side. If this is false,
then we check if mid is equal to key. If yes, we print and break out of the loop. If these
conditions don’t match then we assign high the value of mid-1, which means that the key is
smaller than mid.
The last part checks if low is greater than high, which means there are no more elements left in
the array.

Remember, this algorithm won’t work if the array is not sorted.

Bubble Sort:

Bubble sort is a simple method that sorts the elements of an array into either increasing or
decreasing order. It works by comparing the adjacent elements and swapping them if they are out
of order. Multiple passes through the array are necessary.

The following are the steps to sort an array of size N in ascending order using bubble sort:
Passthrough #1:
Compare arr[0] with arr[1]. If arr[0] > arr[1], swap them.
Compare arr[1] with arr[2]. If arr[1] > arr[2], swap them.
Finally, compare a[N-2] with arr[N-1], if arr[N-2] > arr[N-1], swap them.
This completes the first passthrough.
After, the first passthrough, the highest value in the array will be at the end.

Passthrough #2:
Compare arr[0] with arr[1]. If arr[0] > arr[1], swap them.
Compare arr[1] with arr[2]. If arr[1] > arr[2], swap them.
Finally, compare a[N-3] with arr[N-2], if arr[N-3] > arr[N-2], swap them.
This completes the second passthrough. After, this passthrough, the second highest element will
be at the second highest index in the array.

Note that in the final step of the second pass through, we are not comparing the second last
element i.e a[N-2] with the last element i.e arr[N-1], this is because the last element is already in
its correct position.
Passthrough #3:
Compare arr[0] with arr[1]. If arr[0] > arr[1], swap them.
Compare arr[1] with arr[2]. If arr[1] > arr[2], swap them.
Finally, compare a[N-4] with arr[N-3], if arr[N-4] > arr[N-3], swap them.
This completes the third pass through. After, this pass through, the third highest element will be
at the third highest index in the array.
In this way, we keep passing through the array. We stop when we encountered a pass through
that's hasn't swapped any elements.

Example with Tracing: int arr[5] = {80, 60, 90, 10, 40}
Passthrough #1:

Step 1: Compare 80 and 60. Since, 80 > 60, swap them:

| 60 | 80 | 90 | 10 | 40 |

Step 2: Compare 80 and 90. Since, 80 < 90, we do nothing:

| 60 | 80 | 90 | 10 | 40 |

Step 3: Compare 90 and 10. Since, 90 > 10, swap them:

| 60 | 80 | 10 | 90 | 40 |

Step 4: Compare 90 and 40. Since, 90 > 40, swap them:

| 60 | 80 | 10 | 40 | 90 |
This completes the first pass through. The highest element i.e 90, is now at the end of the array.
We have made three swaps in this pass through. So, we need to perform another pass through.
Keep in mind that we keep passing through the array until we encounter a pass through that
hasn't swapped any elements.

Passthrough #2:

Step 1: Compare 60 and 80. Since, 60 < 80, we do nothing:

| 60 | 80 | 10 | 40 | 90 |

Step 2: Compare 80 and 10. Since, 80 > 10, swap them:

| 60 | 10 | 80 | 40 | 90 |
Step 3: Compare 80 and 40. Since, 80 > 40, swap them:

| 60 | 10 | 40 | 80 | 90 |

This completes the second pass through. The second highest element i.e 80, is now at the second
highest index in the array. Also, note that we haven't compared 80 with 90. This is because the
element 90 is already in its correct position from pass through #1.We have made 2 swaps in this
pass through. So, we need to perform another one.

Passthrough #3:

Step 1: Compare 60 and 10. Since, 60 > 10, swap them:

| 10 | 60 | 40 | 80 | 90 |
Step 2: Compare 60 and 40. Since, 60 > 40, swap them:

| 10 | 40 | 60 | 80 | 90 |
This completes the third pass through. The third highest element i.e 60, is now at the third
highest index in the array. Also, note that we haven't compared 60 with 80. This is because the
element 80 is already in its correct position from pass through #2.We have made 2 swaps in this
pass through. So, we need to perform another one.

Passthrough #4:

Step 1: Compare 10 and 40. Since, 10 < 40, we do nothing:

| 10 | 40 | 60 | 80 | 90 |
This completes the fourth pass through. We haven't made any swaps in this pass through. So, we
need don't need to perform another one. All the elements in the array are now sorted in ascending
order.
/* C program to sort array elements I n ascending order using
Bubble sort Technique*/
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[10], i, j, temp,n;

printf(“Enter number of elements in the list\n”);


scanf(“%d”,&n);
printf("Enter %d array elements:",n);
for(i=0; i<n; i++)
scanf("%d", &arr[i]);

for(i=0; i<n-1; i++)


{
for(j=0; j<n-i-1; j++)
{
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}

}
printf("\nSorted Array is:\n");
for(i=0; i<n; i++)
printf("%d\n ", arr[i]);
getch();
}

Selection Sort:
Selection sort is another algorithm that is used for sorting. This sorting algorithm, iterates
through the array and finds the smallest number in the array and swaps it with the first element if
it is smaller than the first element. Next, it goes on to the second element and so on until all
elements are sorted.
Example of Selection Sort:
Consider the array:
[10,5,2,1]
The first element is 10. The next part we must find the smallest number from the remaining
array. The smallest number from 5 2 and 1 is 1. So, we replace 10 by 1.
The new array is [1,5,2,10] Again, this process is repeated.
Finally, we get the sorted array as [1,2,5,10].
Let us continue with this article on Selection Sort in C and see how the algorithm works,
Algorithm for Selection Sort:
Step 1 − Set min to the first location
Step 2 − Search the minimum element in the array
Step 3 – swap the first location with the minimum value in the array
Step 4 – assign the second element as min.
Step 5 − Repeat the process until we get a sorted array.

/* c Program to sort array elements in ascending order using Selection sort*/


#include <stdio.h>
#inluce<conio.h>
void main()
{
int a[100], n, i, j, min,temp;
clrscr();
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d Numbersn", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i = 0; i < n - 1; i++)
{
min=i;
for(j = i + 1; j < n; j++)
{
if(a[min] > a[j])
min=j;
}
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
printf("Sorted Array:n");
for(i = 0; i < n; i++)
printf("%dn", a[i]);
getch();
}
Step by Step working of the above Program Code:
Let us assume that a user enters the number of elements as “5” and the elements as “4,1,9,3,6”.
So it assigns n=5 and stores the elements in a[]={4,1,9,3,6} using for loop.
Step for Sorting the array elements:
Then it assigns i=0 and the loop continues till the condition of for loop is true.
3.1. i<n-1 (0<4) for loop condition is true
min=i So, min=0
Then it assigns j=i+1 (j=1) and the loop continues till the condition of for loop is true.
3.1.1. j<n (1<5) for loop condition is true
a[0]>a[1] (4>1) if condition is true
min=j So, min=1
j++ (j=j+1) So, j=2

3.1.2. j<n (2<5) for loop condition is true


a[1]>a[2] (1>9) if condition is false
j++ (j=j+1) So, j=3

3.1.3. j<n (3<5) for loop condition is true


a[1]>a[3] (1>3) if condition is false
j++ (j=j+1) So, j=4

3.1.4. j<n (4<5) for loop condition is true


a[1]>a[4] (1>6) if condition is false
j++ (j=j+1) So, j=5

3.1.5. j<n (5<5) for loop condition is false


It comes out of the for loop.
min!=i (1!=0) if condition is true
temp=a[i] (temp=a[0]) So, temp=4
a[i]=a[min] (a[0]=a[1]) So, a[0]=1
a[min]=temp (a[1]=temp) So, a[1]=4
i++ (i=i+1) So, i=1
So after first iteration the array is: 1 4 9 3 6

3.2. Similarly it continue till the value of i<4.


In each iteration the smallest element is swapped with the element of “i” in the array.
Thus after second iteration the array is: 1 3 9 4 6
After third iteration the array is: 1 3 4 9 6
After fourth iteration the array is: 1 3 4 6 9

3.3 i<n-1 (4<4) for loop condition is false


So it comes out of the for loop.

Finally it prints the sorted array on the screen using for loop as given below:
The Sorted array in ascending order: 1 3 4 6 9

You might also like