SlideShare a Scribd company logo
1 of 22
ARRAYS IN C
Arrays in C
 OUTLINE


♦ Review of Arrays in C
♦ Declaration and Initialization of Arrays
♦ Sorting: Bubble Sort
♦ Searching: Linear and Binary Search
Arrays
 Arrays are defined to be a sequence/set of data
  elements of the same type. Having an array, each
  array element can be accessed by its position in the
  sequence of the array.
♦ Decleration of the Arrays: Any array declaration
  contains: the array name, the element type and the
  array size.
 Examples:
 int a[20], b[3],c[7];
 float f[5], c[2];
 char m[4], n[20];
Arrays
 Initialisation of an array is the process of
  assigning initial values. Typically declaration
  and initialisation are combined.
 Examples:
 int a[4]={1,3,5,2};
 float, b[3]={2.0, 5.5, 3.14};
 char name[4]= {‘E’,’m’,’r’,’e’};
 int c[10]={0};
Example
 Write a program to calculate and print the average of the following array
    of integers.
   ( 4, 3, 7, -1, 7, 2, 0, 4, 2, 13)
   #include<stdio.h>
   #define size 10
   int main()
   {
   int x[10]={4,3,7,-1,7,2,0,4,2,13}, i, sum=0;
   float av;
   for(i=0,i<=size-1;i++)
   sum = sum + x[i];
   av = (float)sum/size;
   printf(“The average of the numbers=%.2fn”, av);
   return 0;
   }
Sorting
 Sorting an array is the ordering the array elements
  in ascending (increasing -from min to max) or
  descending (decreasing – from max to min) order.
 Example:
 {2 1 5 3 2} →{1, 2, 2, 3, 5} ascending order
 {2 1 5 3 2} →{5, 3, 2, 2, 1} descending order
Bubble Sort
 Smaller values in the list gradually “bubble”
  their way upward to the top of the array.
 The technique makes several passes through
  the array. On each pass successive pairs of
  elements are compared. If the pair is in
  increasing order (or equal) the pair is
  unchanged. If a pair is in descending order,
  their values are swapped in the array:
Bubble Sort
Pass = 1          Pass = 2           Pass = 3           Pass=4

  21532              12325              12235            12235

  12532              12325              12235            12235

  12532              12325              12235            12235

  12352              12235              12235            12235

  12325              12235              12235            12235
Underlined pairs show the comparisons. For each pass there are size-1
 comparisons.
Total number of comparisons= (size-1)2
Bubble Sort C Code
   /* This program sorts the array elements in the ascending order*/
   #include <stdio.h>
   #define SIZE 5
   void BubbleSort(int [ ]);
   int main()
   {
   int a[SIZE]= {2,1,5,3,2};
   int i;
   printf(“The elements of the array before sortingn”);
   for (i=0; i<= SIZE-1; i++)
   printf(“%4d”, a[i]);
   BubbleSort(a);
   printf(“nnThe elements of the array after sortingn”);
   for (i=0; i<= SIZE-1; i++)
   printf(“%4d”, a[i]);
   return 0;
   }
void BubbleSort(int A[ ])
   void BubbleSort(int A[ ])
   {
   int i, pass, hold;
   for (pass=1; pass<= SIZE-1; pass++){
       for (i=0; i<= SIZE-2; i++) {
       if(A[i] >A[i+1]){
           hold =A[i];

           A[i]=A[i+1];

           A[i+1]=hold;

           }

       }
 }
 }
Example
 Write a program to determine the median of
  the array given below:
        (9, 4, 5, 1, 7, 78, 22, 15, 96, 45)
 Note that the median of an array is the middle
  element of a sorted array.
Example
/* This program determines the median of an array*/
#include <stdio.h>
#define SIZE 10
void BubbleSort(int []);
int main()
{
int a[SIZE]= {9, 4, 5, 1, 7, 78, 22, 15, 96, 45}, median;
int i;
printf(“The elements of the input array isn”);
for (i=0; i<= SIZE-1; i++)
printf(“%4d”, a[i]);
BoubleSort(a);
printf(“The elements of the sorted array isn”);
for (i=0; i<= SIZE-1; i++)
printf(“%4d”, a[i]);
median = a[SIZE/2];
printf(“The median of the array is=%d”, median);
return 0;
}
Example
  void BubbleSort(int A[ ])
  {
  int i, pass, hold;
  for (pass=1; pass<= SIZE-1; pass++){
  for (i=0; i<= SIZE-2; i++) {
  if(A[i] >A[i+1]){
  hold =A[i];
  A[i]=A[i+1];
  A[i+1]=hold;
  }
  }
  }
  }
Searching
 The process of finding a particular element of an
  array is called searching. There two popularsearching
  techniques:
 Linear search and binary search.
 The linear search compares each array element with
  the search key.
 If the search key is a member of the array, typically
  the location of the search key is reported to indicate
  the presence of the search key in the array.
  Otherwise, a sentinel value is reported to indicate the
  presence of the search key in the array.
Linear Search
 Each member of the array is visited until the
  search key is found.
 Example:
 Write a program to search for the search key
  entered by the user in the following array:
        (9, 4, 5, 1, 7, 78, 22, 15, 96, 45)
 You can use the linear search in this
  example.
Linear Search
   /* This program is an example of the Linear Search*/
   #include <stdio.h>
   #define SIZE 10
   int LinearSearch(int [], int);
   int main()
   {
   int a[SIZE]= {9, 4, 5, 1, 7, 78, 22, 15, 96, 45}, key, pos;
   printf(“Enter the Search Keyn”);
   scanf(“%d”,&key);
   pos = LinearSearch(a, key);
   if(pos == -1)
   printf(“The search key is not in the arrayn”);
   else
   printf(“The search key %d is at location %dn”, key, pos);
   return 0;
   }
int LinearSearch (int b[ ], int skey)
int LinearSearch (int b[ ], int skey)
{
int i;
for (i=0; i<= SIZE-1; i++)
if(b[i] == skey)
return i;
return -1;
}
Binary Search
 Given a sorted array Binary Search
  algorithm can be used to perform fast
  searching of a search key on the sorted array.
 The following program uses pointer notation
  to implement the binary search algorithm for
  the search key entered by the user in the
  following array:
       (3, 5, 9, 11, 15, 17, 22, 25, 37, 68)
Binary Search
 #include <stdio.h>
 #define SIZE 10
 int BinarySearch(int [ ], int);
 int main()
 {
 int a[SIZE]= {3, 5, 9, 11, 15, 17, 22, 25, 37, 68}, key, pos;
 printf(“Enter the Search Keyn”);
 scanf(“%d”,&key);
 pos = BinarySearch(a, key);
 if(pos == -1)
 printf(“The search key is not in the arrayn”);
 else
 printf(“The search key %d is at location %dn”, key, pos);
 return 0;
 }
int BinarySearch (int A[], int skey)
  int BinarySearch (int A[], int skey)
  {
  int low=0,high=SIZE-1,middle;
  while(low <= high){
      middle= (low+high)/2;
      if(skey == A[middle])
         return middle;
      else if(skey <A[middle])
                high = middle-1;
            else
                low = middle+1;
      }
  return -1;
  }
Computational Complexity
 The Computational Complexity of the Binary
    Search algorithm is measured by the maximum
    (worst case) number of Comparisons it performs for
    searching operations.
   The searched array is divided by 2 for each
    comparison/iteration.
   Therefore, the maximum number of comparisons is
    measured by:
   log2(n) where n is the size of the array
   Example:
   If a given sorted array 1024 elements, then the
    maximum number of comparisons required is:
   log2(1024) = 10 (only 10 comparisons is enough)
Computational Complexity
 Note that the Computational Complexity of the
  Linear Search is the maximum number of
  comparisons you need to search the array. As you
  are visiting all the array elements in the worst case,
  then, the number of comparisons required is:
               n (n is the size of the array)
 Example:
 If a given an array of 1024 elements, then the
  maximum number of comparisons required is:
   n = 1024 (As many as 1024 comparisons may be
                           required)

More Related Content

What's hot (20)

C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
C Programming : Arrays
C Programming : ArraysC Programming : Arrays
C Programming : Arrays
 
C arrays
C arraysC arrays
C arrays
 
Arrays basics
Arrays basicsArrays basics
Arrays basics
 
Array in C
Array in CArray in C
Array in C
 
Lecture 15 - Array
Lecture 15 - ArrayLecture 15 - Array
Lecture 15 - Array
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Multi dimensional array
Multi dimensional arrayMulti dimensional array
Multi dimensional array
 
Arrays
ArraysArrays
Arrays
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Arrays in C
Arrays in CArrays in C
Arrays in C
 
Programming in c arrays
Programming in c   arraysProgramming in c   arrays
Programming in c arrays
 
2D Array
2D Array 2D Array
2D Array
 
Pf presntation
Pf presntationPf presntation
Pf presntation
 
Array in c
Array in cArray in c
Array in c
 
C++ programming (Array)
C++ programming (Array)C++ programming (Array)
C++ programming (Array)
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 
1 D Arrays in C++
1 D Arrays in C++1 D Arrays in C++
1 D Arrays in C++
 

Viewers also liked

Control structuresin c
Control structuresin cControl structuresin c
Control structuresin cVikash Dhal
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1Prerna Sharma
 
C – A Programming Language- I
C – A Programming Language- IC – A Programming Language- I
C – A Programming Language- IGagan Deep
 
HTML Basics 1 workshop
HTML Basics 1 workshopHTML Basics 1 workshop
HTML Basics 1 workshopJohn Allan
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2Prerna Sharma
 
How to Create an Array & types in PHP
How to Create an Array & types in PHP How to Create an Array & types in PHP
How to Create an Array & types in PHP Ajit Sinha
 
Arrays In C Language
Arrays In C LanguageArrays In C Language
Arrays In C LanguageSurbhi Yadav
 
HTML Start Up - Introduction to HTML
HTML Start Up - Introduction to HTMLHTML Start Up - Introduction to HTML
HTML Start Up - Introduction to HTMLGrayzon Gonzales, LPT
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to cHattori Sidek
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in CJeya Lakshmi
 
Tp1 compte rendu en langage c
Tp1 compte rendu en langage cTp1 compte rendu en langage c
Tp1 compte rendu en langage cEbrima NJIE
 
9. statements (conditional statements)
9. statements (conditional statements)9. statements (conditional statements)
9. statements (conditional statements)Way2itech
 
HTML - Basics and Good Practices
HTML - Basics and Good PracticesHTML - Basics and Good Practices
HTML - Basics and Good PracticesPriscila Negreiros
 

Viewers also liked (20)

Statements in C
Statements in CStatements in C
Statements in C
 
Control structuresin c
Control structuresin cControl structuresin c
Control structuresin c
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
C – A Programming Language- I
C – A Programming Language- IC – A Programming Language- I
C – A Programming Language- I
 
HTML Basics 1 workshop
HTML Basics 1 workshopHTML Basics 1 workshop
HTML Basics 1 workshop
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
How to Create an Array & types in PHP
How to Create an Array & types in PHP How to Create an Array & types in PHP
How to Create an Array & types in PHP
 
Arrays In C Language
Arrays In C LanguageArrays In C Language
Arrays In C Language
 
BASICS OF HTML
BASICS OF HTMLBASICS OF HTML
BASICS OF HTML
 
HTML Start Up - Introduction to HTML
HTML Start Up - Introduction to HTMLHTML Start Up - Introduction to HTML
HTML Start Up - Introduction to HTML
 
HTML basics
HTML basicsHTML basics
HTML basics
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in C
 
Tp1 compte rendu en langage c
Tp1 compte rendu en langage cTp1 compte rendu en langage c
Tp1 compte rendu en langage c
 
9. statements (conditional statements)
9. statements (conditional statements)9. statements (conditional statements)
9. statements (conditional statements)
 
C programming
C programmingC programming
C programming
 
C tutorials
C tutorialsC tutorials
C tutorials
 
Basics of HTML 5 for Beginners
Basics of HTML 5 for Beginners Basics of HTML 5 for Beginners
Basics of HTML 5 for Beginners
 
HTML - Basics and Good Practices
HTML - Basics and Good PracticesHTML - Basics and Good Practices
HTML - Basics and Good Practices
 

Similar to Arrays (20)

Arrays searching-sorting
Arrays searching-sortingArrays searching-sorting
Arrays searching-sorting
 
SlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdfSlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdf
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
 
Arrays
ArraysArrays
Arrays
 
Unit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTUREUnit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTURE
 
UNIT V.docx
UNIT V.docxUNIT V.docx
UNIT V.docx
 
CSEG1001Unit 3 Arrays and Strings
CSEG1001Unit 3 Arrays and StringsCSEG1001Unit 3 Arrays and Strings
CSEG1001Unit 3 Arrays and Strings
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
1D Array
1D Array1D Array
1D Array
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
C_Arrays.pptx
C_Arrays.pptxC_Arrays.pptx
C_Arrays.pptx
 
presentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.pptpresentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.ppt
 
07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
 
02 arrays
02 arrays02 arrays
02 arrays
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
 
array
arrayarray
array
 
design and analysis of algorithm Lab files
design and analysis of algorithm Lab filesdesign and analysis of algorithm Lab files
design and analysis of algorithm Lab files
 
Array
ArrayArray
Array
 
UNIT IV -Data Structures.pdf
UNIT IV -Data Structures.pdfUNIT IV -Data Structures.pdf
UNIT IV -Data Structures.pdf
 
Array
ArrayArray
Array
 

Recently uploaded

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 

Recently uploaded (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 

Arrays

  • 2. Arrays in C  OUTLINE ♦ Review of Arrays in C ♦ Declaration and Initialization of Arrays ♦ Sorting: Bubble Sort ♦ Searching: Linear and Binary Search
  • 3. Arrays  Arrays are defined to be a sequence/set of data elements of the same type. Having an array, each array element can be accessed by its position in the sequence of the array. ♦ Decleration of the Arrays: Any array declaration contains: the array name, the element type and the array size.  Examples:  int a[20], b[3],c[7];  float f[5], c[2];  char m[4], n[20];
  • 4. Arrays  Initialisation of an array is the process of assigning initial values. Typically declaration and initialisation are combined.  Examples:  int a[4]={1,3,5,2};  float, b[3]={2.0, 5.5, 3.14};  char name[4]= {‘E’,’m’,’r’,’e’};  int c[10]={0};
  • 5. Example  Write a program to calculate and print the average of the following array of integers.  ( 4, 3, 7, -1, 7, 2, 0, 4, 2, 13)  #include<stdio.h>  #define size 10  int main()  {  int x[10]={4,3,7,-1,7,2,0,4,2,13}, i, sum=0;  float av;  for(i=0,i<=size-1;i++)  sum = sum + x[i];  av = (float)sum/size;  printf(“The average of the numbers=%.2fn”, av);  return 0;  }
  • 6. Sorting  Sorting an array is the ordering the array elements in ascending (increasing -from min to max) or descending (decreasing – from max to min) order.  Example:  {2 1 5 3 2} →{1, 2, 2, 3, 5} ascending order  {2 1 5 3 2} →{5, 3, 2, 2, 1} descending order
  • 7. Bubble Sort  Smaller values in the list gradually “bubble” their way upward to the top of the array.  The technique makes several passes through the array. On each pass successive pairs of elements are compared. If the pair is in increasing order (or equal) the pair is unchanged. If a pair is in descending order, their values are swapped in the array:
  • 8. Bubble Sort Pass = 1 Pass = 2 Pass = 3 Pass=4 21532 12325 12235 12235 12532 12325 12235 12235 12532 12325 12235 12235 12352 12235 12235 12235 12325 12235 12235 12235 Underlined pairs show the comparisons. For each pass there are size-1 comparisons. Total number of comparisons= (size-1)2
  • 9. Bubble Sort C Code  /* This program sorts the array elements in the ascending order*/  #include <stdio.h>  #define SIZE 5  void BubbleSort(int [ ]);  int main()  {  int a[SIZE]= {2,1,5,3,2};  int i;  printf(“The elements of the array before sortingn”);  for (i=0; i<= SIZE-1; i++)  printf(“%4d”, a[i]);  BubbleSort(a);  printf(“nnThe elements of the array after sortingn”);  for (i=0; i<= SIZE-1; i++)  printf(“%4d”, a[i]);  return 0;  }
  • 10. void BubbleSort(int A[ ])  void BubbleSort(int A[ ])  {  int i, pass, hold;  for (pass=1; pass<= SIZE-1; pass++){  for (i=0; i<= SIZE-2; i++) {  if(A[i] >A[i+1]){  hold =A[i];  A[i]=A[i+1];  A[i+1]=hold;  }  }  }  }
  • 11. Example  Write a program to determine the median of the array given below: (9, 4, 5, 1, 7, 78, 22, 15, 96, 45)  Note that the median of an array is the middle element of a sorted array.
  • 12. Example /* This program determines the median of an array*/ #include <stdio.h> #define SIZE 10 void BubbleSort(int []); int main() { int a[SIZE]= {9, 4, 5, 1, 7, 78, 22, 15, 96, 45}, median; int i; printf(“The elements of the input array isn”); for (i=0; i<= SIZE-1; i++) printf(“%4d”, a[i]); BoubleSort(a); printf(“The elements of the sorted array isn”); for (i=0; i<= SIZE-1; i++) printf(“%4d”, a[i]); median = a[SIZE/2]; printf(“The median of the array is=%d”, median); return 0; }
  • 13. Example void BubbleSort(int A[ ]) { int i, pass, hold; for (pass=1; pass<= SIZE-1; pass++){ for (i=0; i<= SIZE-2; i++) { if(A[i] >A[i+1]){ hold =A[i]; A[i]=A[i+1]; A[i+1]=hold; } } } }
  • 14. Searching  The process of finding a particular element of an array is called searching. There two popularsearching techniques:  Linear search and binary search.  The linear search compares each array element with the search key.  If the search key is a member of the array, typically the location of the search key is reported to indicate the presence of the search key in the array. Otherwise, a sentinel value is reported to indicate the presence of the search key in the array.
  • 15. Linear Search  Each member of the array is visited until the search key is found.  Example:  Write a program to search for the search key entered by the user in the following array: (9, 4, 5, 1, 7, 78, 22, 15, 96, 45)  You can use the linear search in this example.
  • 16. Linear Search  /* This program is an example of the Linear Search*/  #include <stdio.h>  #define SIZE 10  int LinearSearch(int [], int);  int main()  {  int a[SIZE]= {9, 4, 5, 1, 7, 78, 22, 15, 96, 45}, key, pos;  printf(“Enter the Search Keyn”);  scanf(“%d”,&key);  pos = LinearSearch(a, key);  if(pos == -1)  printf(“The search key is not in the arrayn”);  else  printf(“The search key %d is at location %dn”, key, pos);  return 0;  }
  • 17. int LinearSearch (int b[ ], int skey) int LinearSearch (int b[ ], int skey) { int i; for (i=0; i<= SIZE-1; i++) if(b[i] == skey) return i; return -1; }
  • 18. Binary Search  Given a sorted array Binary Search algorithm can be used to perform fast searching of a search key on the sorted array.  The following program uses pointer notation to implement the binary search algorithm for the search key entered by the user in the following array: (3, 5, 9, 11, 15, 17, 22, 25, 37, 68)
  • 19. Binary Search #include <stdio.h> #define SIZE 10 int BinarySearch(int [ ], int); int main() { int a[SIZE]= {3, 5, 9, 11, 15, 17, 22, 25, 37, 68}, key, pos; printf(“Enter the Search Keyn”); scanf(“%d”,&key); pos = BinarySearch(a, key); if(pos == -1) printf(“The search key is not in the arrayn”); else printf(“The search key %d is at location %dn”, key, pos); return 0; }
  • 20. int BinarySearch (int A[], int skey) int BinarySearch (int A[], int skey) { int low=0,high=SIZE-1,middle; while(low <= high){ middle= (low+high)/2; if(skey == A[middle]) return middle; else if(skey <A[middle]) high = middle-1; else low = middle+1; } return -1; }
  • 21. Computational Complexity  The Computational Complexity of the Binary Search algorithm is measured by the maximum (worst case) number of Comparisons it performs for searching operations.  The searched array is divided by 2 for each comparison/iteration.  Therefore, the maximum number of comparisons is measured by:  log2(n) where n is the size of the array  Example:  If a given sorted array 1024 elements, then the maximum number of comparisons required is:  log2(1024) = 10 (only 10 comparisons is enough)
  • 22. Computational Complexity  Note that the Computational Complexity of the Linear Search is the maximum number of comparisons you need to search the array. As you are visiting all the array elements in the worst case, then, the number of comparisons required is: n (n is the size of the array)  Example:  If a given an array of 1024 elements, then the maximum number of comparisons required is: n = 1024 (As many as 1024 comparisons may be required)