SlideShare a Scribd company logo
1 of 52
Arrays in C
Definition
• Defn: An array in C is a collection of items
stored at contiguous memory locations and
elements can be accessed randomly using
indices of an array.
• An array is a linear data structure which
stores homogeneous(similar)data items.
• The array is the simplest data structure where
each data element can be randomly accessed
by using its index number.
Example:
• C array is beneficial if you have to store similar elements.
• Suppose you have to store marks of 50 students, one way to do this is
allotting 50 variables.
• So it will be typical and hard to manage. For example we can not access
the value of these variables with only 1 or 2 lines of code.
• Another way to do this is array. By using array, we can access the elements
easily. Only few lines of code is required to access the elements of
array.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Easy to traverse data: By using the for loop, we can retrieve the
elements of an array easily.
3) Easy to sort data: To sort the elements of 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
1) Fixed Size: Whatever size, we define at the time of declaration
of array, we can't exceed the limit. So, it doesn't grow the size
dynamically like LinkedList.
Array Terminology
Array variable is composed with the following terms:
• Size:total number of elements in an array
• Type: data type of declared array.
• Base:address of the first element of the array.
• Index:Location or index value of array element.
• Range:Value from lower bound to upper bound.
• Word:indicates the space required for an element.
Declaration of C Array
when array size is given:
• We can declare an array in the c language in the following way:
• the example to declare array:
• Here, int is the data_type, marks is the array_name and 5 is
the array_size.
Declaration of C Array
when array size is not known before compilation:
data type array_name [];
//size will depend upon the elements entered by
user at run time.
Example:
int a[];
Initialization of C Array
At the time of declaration:
• A simple way to initialize array is by index.
• array index starts from 0 and ends with [SIZE - 1].
int a[5]={10,20,30,40,50}
Taking input from the user:
void main()
{
int a[5];
for(int i=0;i<5;i++)
{ to take input
printf(“enter the array element”); from the user
scanf(“%d”,&a[i]);
}
for(int i=0;i<5;i++)
{ to display output
printf(“the array is: %d”,a[i]); to the user
}
}
A
i=0<5 true
a[0]
=5
i=1<5 true
A[1]= 7
i=2<5 true
A[2]=9
i=3<5 true
A[3]=4
i=4<5 true
A[4]=3
A[0] A[1] A[2] A[3] A[4]
5 7 9 4 3
C array example
0 1 2 3 4
marks[0] marks[1] marks[2] marks[3] marks[4]
80 60 70 85 75
C Array: Declaration with
Initialization
• We can initialize the c array at the time of declaration.
• In such case, there is no requirement to define size. So it can
also be written as the following code.
C array example:
0 1 2 3 4
marks[0] marks[1] marks[2] marks[3] marks[4]
20 30 40 50 60
Memory Representation of elements of 1D- array
• Loc(a[k])=base(a)+w(k-lb)
• Size of an array =ub-lb+1
Where
a[k]= element at kth location of an array
base(a)= base address of an array.
w= number of bytes per storage location
k= position of element
lb= lower bound of an array
ub= upper bound of array
1. Consider an integer array a of 10 elements[0,1,…,9] such that first element is stored at
1197. Also if each integer stores 2 bytes of memory. Find the address of 4th element . (K=3)
1197-1198 1199-1200 1201-1202
1203-1204
Giveb:
W,width=2 bytes
K=4
Lower bound,lb=1
Upper bound,ub=10
Base address,base(a)= 1197
To find: loc(a[4])?
Loc(a[k])=base(a)+w(k-lb)
loc(a[4])= 1197 + 2(4- 1)
= 1197 +6
= 1203
traversing the entered array
WAP to insert an element at a given position.
WAP to delete an element from given position.
WAP to replace an element at given position.
WAP to print the smallest element of the array
Linear search
Time Complexity of Linear Search
• The best-case complexity is O(1) if the element is found in the first iteration
of the loop.
• The worst-case time complexity is O(n), if the search element is found at
the end of the array, provided the size of the array is n.
Binary Search
• Binary search can be implemented only
on a sorted list of items. If the elements
are not sorted already, we need to sort
them first.
• Procedure: 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.
1. Input size of array, array, element to be searched.
2. Set Low=0, high=size-1
3. Mid=(low+high)/2
4. While((low<=high) && (a[mid]!= element))
5. {
1. If(element<a[mid])
2. High=mid-1
3. else
4. low=mid+1
5. Mid=(low+high)/2
}
6. If(low>end)
7. Display not found
8. Else
9. Return found at location
Pre-requisite: elements in the array
should be sorted in ascending order.
• i is used for iteration through the array.
• first is used to hold the first array index.
• last is used to hold the last array index.
• middle holds the middle value calculated by
adding high and low and dividing it by 2.
• n is the number of elements in the array.
• search is the element to search.
• array is the array element of size 100.
SOrting-bubble sort
Selection sort
The selection sort algorithm sorts an array
by repeatedly finding the minimum
element (considering ascending order) from
unsorted part and putting it at the
beginning.
The algorithm maintains two subarrays in a
given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the
minimum element (considering ascending
order) from the unsorted subarray is picked
and moved to the sorted subarray.
Working of Selection Sort
1.Set the first element as minimum
2.Compare minimum with the second element. If the second
element is smaller than minimum, assign the second element
as minimum.
Compare minimum with the third element. Again, if the third
element is smaller, then assign minimum to the third element
otherwise do nothing. The process goes on until the last element.
3.After each iteration, minimum is placed in the front of the
unsorted list.
4.For each iteration, indexing starts from the first unsorted
element. Step 1 to 3 are repeated until all the elements are
placed at their correct positions.
Insertion sort
• Insertion sort is a sorting algorithm that places an unsorted
element at its suitable place in each iteration.
Working of Insertion Sort
Suppose we need to sort the following array.
1. The first element in the array is assumed to be sorted. Take the second element and store it
separately in key.
Compare key with the first element. If the first element is greater than key, then key is placed in front of the
first element.
2. Now, the first two elements are sorted.
Take the third element and compare it with the elements on the left of it. Placed it just behind
the element smaller than it. If there is no element smaller than it, then place it at the
beginning of the array.
3. Similarly, place every unsorted element at its correct position.
Time complexities
Algorithm Best case Average case Worst case
Linear search O(1) O(n) O(n)
Binary search O(1) O(logn) O(logn)
Bubble sort O(n*n) O(n*n) O(n*n)
Selection sort O(n*n) O(n*n) O(n*n)
Insertion sort O(n) O(n*n) O(n*n)
Lab Exercises on 1D array
1. WAP to input an array and traverse each element of the array.
2. WAP to find sum of all elements in an array.
3. Create a Menu driven program to insert and delete any element in an array at specific position.
4. WAP to replace an element at given position.
5. WAP to print the smallest element of the array
6. WAP to search a particular element in an array.(Linear search)
7. WAP to search a particular element in an array.(Binary Search)
8. WAP to implement Bubble Sort.
9. WAP to implement Selection Sort.
10. WAP to implement Insertion Sort.
Two dimensional Array
• The two dimensional array in C language
is represented in the form of rows and
columns, also known as matrix.
• It is also known as array of arrays or list
of arrays.
• The two dimensional, three dimensional
or other dimensional arrays are also
known as multidimensional arrays.
Declaration of two dimensional Array in
C
• We can declare an array in the C language in the following way:
• A simple example to declare two dimensional array:
• Here, 4 is the row number and 3 is the column number.
Initialization of 2D Array in C
While declaring it:
Taking input from the user:
Col0 Col1 Col2
Row0 a[0][0] a[0][1] a[0][2]
Row1 a[1][0] a[1][1] a[1][2]
Row2 A[2][0] a[2][1] a[2][2]
int a[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
printf(“enter the arary”); Taking input
scanf(“%d”,&a[i][j]);
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++) Giving output
{
printf(“the array is: %d”,a[i][j]);
printf(“t”);
}
Printf(“n”);
}
Two dimensional array example in C
Memory Representation of 2-D Array
Row Major Order
Loc(a[i][j])=base(a)+w[n(i-lbr)+(j-lbc)]
Where,
Base(a)= base address of array
W= bytes per word
N= total number of col.
I= index of element
Lbr= lower bound of row
J= index of element
Lbc= lower bound of col.
Column Major Order
Loc(a[i][j])=base(a)+w[(i-lbr)+m(j-lbc)]
Where,
Base(a)= base address of array
W= bytes per word
m= total number of rows.
I= index of element
Lbr= lower bound of row
J= index of element
Lbc= lower bound of col.
Numerical
Question:
Consider a 2D array [3,…...,10:2,…..7]. Suppose the base address of
the array is 1197. Find the location of a[5][4] if each element
requires 4 bytes for its storage. Find the location if the elements
are arranged in
1) row major order
2.) col major order
Addition & Subtraction of Two Matrices
Point to Remember:
Two matrices can be added or subtracted if they have same dimensions I.e; rows and columns of first
matrix should be equal to rows and columns of second matrix.
Program to perform addition of two matrices
#include<stdio.h>
#include<conio.h>
Void main()
{
int a[2][2],b[2][2],c[2][2];
for (int i=0;i<2;i++)
{
for (int j=0;j<2;j++)
{
printf(“enter a[][]”);
scanf(“%d”,&a[i][j]);
}
}
A[2][2]
Col0Col1
Row0 1 2
Row1 3 4
B[2][2]
Col0Col1
Row0 5 6
Row1 7 8
C[2][2]
Col0Col1
Row0 6 8
Row1 10 12
C[0][0]=a[0][0]+b[0][0]
C[0][1]=a[0][1]+b[0][1]
for (int i=0;i<2;i++)
{
for (int j=0;j<2;j++)
{
printf(“enter b[][]”);
scanf(“%d”,&b[i][j]);
}
}
for (int i=0;i<2;i++)
{
for (int j=0;j<2;j++)
{
c[i][j]=a[i][j]+ b[i][j];
}
}
for (int i=0;i<2;i++)
{
for (int j=0;j<2;j++)
{
printf(“c[i][j] : %d”,c[i][j]);
}
}
TRANSPOSE OF A MATRIX
Row becomes column and
column becomes row.
Multiplication of two matrices
Lab exercise for 2-D Array
1. Write a program to enter elements in a matrix and display them
where rows and columns are entered by the user.
2. WAP to add two matrices.
3. WAP to find the transpose of a matrix.
4. WAP to multiply two matrices.

More Related Content

Similar to Arrays in C.pptx (20)

Arrays
ArraysArrays
Arrays
 
Arrays.pptx
Arrays.pptxArrays.pptx
Arrays.pptx
 
Array ppt
Array pptArray ppt
Array ppt
 
Array.pdf
Array.pdfArray.pdf
Array.pdf
 
Arrays
ArraysArrays
Arrays
 
Arrays accessing using for loops
Arrays accessing using for loopsArrays accessing using for loops
Arrays accessing using for loops
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 
Cunit3.pdf
Cunit3.pdfCunit3.pdf
Cunit3.pdf
 
Basic of array and data structure, data structure basics, array, address calc...
Basic of array and data structure, data structure basics, array, address calc...Basic of array and data structure, data structure basics, array, address calc...
Basic of array and data structure, data structure basics, array, address calc...
 
Unit 4
Unit 4Unit 4
Unit 4
 
ARRAYS.pptx
ARRAYS.pptxARRAYS.pptx
ARRAYS.pptx
 
Arrays.pptx
Arrays.pptxArrays.pptx
Arrays.pptx
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
 
arrayppt.pptx
arrayppt.pptxarrayppt.pptx
arrayppt.pptx
 
Data structure array
Data structure  arrayData structure  array
Data structure array
 
Arrays
ArraysArrays
Arrays
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
 

Recently uploaded

Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...Call Girls in Nagpur High Profile
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 

Recently uploaded (20)

Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 

Arrays in C.pptx

  • 2. Definition • Defn: An array in C is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. • An array is a linear data structure which stores homogeneous(similar)data items. • The array is the simplest data structure where each data element can be randomly accessed by using its index number.
  • 3. Example: • C array is beneficial if you have to store similar elements. • Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. • So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code. • Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.
  • 4. Advantage of C Array 1) Code Optimization: Less code to the access the data. 2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily. 3) Easy to sort data: To sort the elements of array, we need a few lines of code only. 4) Random Access: We can access any element randomly using the array.
  • 5. Disadvantage of C Array 1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList.
  • 6. Array Terminology Array variable is composed with the following terms: • Size:total number of elements in an array • Type: data type of declared array. • Base:address of the first element of the array. • Index:Location or index value of array element. • Range:Value from lower bound to upper bound. • Word:indicates the space required for an element.
  • 7. Declaration of C Array when array size is given: • We can declare an array in the c language in the following way: • the example to declare array: • Here, int is the data_type, marks is the array_name and 5 is the array_size.
  • 8. Declaration of C Array when array size is not known before compilation: data type array_name []; //size will depend upon the elements entered by user at run time. Example: int a[];
  • 9. Initialization of C Array At the time of declaration: • A simple way to initialize array is by index. • array index starts from 0 and ends with [SIZE - 1]. int a[5]={10,20,30,40,50}
  • 10. Taking input from the user: void main() { int a[5]; for(int i=0;i<5;i++) { to take input printf(“enter the array element”); from the user scanf(“%d”,&a[i]); } for(int i=0;i<5;i++) { to display output printf(“the array is: %d”,a[i]); to the user } } A i=0<5 true a[0] =5 i=1<5 true A[1]= 7 i=2<5 true A[2]=9 i=3<5 true A[3]=4 i=4<5 true A[4]=3 A[0] A[1] A[2] A[3] A[4] 5 7 9 4 3
  • 11. C array example 0 1 2 3 4 marks[0] marks[1] marks[2] marks[3] marks[4] 80 60 70 85 75
  • 12. C Array: Declaration with Initialization • We can initialize the c array at the time of declaration. • In such case, there is no requirement to define size. So it can also be written as the following code.
  • 13. C array example: 0 1 2 3 4 marks[0] marks[1] marks[2] marks[3] marks[4] 20 30 40 50 60
  • 14. Memory Representation of elements of 1D- array • Loc(a[k])=base(a)+w(k-lb) • Size of an array =ub-lb+1 Where a[k]= element at kth location of an array base(a)= base address of an array. w= number of bytes per storage location k= position of element lb= lower bound of an array ub= upper bound of array 1. Consider an integer array a of 10 elements[0,1,…,9] such that first element is stored at 1197. Also if each integer stores 2 bytes of memory. Find the address of 4th element . (K=3) 1197-1198 1199-1200 1201-1202 1203-1204 Giveb: W,width=2 bytes K=4 Lower bound,lb=1 Upper bound,ub=10 Base address,base(a)= 1197 To find: loc(a[4])? Loc(a[k])=base(a)+w(k-lb) loc(a[4])= 1197 + 2(4- 1) = 1197 +6 = 1203
  • 16. WAP to insert an element at a given position.
  • 17. WAP to delete an element from given position.
  • 18. WAP to replace an element at given position.
  • 19. WAP to print the smallest element of the array
  • 21. Time Complexity of Linear Search • The best-case complexity is O(1) if the element is found in the first iteration of the loop. • The worst-case time complexity is O(n), if the search element is found at the end of the array, provided the size of the array is n.
  • 22. Binary Search • Binary search can be implemented only on a sorted list of items. If the elements are not sorted already, we need to sort them first. • Procedure: 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. 1. Input size of array, array, element to be searched. 2. Set Low=0, high=size-1 3. Mid=(low+high)/2 4. While((low<=high) && (a[mid]!= element)) 5. { 1. If(element<a[mid]) 2. High=mid-1 3. else 4. low=mid+1 5. Mid=(low+high)/2 } 6. If(low>end) 7. Display not found 8. Else 9. Return found at location Pre-requisite: elements in the array should be sorted in ascending order.
  • 23. • i is used for iteration through the array. • first is used to hold the first array index. • last is used to hold the last array index. • middle holds the middle value calculated by adding high and low and dividing it by 2. • n is the number of elements in the array. • search is the element to search. • array is the array element of size 100.
  • 24.
  • 26. Selection sort The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. 1) The subarray which is already sorted. 2) Remaining subarray which is unsorted. In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.
  • 27. Working of Selection Sort 1.Set the first element as minimum 2.Compare minimum with the second element. If the second element is smaller than minimum, assign the second element as minimum. Compare minimum with the third element. Again, if the third element is smaller, then assign minimum to the third element otherwise do nothing. The process goes on until the last element. 3.After each iteration, minimum is placed in the front of the unsorted list. 4.For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are repeated until all the elements are placed at their correct positions.
  • 28.
  • 29.
  • 30. Insertion sort • Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each iteration.
  • 31. Working of Insertion Sort Suppose we need to sort the following array. 1. The first element in the array is assumed to be sorted. Take the second element and store it separately in key. Compare key with the first element. If the first element is greater than key, then key is placed in front of the first element.
  • 32. 2. Now, the first two elements are sorted. Take the third element and compare it with the elements on the left of it. Placed it just behind the element smaller than it. If there is no element smaller than it, then place it at the beginning of the array.
  • 33. 3. Similarly, place every unsorted element at its correct position.
  • 34.
  • 35. Time complexities Algorithm Best case Average case Worst case Linear search O(1) O(n) O(n) Binary search O(1) O(logn) O(logn) Bubble sort O(n*n) O(n*n) O(n*n) Selection sort O(n*n) O(n*n) O(n*n) Insertion sort O(n) O(n*n) O(n*n)
  • 36. Lab Exercises on 1D array 1. WAP to input an array and traverse each element of the array. 2. WAP to find sum of all elements in an array. 3. Create a Menu driven program to insert and delete any element in an array at specific position. 4. WAP to replace an element at given position. 5. WAP to print the smallest element of the array 6. WAP to search a particular element in an array.(Linear search) 7. WAP to search a particular element in an array.(Binary Search) 8. WAP to implement Bubble Sort. 9. WAP to implement Selection Sort. 10. WAP to implement Insertion Sort.
  • 37. Two dimensional Array • The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. • It is also known as array of arrays or list of arrays. • The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.
  • 38. Declaration of two dimensional Array in C • We can declare an array in the C language in the following way: • A simple example to declare two dimensional array: • Here, 4 is the row number and 3 is the column number.
  • 39. Initialization of 2D Array in C While declaring it: Taking input from the user: Col0 Col1 Col2 Row0 a[0][0] a[0][1] a[0][2] Row1 a[1][0] a[1][1] a[1][2] Row2 A[2][0] a[2][1] a[2][2]
  • 40. int a[3][3]; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { printf(“enter the arary”); Taking input scanf(“%d”,&a[i][j]); } } for(int i=0;i<3;i++) { for(int j=0;j<3;j++) Giving output { printf(“the array is: %d”,a[i][j]); printf(“t”); } Printf(“n”); }
  • 41. Two dimensional array example in C
  • 43. Row Major Order Loc(a[i][j])=base(a)+w[n(i-lbr)+(j-lbc)] Where, Base(a)= base address of array W= bytes per word N= total number of col. I= index of element Lbr= lower bound of row J= index of element Lbc= lower bound of col. Column Major Order Loc(a[i][j])=base(a)+w[(i-lbr)+m(j-lbc)] Where, Base(a)= base address of array W= bytes per word m= total number of rows. I= index of element Lbr= lower bound of row J= index of element Lbc= lower bound of col.
  • 44. Numerical Question: Consider a 2D array [3,…...,10:2,…..7]. Suppose the base address of the array is 1197. Find the location of a[5][4] if each element requires 4 bytes for its storage. Find the location if the elements are arranged in 1) row major order 2.) col major order
  • 45. Addition & Subtraction of Two Matrices Point to Remember: Two matrices can be added or subtracted if they have same dimensions I.e; rows and columns of first matrix should be equal to rows and columns of second matrix.
  • 46. Program to perform addition of two matrices #include<stdio.h> #include<conio.h> Void main() { int a[2][2],b[2][2],c[2][2]; for (int i=0;i<2;i++) { for (int j=0;j<2;j++) { printf(“enter a[][]”); scanf(“%d”,&a[i][j]); } } A[2][2] Col0Col1 Row0 1 2 Row1 3 4 B[2][2] Col0Col1 Row0 5 6 Row1 7 8 C[2][2] Col0Col1 Row0 6 8 Row1 10 12 C[0][0]=a[0][0]+b[0][0] C[0][1]=a[0][1]+b[0][1]
  • 47. for (int i=0;i<2;i++) { for (int j=0;j<2;j++) { printf(“enter b[][]”); scanf(“%d”,&b[i][j]); } } for (int i=0;i<2;i++) { for (int j=0;j<2;j++) { c[i][j]=a[i][j]+ b[i][j]; } } for (int i=0;i<2;i++) { for (int j=0;j<2;j++) { printf(“c[i][j] : %d”,c[i][j]); } }
  • 48. TRANSPOSE OF A MATRIX Row becomes column and column becomes row.
  • 49.
  • 51.
  • 52. Lab exercise for 2-D Array 1. Write a program to enter elements in a matrix and display them where rows and columns are entered by the user. 2. WAP to add two matrices. 3. WAP to find the transpose of a matrix. 4. WAP to multiply two matrices.