arrays ce 102 algorithms and programming kto karatay university arrays are data structures...

25
Arrays CE 102 Algorithms and Programming KTO Karatay University rrays are data structures consisting of data items of the sam rays are not dynamic entities • they remain the same size once they are created • they don’t grow or shrink as the program executes

Upload: buck-hardy

Post on 01-Jan-2016

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Arrays

CE 102 Algorithms and Programming KTO Karatay University

• Arrays are data structures consisting of data items of the same type

• Arrays are not dynamic entities

• they remain the same size once they are created

• they don’t grow or shrink as the program executes

Page 2: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Arrays

CE 102 Algorithms and Programming KTO Karatay University

-45

6

0

72

1543

-89

0

62

-3

1

6453

-78arr[ 11 ]

arr[ 10 ]

arr[ 9 ]

arr[ 8]

arr[ 7 ]

arr[ 4 ]

arr[ 3 ]

arr[ 2 ]

arr[ 1 ]

arr[ 0 ]

arr[ 6 ]

arr[ 5 ]

Position number (index or subscript) of the element within array “arr”

Name of array (Note that all elements of this array have the same name, “arr”arr”)

First element is at index “0”

Page 3: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Declaring Arrays

When defining arrays, specifyWhen defining arrays, specify• NameName• Type of arrayType of array• Number of elementsNumber of elements

arrayType arrayName[ numberOfElements ];arrayType arrayName[ numberOfElements ];• Examples:Examples:

int c[ 10 ]; int c[ 10 ];

float myArray[ 3284 ];float myArray[ 3284 ]; Defining multiple arrays of same typeDefining multiple arrays of same type

• Format similar to regular variablesFormat similar to regular variables• Example:Example:

int int aa[ 100 ], [ 100 ], bb[ 27 ];[ 27 ];

CE 102 Algorithms and Programming KTO Karatay University

Page 4: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Declaring Arrays

InitializersInitializers

int n[ 5 ] = { 1, 2, 3, 4, 5 };int n[ 5 ] = { 1, 2, 3, 4, 5 };

• If not enough initializers, rightmost elements become 0If not enough initializers, rightmost elements become 0

int n[ 5 ] = { 0 } int n[ 5 ] = { 0 } All elements 0All elements 0

• If too manyIf too many,, a syntax error is produced a syntax error is produced

int n[ 5 ] = { 0int n[ 5 ] = { 0, 5, -7, 9, 2, 1, 8, 5, -7, 9, 2, 1, 8 } }

If size If size is is omitted, initializers determine itomitted, initializers determine it

int n[ ] = { 1, 2, 3, 4, 5 };int n[ ] = { 1, 2, 3, 4, 5 };

• 5 initializers, therefore 5 element array5 initializers, therefore 5 element array

CE 102 Algorithms and Programming KTO Karatay University

Page 5: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Example – Declaring and Using Arrays

CE 102 Algorithms and Programming KTO Karatay University

Page 6: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Example – Using Arrays as Index and Histogram Printing

CE 102 Algorithms and Programming KTO Karatay University

Page 7: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Character Arrays

SStrings are in fact sequences of characters, we cantrings are in fact sequences of characters, we can represent them also represent them also as plain arrays of char elements.as plain arrays of char elements.

For example, the following array:For example, the following array:char name[20]char name[20]

is an array that can store up to 20 elements of type char. It can be is an array that can store up to 20 elements of type char. It can be shown shown as:as:

In this array, In this array, we can store sequences of characters up to 20 characters we can store sequences of characters up to 20 characters long.long.

But we can also store shorter sequences.But we can also store shorter sequences. A special character is A special character is used to used to signalsignal the end of the valid sequence: the the end of the valid sequence: the

null characternull character which can be written as which can be written as ‘‘\0’\0’

name

D e e t \0m

D e e t F i l i z \0m

CE 102 Algorithms and Programming KTO Karatay University

Page 8: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Character Arrays

Initializing on declaration:Initializing on declaration:

char myword [] = { 'H', 'e', 'l', 'l', 'o', '\0' }; char myword [] = "Hello"; //initialization by a literal

A literal can not be assigned to char array after the declaration:A literal can not be assigned to char array after the declaration:

char text[10];text = “some text”;text = {‘H’,‘i’,‘/0’};

Content of char array can be modified letter by letter after initializationContent of char array can be modified letter by letter after initialization::

char text[30] = "Here is some text!";printf(“%s\n”,text);text[13] = 'w';text[14] = 'i';text[15] = 'n';text[16] = 'e'; printf(“%s\n”,text);

CE 102 Algorithms and Programming KTO Karatay University

Page 9: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Character Arrays

CE 102 Algorithms and Programming KTO Karatay University

• ExampleExample

char string1[] = "first";char string1[] = "first"; Null character '\0' terminates stringsNull character '\0' terminates strings string1 actually has 6 elementsstring1 actually has 6 elements

• It is equivalent toIt is equivalent to

char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };

• Can access individual charactersCan access individual characters

string1[ 3 ] is character ‘s’string1[ 3 ] is character ‘s’

• Array name is address of array, so Array name is address of array, so ““&&”” not needed for scanf not needed for scanf

scanf( "%s", string2 );scanf( "%s", string2 ); Reads characters until whitespace encounteredReads characters until whitespace encountered Can write beyond end of array, be carefulCan write beyond end of array, be careful

Page 10: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Example - Character Arrays

CE 102 Algorithms and Programming KTO Karatay University

Page 11: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Passing Arrays to Functions

CE 102 Algorithms and Programming KTO Karatay University

Passing arraysPassing arrays• To pass an array argument to a function, specify the name To pass an array argument to a function, specify the name

of the array without any brackets of the array without any brackets

int myArray[ 24 ];int myArray[ 24 ];

myFunction( myArray, 24 );myFunction( myArray, 24 ); Array size usually passed to function Array size usually passed to function

• Arrays passed call-by-reference Arrays passed call-by-reference • Name of array is address of first elementName of array is address of first element• Function knows where the array is storedFunction knows where the array is stored

Modifies original memory locationsModifies original memory locations Passing array elements Passing array elements

• Passed by call-by-valuePassed by call-by-value• Pass subscripted name (i.e., myArray[ 3 ]) to functionPass subscripted name (i.e., myArray[ 3 ]) to function

Page 12: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Passing Arrays to Functions

Function prototypeFunction prototype

void modifyArray( int b[], int arraySize );void modifyArray( int b[], int arraySize );

• Parameter names optional in prototypeParameter names optional in prototype int b[] could be written int []int b[] could be written int [] int arraySize could be simply intint arraySize could be simply int

void modifyArray(int [], int)void modifyArray(int [], int)

CE 102 Algorithms and Programming KTO Karatay University

Page 13: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Example – Array “Name” is equal to &Name[0]

CE 102 Algorithms and Programming KTO Karatay University

Page 14: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Example – Passing Arrays to Functions

CE 102 Algorithms and Programming KTO Karatay University

Page 15: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Example – Passing Arrays to Functions

CE 102 Algorithms and Programming KTO Karatay University

Page 16: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Example – const type qualifier with arrays

CE 102 Algorithms and Programming KTO Karatay University

Page 17: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Sorting Arrays

CE 102 Algorithms and Programming KTO Karatay University

Sorting dataSorting data• Important computing applicationImportant computing application• Virtually every organization must sort some data Virtually every organization must sort some data

Bubble sort (sinking sort) Bubble sort (sinking sort) • Several passes through the array Several passes through the array • Successive pairs of elements are compared Successive pairs of elements are compared

If increasing order (or identical ), no changeIf increasing order (or identical ), no change If decreasing order, elements exchangedIf decreasing order, elements exchanged

• RepeatRepeat Example:Example:

• original: 3 4 2 6 7original: 3 4 2 6 7• pass 1: 3 2 4 6 7pass 1: 3 2 4 6 7• pass 2: 2 3 4 6 7 pass 2: 2 3 4 6 7 • Small elements "bubble" to the topSmall elements "bubble" to the top

BubbleSort.cBubbleSort.c

Page 18: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Searching Arrays : Linear Search

Search an array for a Search an array for a key valuekey value Linear searchLinear search

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

• Example Example LinearSearch.c LinearSearch.c

CE 102 Algorithms and Programming KTO Karatay University

Page 19: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Searching Arrays : Binary Search

Binary search Binary search • For sorted arraysFor sorted arrays• Compares middle element with keyCompares middle element with key

If equal, match foundIf equal, match found If key < middle, looks in first half of arrayIf key < middle, looks in first half of array If key > middle, looks in last halfIf key > middle, looks in last half RepeatRepeat

• Very fast; at most n steps, where 2Very fast; at most n steps, where 2nn > number of elements > number of elements 30 element array takes at most 5 steps30 element array takes at most 5 steps

• 2255 > 30 so at most 5 steps > 30 so at most 5 steps

BinarySearch.cBinarySearch.c

CE 102 Algorithms and Programming KTO Karatay University

Page 20: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Multi-dimensional Arrays

Multidimensional arrays can be described as "arrays Multidimensional arrays can be described as "arrays of arrays".of arrays".

A two dimentional (2D) array can be imagined as a A two dimentional (2D) array can be imagined as a table made of elements all having the same data table made of elements all having the same data typetype

Arrays can be 1D, 2D, 3D or even more...Arrays can be 1D, 2D, 3D or even more...• 2D array having size 3x5 has 15 elements2D array having size 3x5 has 15 elements• 3D array having size 4x5x3 has 60 elements 3D array having size 4x5x3 has 60 elements • As dimension increase, array size grows quicklyAs dimension increase, array size grows quickly

CE 102 Algorithms and Programming KTO Karatay University

Page 21: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Multi-dimensional Arrays

Decleration of a 2D array:Decleration of a 2D array:• int matrix[3][5];int matrix[3][5];

• type name[row_size][column_size];type name[row_size][column_size];

Access to elements: matrix[1][3] = 12;Access to elements: matrix[1][3] = 12;

CE 102 Algorithms and Programming KTO Karatay University

Page 22: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Multi-dimensional Arrays

Row 0

Row 1

Row 2

Column 0 Column 1 Column 2 Column 3

a[ 0 ][ 0 ]

a[ 1 ][ 0 ]

a[ 2 ][ 0 ]

a[ 0 ][ 1 ]

a[ 1 ][ 1 ]

a[ 2 ][ 1 ]

a[ 0 ][ 2 ]

a[ 1 ][ 2 ]

a[ 2 ][ 2 ]

a[ 0 ][ 3 ]

a[ 1 ][ 3 ]

a[ 2 ][ 3 ]

Row subscript

Array nameColumn subscript

CE 102 Algorithms and Programming KTO Karatay University

Page 23: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Array Initialization

int a[3][4] = {1,2,3,4,5,6,7,8,9,0,1,2};int a[3][4] = {1,2,3,4,5,6,7,8,9,0,1,2};

int b[3][4] = {{1,2,3,4},{5,6,7,8},{9,0,1,2}};int b[3][4] = {{1,2,3,4},{5,6,7,8},{9,0,1,2}};

int c[3][4] = {{1,2,3,4},{5,6},{}};int c[3][4] = {{1,2,3,4},{5,6},{}};

1

5

9

2

6

0

3

7

1

4

8

2

1

5

0

2

6

0

3

0

0

4

0

0

• Examples Examples ArrayInitialization.c ArrayInitialization.cStudentGrades.cStudentGrades.c

• UUnspecified elements nspecified elements are are set to zeroset to zero

CE 102 Algorithms and Programming KTO Karatay University

Page 24: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Multi-dimensional Arrays (3D)

Decleration of a 3D array:Decleration of a 3D array:• int cube[4][4][4];int cube[4][4][4];• type name[row_size][column_size][depth_size];type name[row_size][column_size][depth_size];

Access to elements:

cube[2][3][0] = 8;cube[0][3][2] = 5;cube[0][1][3] = 6;

depth

columns

rows

6

8

5

6

8

5

CE 102 Algorithms and Programming KTO Karatay University

Page 25: Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic

Homework-2

CE 102 Algorithms and Programming KTO Karatay University

Write a C program that calculates mean, median and mode of an array entered by the user.

Mean Mean –– average average Median Median –– number in middle of sorted list number in middle of sorted list

• 1, 2, 3, 4, 5 1, 2, 3, 4, 5

• 3 is the median3 is the median Mode Mode –– number that occurs most often number that occurs most often

• 1, 1, 1, 2, 3, 3, 4, 5 1, 1, 1, 2, 3, 3, 4, 5

• 1 is the mode1 is the mode

The program will display the histogram of the array after finding the mode.