You are on page 1of 44

CS103

Computer Programming 2

Lecture 1: Arrays

Bicol University College of Science


CSIT Department
2nd Semester, 2019-2020
2

Introduction
• Arrays
– Structures of related data items
– Static entity – same size throughout program
– Dynamic data structures
3
Name of array
Arrays (Note that all
elements of this
• Array array have the
same name, c)
– Group of consecutive memory locations
– Same name and type c[0] -45
c[1] 6
• To refer to an element, specify c[2] 0
c[3] 72
– Array name c[4] 1543
– Position number c[5] -89
c[6] 0
• Format: c[7] 62

arrayname[ position number ] c[8] -3


c[9] 1
– First element at position 0 c[10] 6453
– n element array named c: c[11] 78

• c[ 0 ], c[ 1 ]...c[ n – 1 ]
Position number
of the element
within array c
4

Arrays
• Array elements are like normal variables
c[ 0 ] = 3;
printf( "%d", c[ 0 ] );

– Perform operations in subscript. If x equals 3


c[ 5 - 2 ] == c[ 3 ] == c[ x ]
5

Declaring Arrays
• When declaring arrays, specify
– Name
– Type of array
– Number of elements
arrayType arrayName[ numberOfElements ];
– Examples:
int c[ 10 ];
float myArray[ 3284 ];
• Declaring multiple arrays of same type
– Format similar to regular variables
– Example:
int b[ 100 ], x[ 27 ];
6

Examples Using Arrays


• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements become 0
int n[ 5 ] = { 0 }
• All elements 0
– If too many a syntax error is produced
– C arrays have no bounds checking
• If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
– 5 initializers, therefore 5 element array
Example: MonthlyRainfall
Problem: using
month mean rainfall (in mm)
Rainfall Table 0 30
• input month 1 40
2 45
• output mean rainfall 3 95
for that month 4 130
5 220
6 210
7 185
8 135
9 80
10 40
Example (cont): MonthlyRainfall (v.1)
#include <stdio.h>

int main()
{
int month;
int table[12] = { 30, 40, 45, 95, 130, 220,
210, 185, 135, 80, 40, 45 };

printf("Enter month: ");


scanf("%d", &month);

printf("Average rainfall: %d mm.\n", table[month-1]);

return 0;
}

rainfall1.c
Example (cont): MonthlyRainfall (v.1)
#include <stdio.h>

int main()
{
int month;
int table[12] = { 30, 40, 45, 95, 130, 220,
210, 185, 135, 80, 40, 45 };

printf("Enter month: ");


scanf("%d", &month);

printf("Average rainfall: %d mm.\n", table[month-1]);

return 0;
}
rainfall1.c
Input / Output of Arrays


Library functions printf() and scanf() do not know
about arrays
So we have to do I/O ourselves
Example: IORainfall-1
#include <stdio.h>
#define NMONTHS 12

/* Store and print rainfall */

int main()
{
int data[NMONTHS];
int month;

for ( month=0; month < NMONTHS; month++ )


{
scanf("%d", &data[month] );
}

...

rainio1.c
Example (cont): IORainfall-1
#include <stdio.h>
#define NMONTHS 12

/* Store and print rainfall */

int main()
{
int data[NMONTHS];
int month;

for ( month=0; month < NMONTHS; month++ )


{
scanf("%d", &data[month] );
}

...

rainio1.c
Example (cont): IORainfall-2 (v.1)
#include <stdio.h>
#define NMONTHS 12
...
/* Print from January to December */
for ( month=0; month < NMONTHS; month++ )
{
printf( "%d ", data[month] );
}
printf("\n");

/* Print from December to January */


for ( month = NMONTHS - 1; month >= 0; month-- )
{
printf( "%d ", data[month] );
}
printf("\n");
return 0;
}
rainio1.c
Example (cont): IORainfall-2 (v.1)
#include <stdio.h>
#define NMONTHS 12
...
/* Print from January to December */
for ( month=0; month < NMONTHS; month++ )
{
printf( "%d ", data[month] );
}
printf("\n");

/* Print from December to January */


for ( month = NMONTHS - 1; month >= 0; month-- )
{
printf( "%d ", data[month] );
}
printf("\n");
return 0;
}

rainio1.c
Example (cont): IORainfall-2 (v.2)
#include <stdio.h>
#define NMONTHS 12
...
/* Print from January to December */
for ( month=0; month < NMONTHS; month++ )
{
printf( "%5d ” , data[month] );
}
printf("\n");

/* Print from December to January */


for ( month = NMONTHS - 1; month >= 0; month-- )
{
printf( "%5d ” , data[month] );
}
printf("\n");

return 0;
}

rainio2.c
Handling Indices


Arrays have a fixed size

There is no built-in way of checking if the supplied
index is within range

We must check for valid indices ourselves
Example (cont): MonthlyRainfall (v.2)
#include <stdio.h>
#define MAXLEN 1024
int main()
{
int month;
char line[MAXLEN];
char dummy[MAXLEN];
int table[12] = { 30, 40, 45, 95, 130, 220, 210, 185, 135, 80, 40, 45 };

while(1)
{
printf("Enter month or ctrl-c to end: ");
fgets(line, MAXLEN, stdin);
if (sscanf(line, "%d%s", &month, dummy) != 1) /* valid input? */
{
printf("Invalid input. Try again.\n");
}
else if (1 <= month && month <= 12) /* input in range? */
{
printf("Average rainfall for month %d is %d mm.\n",month,table[month-1]);
}
else
{
printf("Month should be between 1 and 12. Try again.\n");
} rainfall2.c
}
return 0;
}
Example (cont): MonthlyRainfall-1 (v.3)
#include <stdio.h>
#define MAXLEN 1024
int rainfall(int month);
/* Main program to test rainfall() function */
int main()
{
int month;
char line[MAXLEN];
char dummy[MAXLEN];
while(1)
{
printf("Enter month or ctrl-c to end: ");
fgets(line, MAXLEN, stdin);
if (sscanf(line, "%d%s", &month, dummy) != 1)
{
printf("Invalid input. Try again.\n");
}
else if (1 <= month && month <= 12)
{
printf("Average rainfall for month %d is %d mm.\n",month,rainfall(month-
1));
}
else
{
printf("Month should be between 1 and 12. Try again.\n");
}
rainfall3.c
}
return 0;
}
Example (cont): MonthlyRainfall-2 (v.3)
/**********************************************************\
* NAME:
* int rainfall(int month)
* DESCRIPTION:
* Returns the mean monthly rainfall (in millimeters)
* in a given month
* PRE:
* The integer `month' must be between 0 and 11, where
* 0 = January, 1 = February, etc. Otherwise, the behaviour
* is undefined
* The local array `table' should be initialized to contain
* the average rainfall in a given month
* POST:
* It returns an integer value corresponding to the mean
* rainfall (in millimeters) for the given `month'
\**********************************************************/
int rainfall ( int month )
{
int table[12] = { 30, 40, 45, 95, 130, 220,
210, 185, 135, 80, 40, 45 };
return (table[month]);
} rainfall3.c
Example (cont): MonthlyRainfall-2 (v.3)
/**********************************************************\
* NAME:
* int rainfall(int month)
* DESCRIPTION:
* Returns the mean monthly rainfall (in millimeters)
* in a given month
* PRE:
* The integer `month' must be between 0 and 11, where
* 0 = January, 1 = February, etc. Otherwise, the behaviour
* is undefined
* The local array `table' should be initialized to contain
* the average rainfall in a given month
* POST:
* It returns an integer value corresponding to the mean
* rainfall (in millimeters) for the given `month'
\**********************************************************/
int rainfall ( int month )
{
int table[12] = { 30, 40, 45, 95, 130, 220,
210, 185, 135, 80, 40, 45 };
return (table[month]);
}
rainfall3.c
Passing Arrays to Functions


The array is passed
– as an array of unspecified size (int array[])
OR
– as a pointer (int *array)

Changes to the array within the function affect the
“original” array
Example (cont): IORainfall-1
(v.3)
#include <stdio.h>
#define NMONTHS 12

void loadRain ( int arrayPtr[] )


{
int month;

for (month=0; month < NMONTHS; month++)


{
scanf("%d", &arrayPtr[month]);
}
}
rainio3.c
Example (cont): IORainfall-2 (v.3)

void printRain ( const int arrayPtr[] )


{
int month;

for (month=0; month < NMONTHS; month++)


{
printf("%5d", arrayPtr[month]);
}

printf("\n");
}
rainio3.c
Example (cont): IORainfall-3 (v.3)
#include <stdio.h>
#define NMONTHS 12

void loadRain ( int arrayPtr[] );


void printRain ( const int arrayPtr[] );

/* Store and print rainfall */


int main()
{
int data[NMONTHS];

loadRain(data);
printRain(data);

return 0;
}
rainio3.c
Example: IORainfall -- v.3 (cont)
#include <stdio.h>
#define NMONTHS 12
void loadRain ( int arrayPtr[] );
void printRain ( const int arrayPtr[] );
/* Store and print rainfall */
int main()
{
int data[NMONTHS];
loadRain(data);
printRain(data);
return 0;
}
/* Read in rainfall for each month*/
void loadRain ( int arrayPtr[] )
{
int month;
for (month=0; month < NMONTHS; month++)
{ scanf("%d", &arrayPtr[month]); }
}
/* Print rainfall for each month*/
void printRain ( const int arrayPtr[] )
{
int month;
for (month=0; month < NMONTHS; month++)
{ printf("%5d", arrayPtr[month]); } rainio3.c
printf("\n");
}
26
Searching Arrays: Linear Search and
Binary Search
• Search an array for a key value
• Binary search
– For sorted arrays

• Linear search
– Useful for small and unsorted arrays
27

Searching Arrays: Linear Search


• Simple
• Compare each element of array with key value
• Useful for small and unsorted arrays
28

Searching Arrays: Linear Search


#include<stdio.h>

int main() Output 


{
How many elements? 4
int a[20],i,key,n;
printf("How many elements? "); Enter array elements:
scanf("%d",&n); 6891

printf("Enter array elements:\n"); Enter element to search: 9


for(i=0;i<n;++i)
scanf("%d",&a[i]); Element found at index 2
printf("\nEnter element to search: ");
scanf("%d",&key);

for(i=0;i<n;++i)
if(a[i]==key)
break;

if(i<n)
printf("\nElement found at index %d",i);
else
printf("Element not found");

return 0;
}
29

Searching Arrays: Binary Search


– For sorted arrays
– Compares middle element with key
• If equal, match found
• If key < middle, looks in first half of array
• If key > middle, looks in last half
• Repeat
– Very fast; at most n steps, where 2n > number of elements
• 30 element array takes at most 5 steps
– 25 > 30 so at most 5 steps
30

Searching Arrays: Binary Search


#include<stdio.h>
first=0;
int main() last=n-1;
{
int while(first<=last)
arr[50],i,n,key,flag=0,first,last,mid {
; mid=(first+last)/2;

printf("Enter size of array:"); if(key==arr[mid]){


scanf("%d",&n); flag=1;
printf("\nEnter array break;
element(ascending order)\n"); }
else
for(i=0;i<n;++i) if(key>arr[mid])
scanf("%d",&arr[i]); first=mid+1;
else
printf("\nEnter the element to last=mid-1;
search:"); }
scanf("%d",&key);
if(flag==1)
Enter size of array: 6 printf("\nElement found at
position %d",mid+1);
Enter array element(ascending order) else
20 27 40 50 58 99 printf("\nElement not found");

Enter the element to search: 27 return 0;


}
Element found at position 2
Sorting Arrays

Sorting data can be of utmost of importance.
Especially in situations where you need data
arranged in a specific order.

Sorting an array is the ordering of 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
Sorting Arrays
SORTING ALGORITHMS

Selection sort

Insertion Sort

Bubble sort

Merge sort

Quicksort

Heapsort
Sorting Arrays:Selection Sort
• This sorting algorithm, iterates through the array and
finds the smallest number in the array and swaps it
with the first element if it is smaller than the first
element. Next, it goes on to the second element and
so on until all elements are sorted.

• Algorithm for Selection Sort:


1)Set min to the first location
2)Search the minimum element in the array
3)Swap the first location with the minimum value in
the array
4)Assign the second element as min.
5)Repeat the process until we get a sorted array.
34

Sorting Arrays:Selection Sort


#include <stdio.h>
int main() {
int a[100], n, i, j, position, swap;

printf("Enter the size of array: ");


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

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


Enter the size of array: 4
position=i;
Enter the array elements: 3 7 9 2
for(j = i + 1; j < n; j++){
if(a[position] > a[j]) Array after sorting: 2 3 7 9
position=j;
}
if(position != i) {
swap=a[i];
a[i]=a[position];
a[position]=swap;
}
}
printf("Array after sorting: ");
for(i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}
Sorting Arrays: Insertion Sort
• Insertion Sort is a sorting algorithm where the array
is sorted by taking one element at a time. The
principle behind insertion sort is to take one element,
iterate through the sorted array & find its correct
position in the sorted array.

• Insertion Sort works in a similar manner as we arrange


a deck of cards.
Sorting Arrays: Insertion Sort
Algorithm for Insertion Sort:
1)If the element is the first one, it is already sorted.
2)Move to next element
3)Compare the current element with all elements in
the sorted array
4)If the element in the sorted array is smaller than
the current element, iterate to the next element.
Otherwise, shift all the greater element in the array
by one position towards the right
5)Insert the value at the correct position
6)Repeat until the complete list is sorted
Sorting Arrays: Insertion Sort
Example:
38

Sorting Arrays: Insertion Sort


/*Insertion Sort Function */

void insertionSort(int array[], int n)


{
int i, key, j;

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


{
key = array[i];
j = i - 1;

while (j >= 0 && array[j] > key)


{
array[j + 1] = array[j];
j = j - 1;
}

array[j + 1] = key;
}
}
Sorting Arrays: Merge Sort
• Merge sort is one of the most powerful sorting
algorithms.
• Merge Sort is one of the best examples of Divide &
Conquer algorithm.
• In Merge sort, we divide the array recursively in two
halves, until each sub-array contains a single element,
and then we merge the sub-array in a way that it
results into a sorted array. merge() function merges
two sorted sub-arrays into one, wherein it assumes
that array[l .. n] and arr[n+1 .. r] are sorted.
Sorting Arrays: Merge Sort
Algorithm for Insertion Sort:
Given an array of length, say n, we perform the following
steps to sort the array:
1)Divide the array into 2 parts of lengths n/2 and
n-n/2 respectively (if n is odd, round off the value of
n/2). Let us call these arrays as left half and right
half respectively.
2)Recursively sort the left half array and the right half
array.
3)Merge the left half array and right half-array to get
the full array sorted.
Sorting Arrays: Merge Sort
Sorting Arrays: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
Sorting Arrays: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
End of Lecture 1

You might also like