0% found this document useful (0 votes)
37 views90 pages

UNIT - 2.2 Arrays

An array is a collection of continuous memory locations which can store similar data type values and all these memory locations shares same name. Arrays allow to store multiple values in one variable and can be initialized at compile time or run time. Common sorting algorithms like bubble sort, insertion sort, selection sort are used to arrange array elements in ascending or descending order.

Uploaded by

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

UNIT - 2.2 Arrays

An array is a collection of continuous memory locations which can store similar data type values and all these memory locations shares same name. Arrays allow to store multiple values in one variable and can be initialized at compile time or run time. Common sorting algorithms like bubble sort, insertion sort, selection sort are used to arrange array elements in ascending or descending order.

Uploaded by

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

Unit-2

Arrays
In C Programming
What is an array?
• An array is a variable that holds multiple
values of the same data type.

(OR)
• An array is a collection of continuous
memory locations which can store similar
data type values and all these memory
locations shares same name.
How an array is declared?
Syntax:
DataType arrayName[size];

Example:
int rollNo[60];
How an array is initialized?
Syntax:
DataType arrayName[size] = {value1,value2….,valuen};

Example:
int rollNo[5] = {1,2,3,4,5};
How an array element is assign?
❑To know how to assign a value to the
individual elements of an array first we must
know how an array is organized in memory.
How an array is organized?
Normal Variable –
int a, b, c; a b
Array Variable – c
int x[3];
x

0 1 2
index
How an array element is assign?

We can use the index values to access individual


elements of an array.

Syntax –
arrayName [indexValue] = value;
Example –
x [1] = 100;
Arrays are of two types:
One dimension array

□ Single or one dimension array is


used to represent and store data in a
linear form.
□ Array having only one subscript
variable is called one dimension
array.
□ It is also called as single dimensional
array or linear array.
Declaration of one-dimensional array
syntax:
datatype arrayname[size];
For example:
int iarr[3] = {2, 3, 4};
char carr[20] = "learn" ;
float farr[3] = {12.5,13.5,14.5} ;
int age[5]={2,4,34,3,4};
Array elements

Size of array defines the number of elements in an


array.

Note : the first element is numbered 0 and so on.


Different ways to initialize an
array
□ There are two ways to initialize
an array
1. At compile time
2. At run time
At compile time

□ We can initialize an array at compile


time using following syntax
dataType arraName[ size ] =
{value1, value2, value3, …..}
□ Example:
int a[ 3 ] = {10, 20, 30};
At run time
□ We can initialize an array at run time using
index value of that array with following
syntax
arraName[ indexValue ] = value;
□ Example:
a[ 2 ] = 200;

Generally run time initialization is performed


using the concept of loops like for, while and
do-while
At run time
□ Example:
int a[5], i;
printf(“Enter array values:”)
for(i = 0; i<5; i++)
{
scanf(“%d”, &a[i]);
}
More about Initialization of one-
dimensional array:
□ Arrays can be initialized at declaration time in this source
code as:
int age[5]={2,4,34,3,4};
□ It is not necessary to define the size of arrays during
initialization.
int age[]={2,4,34,3,4};
□ In this case, the compiler determines the size of array by
calculating the number of elements of an array.
Accessing Array Elements

for example:
□ scanf("%d",&age[2]);
/* statement to insert value in the third element
of array age[]. */
□ scanf("%d",&age[i]);
/* Statement to insert value in (i+1)th element of
array age[i]. */
/* Because, the first element of array is age[0],
second is age[1], ith is age[i-1] and (i+1)th is
age[i]. */
□ printf("%d",age[0]);
/* statement to print first element of an array.
*/

□ printf("%d",age[i]);
/* statement to print (i+1)th element of an
array. */
□ /* C program to find the sum marks of n students using
arrays */
#include <stdio.h>
int main()
{
int marks[10],i,n,sum=0;
printf("Enter number of students: ");
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
Multi-Dimensional Array
In C programming language allows to create arrays of arrays
known as multi-dimensional arrays.
or
□ An array of arrays is called as multi dimensional array.0
□ In simple words, an array created with more than one
dimension (size) is called as multi dimensional array.
□ Multi dimensional array can be of two dimensional array
or three dimensional array or four dimensional
array or more...
□ Most popular and commonly used multi dimensional array
is two dimensional array. The 2-D arrays are used to
store data in the form of table. We also use 2-D arrays to
create mathematical matrices.
Declaration of Two Dimensional Array

Syntax:
datatype arrayname[rowsize][columnsize];
For example:1
float a[2][6];
❑ Here, a is an array of two-dimension, which is an example of
two-dimensional array. This array has 2 rows and 6 columns.
For example:2
int matrix_A [2][3] ;
□ The above declaration of two dimensional array reserves 6
continuous memory locations of 2 bytes each in the form of 2
rows and 3 columns.
□ For easy understanding of two-dimensional arrays,
array elements of above example are showed below.
Initialization of two-dimensional Arrays

❑ We use the following general syntax for declaring and


initializing a two dimensional array with specific number of
rows and columns with initial values.
datatype arrayName [rows][columns] = {{r1c1value,
r1c2value, ...},{r2c1, r2c2,...}...} ;
Example:
int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;
❑ The above declaration of two dimensional array reserves 6
continuous memory locations of 2 bytes each in the form of
2 rows and 3 columns. And the first row is initialized with
values 1, 2 & 3 and second row is initialized with values 4, 5
& 6.
□ We can also initialize as follows...
Example: int matrix_A [2][3] = { {1, 2, 3}, {4, 5, 6} } ;
□ In C programming language, two-
dimensional arrays can be initialized in
different number of ways.
For example:
int c[2][3]={{1,3,0},{-1,5,9}};
1 3 0
int c[][3]={{1,3,0},{-1,5,9}};
OR -1 5 9
OR
int c[2][3]={1,3,0,-1,5,9};
Accessing Individual Elements of Two
Dimensional Array

□ In c programming language, to access elements of a two


dimensional array we use array name followed by row index
value and column index value of the element that to be
accessed. Here the row and column index values must be
enclosed in separate square braces. In case of two
dimensional array the compiler assigns separate index values
for rows and columns.
□ We use the following general syntax to access the individual
elements of a two dimensional array...
arrayName [ rowIndex ] [ columnIndex ];
Example:
matrix_A [0][1] = 10 ;
In the above statement, the element with row index 0 and
column index 1 of matrix_A array is assinged with value 10.
SORTING

□ In simple word, sorting means arranging the


given elements or data in an ordered
sequence(ascending or descending order).

□ The main purpose of sorting is to easily &


quickly locate an element in a sorted list & design
an efficient algorithm around it.
SORTING(cont.

□ The sorting methods can be divided into two


parts i.e. internal and external.
□ Internal Sorting: data that is going to be sorted
will be in main memory.
□ External Sorting: which deals with sorting data
stored in files, data will be on auxiliary storage
like tape, floppy, disk etc.
Sorting Methods

□ Many methods are used for sorting,


such as:
1. Bubble sort
2. Selection sort
3. Insertion sort
4. Quick sort
5. Merge sort
6. Heap sort
7. Radix sort
8. Shell sort
1.Bubble Sort

❑ The term sorting means arranging the elements of the array so


that they are placed in some relevant order which may either be
ascending order, descending order or alphabetical order.
❑ Bubble sort is a very simple method that sorts the array elements
by repeatedly moving the largest element to the highest index
position of the array.
❑ In bubble sorting, consecutive adjacent pairs of elements in the
array are compared with each other.
❑ If the element at lower index is greater than the element at the
higher index, the two elements are interchanged so that the
smaller element is placed before the bigger one.
❑ This procedure of sorting is called bubble sorting because the
smaller elements “bubble” to the top of the list.
1.Algorithm for Bubble Sort:
Algorithm for Bubble Sort:
❑ If N elements are given in memory then for sorting we do
following steps
1. First compare the 1st and 2nd element of array if 1st 3 rd then
interchange the value of 2 nd and 3 rd.
2. If 2 nd > 3 rd then interchange the value of 2 nd and 3 rd..
3. Now compare the value of 3 rd (which has the value of 2 nd )
with 4 th.
4. Similarly compare until the N-1 th element is compared with N th
element
5. Now the highest value element is reached at the N th place.
6. Now elements will be compared until N-1 elements.
Bubble Sort Example:
Let us consider an array that has the following elements:-
A[]={ 13, 32, 20, 62, 68, 52, 38, 46 }
Pass1:
Compare 1st and 2nd element, 13<20, interchange is done.
Compare 2nd and 3rd element, 32>20 interchange is done
13 20 32 62 68 52 38 46
Compare 3rd and 4th element, 32<62, No change .
Compare 4th and 5th element, 62<68,No change
Compare 5th and 6th element, 68>52 interchange
13 20 32 62 52 68 38 46
Compare 6th and 7th element, 68>38 interchange
13 20 32 62 52 38 68 46
Bubble Sort Example:
Compare 7th and 8th element, 68>46 interchange
13 20 32 62 52 38 46 68
Pass2- interchanges are
13 20 32 52 62 38 46 68
13 20 32 52 38 62 46 68
13 20 32 52 38 46 62 68
Pass3-
13 20 32 38 52 46 62 68
13 20 32 38 46 52 62 68
Pass4-
13 20 32 38 46 52 62 68
BUBBLE_SORT(A,N)
▪ Step 1: Repeat steps For I=0 to N-1
Step 2: Repeat For J=I to N
▪ Step 3: If A[i] > A[j], then SWAP
A[i] and A[J]
▪ [End of inner loop] [End of Outer
loop]
▪ Step 4: EXIT
1.Bubble Sort- example

/* program of sorting using bubble sort */


#include<stdio.h> main()
{
int i,j,k,n,t,a[10];
printf("enter numberof elements: "); scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter elements %d: ",i+1); scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
{
1.Bubble Sort- example

if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
printf("\nafter pass %d elements are: ",i+1);
for(k=0;k<n;k++)
printf("\t%d",a[k]); // these are optional part for understanding
movements of elements
}
printf("\nthe sorted list:");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
}
2. Selection sort
□ As the name suggests selection sort is the selection of an element and
keeping it in sorted order.
□ If list of elements in unsorted order and to make a list of elements in
sorted order then first take the smallest element and keep in the new list,
after that second smallest element and so on until the largest element of
list.
□ Let us take an array arr[0], arr[1]…..arr[N-1] of elements.
□ First search the position of smallest element from arr[0]….arr[N-1].
□ Then interchange that smallest element with arr[0].
□ Now search position of smallest element from arr[1]… arr[N-1],
arr[2]….arr[N-1].
□ Pass 1:
Search the smallest element from arr[0]….arr[N-1].
Interchange arr[0] with smallest element.
Result: arr[0] is sorted.
□ Pass 2:
Search the smallest element from arr[1]….arr[N-1].
Interchange arr[1] with smallest element.
Result: arr[0], arr[1] is sorted.
…..
…..
□ Pass N-1:
Search the smallest element from arr[N-2]….arr[N-1].
Interchange arr[N-2] with smallest element.
Result: arr[0]……..arr[N-1] is sorted.
Let us take list of elements in unsorted order and sort them
by applying selection sort. Pass

1) 75 35 42 13 87 24 64 57 (swa
2) 13 35 42 75 87 24 64 57 (swa
3) 13 24 42 75 87 35 64 57 (swa
4) 13 24 35 75 87 42 64 57 (swa
5) 13 24 35 42 87 75 64 57 (swa
6) 13 24 35 42 57 75 64 87 (swa
7) 13 24 35 42 57 64 75 87 final output
1. Selection Sort- example
/*Program to sorting using Selection Sort */
#include<stdio.h>
main()
{
int a[10],i,j,k,n,temp,small; printf("Enter the number of elements:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter element %d:",i+1); scanf("%d",&a[i]);
}
printf("Unsorted List:"\n"); for(i=0;i<n;i++)
printf("%d",a[i]);
/*Selection Sort */ for(i=0;i<n-1;i++)
{
/* Find the smallest element*/ small=i;
for(k=i+1;k<n;k++)
{
1. Selection Sort- example

if(a[small]>a[k]) small=k;
}
if(i!=small)
{
temp=a[i]; a[i]=a[small]; a[small]=temp;
}

printf("After pass %d elements are :",i+1); for(j=0;j<n;j++)


printf("%d",a[j]);
}
printf("Sorted list is :\n"); for(i=0;i<n;i++) printf("%d",a[i]); printf("\n");
}
3. Insertion sort
□ The insertion sort insert each element in
proper place.
□ This is same as playing cards, in which we
place the cards in proper order.
□ There are n elements in the array and we place
each element of array at proper place in the
previously sorted element list.
3. Insertion sort
Let us take there are N elements in the array arr. Then process of inserting each element in proper
place is as-
□ Pass 1- arr[0] is already sorted because of only one element.
□ Pass 2 – arr[1] is inserted before or after arr[0].
□ So arr[0] and arr[1] are sorted.
□ Pass 3 – arr[2] is inserted before arr[0], in between arr[0] and arr[1] or after arr[1]. So arr[0],
arr[1] and arr[2] are sorted.
□ Pass 4 – arr[3] is inserted into its proper place in array arr[0], arr[1],arr[2] So
arr[0],arr[1],arr[3] are sorted.
□ ……………………………..
□ ……………………………..
□ Pass N- arr[N-1] is inserted into its proper place in array So arr[0],arr[1] arr[N-1] are sorted.
□ The element inserted in the proper place is compared with the previous elements and placed
in between the ith element and i+1 th element if element >= ith element , element <= (i+1)th
element
Ex 82 42 49 8 92 25 59 52
Pass1 - 82 42 49 8 92 25 59 52
Pass2 - 82 42 49 8 92 25 59 52
Pass3 - 42 82 49 8 92 25 59 52
Pass4 - 42 49 42 8 92 25 59 52
Pass5 - 8 42 49 82 92 25 59 52
Pass6 - 8 42 49 82 92 25 59 52
Pass7 - 8 25 42 49 82 92 59 52
Pass8 - 8 25 42 49 59 82 92 52
Sorted elements are 8 25 42 49 52 59 82 92
3. Insertion sort-example
/*program of sorting using insertion sort
#include<stdio.h> main()
{
int a[10],i,j,k,n;
printf("Enter the number of elements:"); scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter element %d:",i+1); scanf("%d",&a[i]);
}
printf("Unsorted List:"\n"); for(i=0;i<n;i++)
printf("%d",a[i]); printf("\n");
3. Insertion sort-example
/*insertion Sort */ for(j=1;j<n;j++)
{
k=a[j];
for(i=j-1;i>=0 && k<a[i];i--) a[i+1]=a[i];
a[i+1]=k;
printf("After pass %d elements are :",i+1); for(i=0;i<n;i++)
printf("%d",a[i]); printf("\n");
}
printf("Sorted list is :\n"); for(i=0;i<n;i++) printf("%d",a[i]); printf("\n");
}
Note: The above three sorting methods i.e. bubble sort, selection sort
and insertion sort are the most common methods used for sorting.
All the other methods are used rarely.
What is Search?

Searching is the process of finding the given


element in a list of elements

OR

Searching is a process of locating a


particular element present in a given set of
elements. The element may be a record, a
table, or a file.
Searching Algorithm

Linear
Search
Searchin
g Binary
Search
Linear Search Algorithm (Sequential Search)

Linear search algorithm finds the given element in a


list of elements with O(n) time complexity
where n is the total number of elements in the list.

This search process starts comparing the search


element with the first element in the list,

If both are matched then the result is "element found


“, otherwise the search element is compared with the
next element in the list .
□ If both are matched, then the result is "element found"

• Otherwise, repeat the same with the next element


in the list until the search element is compared
with the last element in the list.

• If that last element also doesn't match with the


search element, then the result we get
as "Element not found in the list". That
means, the search element is compared with all
other elements in the list sequentially until the
match found.
Linear search is implemented using following
steps...)

Step 1: Read the search element from the user

Step 2: Compare, the search element with the first


element in the list.

Step 3: If both are matched, then display "Given


element found!!!" and terminate the function
Step 4: If both are not matched, then compare
search element with the next element in the list.

Step 5: Repeat steps 3 and 4 until the search


element is compared with the last element in the
list.

Step 6: If the last element in the list is also not


matched, then display "Element not found!!!" and
terminate the function.
EXAMPLE :
Consider the following list of element and
search element...

0 1 2 3
65 20 10 55
List 32 12 50 99
4 5 6 7
Search element 12
step 1:
search element(12) is compared with first
element list(65)
0 1 2 3 4 5

6 2 10 5 3 1 5 9
5 0 5 2 2 0 9
6 7
List 12
□ Both are not matching .so move to the next element.
Step 2:
search element(12) is compared with first
element list(20)

List
6 2 1 5 3 1 5 9
5 0 0 5 2 2 0 9
Binary Search Algorithm

❑Binary search algorithm finds a given


element in a list of elements with O(log
n) time complexity where n is total number
of elements in the list.
❑The binary search algorithm can be used
with only a sorted list of elements. That
means the binary search is used only with a
list of elements that are already arranged in
an order.
❑ The binary search can not be used for a
list of elements arranged in random order.
Binary Search Algorithm

❑This search process starts comparing the search element


with the middle element in the list. If both are matched, then
the result is "element found".
❑Otherwise, we check whether the search element is smaller
or larger than the middle element in the list. If the search
element is smaller, then we repeat the same process for the
left sublist of the middle element.
❑ If the search element is larger, then we repeat the same
process for the right sublist of the middle element.
❑ We repeat this process until we find the search element in
the list or until we left with a sublist of only one element.
And if that element also doesn't match with the search
element, then the result is "Element not found in the list".
Binary Search Algorithm

Binary search is implemented using following steps...


Step 1 - Read the search element from the user.
Step 2 - Find the middle element in the sorted list.
Step 3 - Compare the search element with the middle element in the
sorted list.
Step 4 - If both are matched, then display "Given element is found!!!" and
terminate the function.
Step 5 - If both are not matched, then check whether the search element
is smaller or larger than the middle element.
Step 6 - If the search element is smaller than middle element, repeat
steps 2, 3, 4 and 5 for the left sublist of the middle element.
Step 7 - If the search element is larger than middle element, repeat steps
2, 3, 4 and 5 for the right sublist of the middle element.
Step 8 - Repeat the same process until we find the search element in the
list or until sublist contains only one element.
Step 9 - If that element also doesn't match with the search
element, then display "Element is not found in the list!!!" and
terminate the function.
#include<stdio.h> middle = (first+last)/2;
#include<conio.h> while (first <= last)
void main() {
{ if (list[middle] < sElement)
int first, last, middle, size, i, first = middle + 1;
sElement, list[100]; else if (list[middle] == sElement)
{
clrscr();
printf("Element found at index
printf("Enter the size of the list: "); %d.\n",middle);
scanf("%d",&size); break;
printf("Enter %d integer values in }
Ascending order\n", size); else
for (i = 0; i < size; i++) last = middle - 1;
middle = (first + last)/2;
scanf("%d",&list[i]);
}
printf("Enter value to be search: "); if (first > last)
scanf("%d", &sElement); printf("Element Not found in the
first = 0; list.");
last = size - 1; getch();
}
printf("\nThe elements of A matrics");
1:Write a C program Addition for(i=0;i<m;i++)
of Two Matrices {
#include<stdio.h> printf("\n");
for(j=0;j<n;j++)
#include<conio.h>
printf("\t%d",a[i][j]);
void main() }
{ printf("\nThe elements of B matrics");
int for(i=0;i<m;i++)
a[25][25],b[25][25],c[25][2 {
5],i,j,m,n; printf("\n");
clrscr(); for(j=0;j<n;j++)
printf("enter the rows and printf("\t%d",a[i][j]);
colums of two matrics:\n"); }
printf("\nThe additon of two matrics");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
printf("\nenter the elements of A {
matrics"); printf("\n");
for(i=0;i<m;i++) { for(j=0;j<n;j++)
for(j=0;j<n;j++) {
scanf("\t%d",&a[i][j]); c[i][j]=a[i][j]+b[i][j];
} printf("\t%d",c[i][j]);
printf("\nenter the elements of B }
matrics"); }
for(i=0;i<m;i++) getch();
{ }
2 : Write a C program Multiplication
of Two Matrices.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[25][25],b[25][25],c[25][25];
Int i,j,m,n,k,r,s;
clrscr();
printf("enter the rows and colums of A matrics:\n");
scanf("%d%d",&m,&n);
printf("enter the rows and colums of B matrics:\n");
scanf("%d%d",&r,&s);
printf("\nenter the elements of A matrics");
for(i=0;i<m;i++) {
for(j=0;j<n;j++)
scanf("\t%d",&a[i][j]); }
printf("\nenter the elements of B matrics");
for(i=0;i<m;i++) {
for(j=0;j<n;j++)
scanf("\t%d",&b[i][j]); }
printf("\nThe elements of A matrics");
for(i=0;i<m;i++) {
printf("\n");
for(j=0;j<n;j++)
printf("\t%d",a[i][j]); }
printf("\nThe element of B matrics");
for(i=0;i<m;i++) {
printf("\n");
for(j=0;j<n;j++)
printf("\t.0%d",b[i][j]); }
for(i=0;i<m;i++) {
printf("\n");
for(j=0;j<n;j++) {
c[i][j]=0;
for(k=0;k<m;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j]; }
}
printf("\nThe Multiplication of two matrics");
for(i=0;i<m;i++) {
printf("\n");
for(j=0;j<n;j++)
printf("\t%d",c[i][j]); }
getch(); }
Examples:

1. Write a C program to find sum of two matrix


of order 2*2 using multi- dimensional
arrays where, elements of matrix are
entered by user.
2. Write a C Program to Find Transpose of a
Matrix
Example of Multi-dimensional Array In C

#include <stdio.h>
void main()
{ int i,j;
float a[2][2], b[2][2], c[2][2];
printf("Enter the elements of 1st matrix\n");
/* Reading two dimensional Array with the help of two for loop. If
there was an array of 'n' dimension, 'n' numbers of loops are
needed for inserting data to array.*/
for(i=0;i<2;++i)
for(j=0;j<2;++j)
{ printf("Enter a%d%d: ",i+1,j+1);
scanf("%f",&a[i][j]);
} printf("Enter the elements of 2nd matrix\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
{
printf("Enter b%d%d: ",i+1,j+1);
scanf("%f",&b[i][j]);
}
for(i=0;i<2;++i)
for(j=0;j<2;++j)
{ /* Writing the elements of multidimensional array using loop. */
c[i][j]=a[i][j]+b[i][j]; /* Sum of corresponding elements of two
arrays. */
}
printf("\nSum Of Matrix:");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
{
printf("%.1f\t",c[i][j]);
if(j==1) /* To display matrix sum in order. */
printf("\n");
}
}
Applications of Arrays in C
In c programming language, arrays are used in wide range of
applications. Few of them are as follows...
1.Arrays are used to Store List of values
□ In c programming language, single dimensional arrays are
used to store list of values of same data type. In other
words, single dimensional arrays are used to store a row
of values. In single dimensional array data is stored in
linear form.
2.Arrays are used to Perform Matrix Operations
□ We use two dimensional arrays to create matrix. We can
perform various operations on matrices using two
dimensional arrays.
3.Arrays are used to implement
Search Algorithms

❑ We use single dimensional arrays to implement search


algorithms like ...
1.Linear Search
2.Binary Search
4.Arrays are used to implement Sorting Algorithms
□ We use single dimensional arrays to implement sorting
algorithms like ...
1.Insertion Sort
2.Bubble Sort
3.Selection Sort
4.Quick Sort
5.Merge Sort, etc.,
5.Arrays are used to implement Data
structures
□ We use single dimensional arrays to implement
datastructures like...
1.Stack Using Arrays
2.Queue Using Arrays
6.Arrays are also used to implement CPU Scheduling
Algorithms
Arrays and pointers
□ In C programming, Array name by itself is an address or
pointer.
□ It points to the address of the first element(0th element of
an array).
□ The elements of the array together with their addresses
can be displayed by using array name itself.
□ Array elements are always stored in contiguous memory
locations.
□ Arrays and pointers are synonymous in terms of how they
use to access memory. But, the important difference
between them is that, a pointer variable can take different
addresses as value whereas, in case of array it is fixed.
Relation between Arrays and
Pointers
Consider an array:
int arr[4];
□ In arrays of C programming, name of the array always
points to the first element of an array. Here, address of
first element of an array is &arr[0]. Also, arr represents
the address of the pointer where it is pointing.
Hence, &arr[0] is equivalent to arr.
□ Also, value inside the address &arr[0] and address arr are
equal. Value in address &arr[0] is arr[0] and value in
address arr is *arr. Hence, arr[0] is equivalent to *arr.
Similarly,
□ &a[1] is equivalent to (a+1) AND, a[1] is
equivalent to *(a+1).
□ &a[2] is equivalent to (a+2) AND, a[2] is
equivalent to *(a+2).
□ &a[3] is equivalent to (a+1) AND, a[3] is
equivalent to *(a+3). . .. .
□ &a[i] is equivalent to (a+i) AND, a[i] is
equivalent to *(a+i).
for example:

#include <stdio.h>
void main()
{
int a[5]={10,20,30,40,50}; 1 2 3 4 5
clrscr(); 0 0 0 0 0
printf(“%u\n”,a);
1 1 1 1 1
printf(“%d\n”,*a); 0 0 0 0 0
printf(“%d\n”,*(a+1)); 0 2 4 6 8
printf(“%u\n”, &a[2]);
printf(“%d\n”, a[3]);
}
Output:
100
10
20
104
40
Arrays and Functions

□ In C programming, a single array element or


an entire array can be passed as argument
/parameter to a function.
□ Also, both one-dimensional and multi-
dimensional array can be passed as
argument/parameter to function.
Method :-1 Using array

#include<stdio.h>
#include<conio.h>
void sub(int []);
void main() a[0 a[ a[ a[ a[ a[ a[ a[ a[ a[
] 1] 2] 3] 4] 5] 6] 7] 8] 9]
{
int a[10];
printf(“read the values keyboard”);
for(i=0;i<10;i++)
scanf(“%d”,&a[i]);
sub(a);
}
void sub(int b[])
{
int i;
for(i=0;i<10;i++) a[ a[ a[ a[ a[ a[ a[ a[ a[ a[
printf(“%d”,b[i]); 0] 1] 2] 3] 4] 5] 6] 7] 8] 9]

}
Method :-2 using pointer

#include<stdio.h>
#include<conio.h>
void sub(int *);
void main()
a[ a[ a[ a[ a[ a[ a[ a[ a[ a[
{ 0] 1] 2] 3] 4] 5] 6] 7] 8] 9]
int a[10];
printf(“read the values keyboard”);
for(i=0;i<10;i++)
scanf(“%d”,&a[i]);
sub(a);
}
65 65 65 65 65 65 65 65 65 65
void sub(int *b) 52 52 52 53 53 53 53 53 54 54

{
4 6 8 0 2 4 16 8 0 2
1 2 3 4 5 6 7 8 9
0
int i; 1 2 3 4 5 6 7 8 9
a[
0
a[ a[ a[ a[ a[ a[ a[ a[ a[
for(i=0;i<10;i++) 0] 1] 2] 3] 4] 5] 6] 7] 8] 9]
printf(“%d”,*(b+i));
}
65
52
4
#include<stdio.h>
void display(int );
void main()
{
int c[]={2,3,4};
clrscr();
display(c[2]); //Passing array element c[2]
only.
}
void display(int a)
{
printf("%d",a);
}
Output: 4
Passing entire one-dimensional array to a
function

□ Array can be passed as an parameter to a function.


□ Parameter passing method: call by reference / call
by address.
□ It is also called: pass by address
□ Actual parameters is passed to function.
□ Array elements (values) are updated in function.
(or)
□ Array elements are reflected inside main function
also.
Passing entire elements of an Array to a Function- example

#include<stdio.h>
#include<conio.h>
void modify(int b[3]);
void main()
{
int arr[3] = {1,2,3},i;
modify(arr);
for(i=0;i<3;i++)
printf("%d",arr[i]);
getch();
}
void modify(int a[3])
{
int i;
for(i=0;i<3;i++)
a[i] = a[i]*a[i];
}
Output: 1 4 9

⮚ Here ,”arr” is same as “a” because base address


of array“arr” is stored in array “a”.

Alterate way to write function header


void modify(int a[3])
OR
void modify(int *a)
Example:-1.Write a C program to pass an array containing age
of person to a function. This function should find average age
and display the average age in main function.
#include <stdio.h>
float average(float a[]);
void main()
{
float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18};
clrscr();
avg=average(c); /* Only name of array is passed as argument.
*/
printf("Average age=%f",avg);
getch();
}
float average(float a[])
{
int i;
float avg, sum=0;
for(i=0;i<6;++i)
{
sum+=a[i];
}
avg =(sum/6);
return avg;
}
Output: Average age=27.08
Passing Multi-dimensional Arrays to
Function
□ To pass two-dimensional array to a function as an
argument, starting address of memory area reserved is
passed as in one dimensional array.
Example:
#include<stdio.h>
void Function(int c[2][2]);
void main()
{
int c[2][2],i,j;
printf("Enter 4 numbers:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
{
scanf("%d",&c[i][j]);
}
Function(c); /* passing multi-dimensional array to function */
}
void Function(int c[2][2])
{ /* Instead to above line, void Function(int c[][2]){ is
also valid */
int i,j;
printf("Displaying:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
printf("%d\n",c[i][j])
}
Output:
Enter 4 numbers: 2 3 4 5
Displaying: 2 3 4 5

You might also like