Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Chapter 7: Arrays In this chapter, you will learn about
Programming and Data Structure
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
1 Lecture 9  Arrays  Declaration  Initialization  Applications  Pointers  Declaration  The & and * operators  NULL pointer  Initialization  Readings:
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
Programming Logic and Design Fourth Edition, Comprehensive
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Pointers Applications
1 Two-Dimensional Arrays. 2 Can be visualized as consisting m rows, each of n columns Syntax: datatype arrayname [row] [ column] ; Example: int val[3]
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic concepts and uses of arrays ❏ To be able to define C.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
CPS120: Introduction to Computer Science Arrays. Arrays: A Definition A list of variables accessed using a single identifier May be of any data type Can.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Lists in Python.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
chap8 Chapter 8 Arrays (Hanly) chap8 2 Data Structure Simple data types use a simple memory to store a variable. Data Structure: a.
A First Book of ANSI C Fourth Edition
Chapter 8 Arrays and Strings
Chapter 7 One-Dimensional Arrays 7.1 Arrays in C One of the more useful features of C is the ability to create arrays for storing a collection of related.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Algorithm and Programming Array Dr. Ir. Riri Fitri Sari MM MSc International Class Electrical Engineering Dept University of Indonesia 15 March 2009.
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
ARRAY Prepared by MMD, Edited by MSY1.  Introduction to arrays  Declaring arrays  Initializing arrays  Examples using arrays  Relationship with pointers.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 8: Arrays and Functions Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
Chapter 8: Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
CPS120: Introduction to Computer Science Lecture 15 Arrays.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
Arrays and Matrices. One-Dimensional Arrays An array is an indexed data structure All variables stored in an array are of the same data type An element.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Arrays Department of Computer Science. C provides a derived data type known as ARRAYS that is used when large amounts of data has to be processed. “ an.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Chapter 9: Sorting and Searching Arrays
Computer Programming BCT 1113
Arrays … The Sequel Applications and Extensions
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Chapter 8 Arrays Objectives
Chapter 8 Arrays Objectives
Arrays.
Presentation transcript:

Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism to organize the data. One common organizing technique, arrays, allows us to process the data as a group and as individuals elements. An array is a fixed-size, sequenced collection of elements of the same data type. An array has a name and has one or more elements which are referenced through an index (subscript ). Declaring an array - The general form for declaring a single- dimensioned array is: type name [size] ; Like other variables, arrays must be explicitly declared so that the compiler may allocate space for them in memory. Here, type declares the base type of the array which is the type of each element in the array. name is the name of the array which must follow the C naming rules. size defines how many elements the array will hold. The size of the array must have a value at compilation time and therefore must be a constant.

Arrays For example, to declare a 9-element array named first of type char you would use this statement. char first [ 9 ]; Type of elements contained in the array (i.e. int, char, double, etc.) array name array size - number of elements in the array. Must be a constant of type integer!! This declaration creates an array with 9 elements of type char. This tells the compiler to allocate 9 adjacent memory cells for type char values indexed from 0 to 8. The amount of storage required to hold an array is directly related to its type and size. For a single-dimension array, the total size in bytes is computed as shown here: total bytes = sizeof (type) * size of array first[0] first[1] first[2] first[3] first[4] first[5] first[6] first[7] first[8] Notice indexing starts with 0 Notice that the last subscript is one less the size of the array memory

Arrays Accessing Elements in Arrays - C uses an index to access individual elements in an array. The index must be an integral value or an expression that evaluates to an integral value. The simplest form for accessing an element is a numeric constant. Typically, however, the index is a variable or an expression. To access the fifth element in the array named first above use the expression: first [ 4 ] Notice that since the first subscript value is zero the fifth element would be 4 ( 0,1,2,3,4 ). The above expression results in the value stored in the content of the fifth element of array named first. The array’s name is a symbolic reference for the address to the first byte of the array. Whenever we use the array’s name, therefore, we are actually referring to the first byte of the array. The index represents an offset from the beginning of the array to the element being referred to. char *arrayP; arrayP = first; /* assigns the address of the first element of array named first to pointer arrayP */

Arrays Storing values in Arrays - If we want to store values in the array, we must either initialize the elements, read values from the keyboard, or assign values to each individual element. Initialization - all elements in an array can be done at the time of declaration, just like simple variables int numbers [ 5 ] = { 2, 3, 5, 7, 9 }; When the array is completely initialized, it is not necessary to specify the size of the array. int numbers [ ] = { 2, 4, 6, 8, 10 }; Notice the braces Values separated by commas Size not specified Number of values set the size of the array

Arrays If the number of values provided is less than the number of elements in the array, the unassigned elements are filled with zeros. int numbers [ 5 ] = { 2, 4 }; Individual elements can be assigned values using the assignment operator. A simple assignment statement for numbers would be: numbers [ 2 ] = 45 ; on the other hand you cannot assign one array to another array, even if they match fully in type and size. Another way to fill the array is to read the values from the keyboard or a file. This can be done using a loop: for ( i = 0; i < 5; i++ ) scanf ( “%d”, &numbers[ i ] );

Arrays C has no bounds checking on arrays. You could overwrite either end of an array and write into some other variable's data or even into the program’s code. As the programmer, it is your job to provide bounds checking where needed. For example, this code will compile without error, but is incorrect because the for loop will cause the array count to be overrun: int count [10], i; /* this causes count to be overrun */ for(i = 0; i < 100; i++ ) count [ i ] = i; So you want to plan your array logic carefully and fully test it.

Arrays Arrays and functions - To process arrays in a large program, you have to be able to pass them to functions. You can do this in two ways; pass individual elements or pass the whole array. Individual elements can be passed to a function like any ordinary variable. Of course it will be passed as a value parameter, which means that the function cannot change the value of the element. #include int main (void) { void print_square (int ); int i ; int base[ 5 ] = { 3, 7, 2, 4, 5 }; for ( i = 0; i < 5; i++) print_square ( base [ i ] ); return 0; } void print_square( int x ) { printf(“%d”, x * x ); return; }

Arrays If we want the function to operate on the whole array, we must pass the whole array. To do this C passes the address of the array. You must follow two rules to pass the whole array to a function: 1) The function must be called by passing only the name of the array(the address of the first element). 2) In the function definition, the formal parameter must be an array type: the size of the array does not need to be specified. #include int main (void) { double average (int [ ] ); double ave ; int base[ 5 ] = { 3, 7, 2, 4, 5 }; ave = average ( base );... return 0; } double average( int x [ ] ) { int i, sum = 0; for ( i = 0; i < 5; i ++ ) sum += x [ i ]; return ( sum / 5.0 ); }

Arrays Sorting Arrays - One of the most common applications in computer science is sorting, which is the process through which data are arranged according to their values. Sorting is the process of transforming a list into an equivalent list, in which the elements are arranged in ascending or descending order. Sorting lists are especially important in list searching because they facilitate search operations. Because of the importance of sorting in practical applications, many sorting techniques have been developed. Selection Sort - A list (array) is divided into sorted and unsorted. We first find the smallest element in the unsorted part of the list and then swap this element with the first element in the unsorted list. By doing this, the sorted list increases in size and the unsorted list decreases in size.

[0][1][2][3][4] Pass 1: Operation Find smallest of all five elements and swap it with numbers[ 0 ] numbers [ 5 ] [0][1][2][3][4] Pass 2: Find smallest of the last four elements and swap it with numbers[ 1 ] Arrays Selection Sort: [0][1][2][3][4] Pass 3: Find smallest of the last three elements and swap it with numbers[ 2 ] (already smallest) [0][1][2][3][4] Pass 4: Find smallest of the last two elements and swap it with numbers[ 3 ] [0][1][2][3][4] Sorted array: Done! (last element sorted) => sorted element

Arrays Selection Sort Algorithm void selectionSort (int list [ ], int last ) { void exchangeSmallest (int list[ ], int first, int last); int current; for ( current = 0 ; current < last ; current++) exchangeSmallest ( list, current, last); return; } void exchangeSmallest (int list [ ], int current, int last ) { int walker, smallest, tempData; smallest = current; for ( walker = current +1 ; walker <= last ; walker++) if (list[walker] < list[smallest] ) smallest = walker ; tempData = list[current]; list[current] = list[smallest]; list[smallest] = tempData; return; }

Arrays Bubble Sort - A list (array) is divided into sorted and unsorted. The smallest element is bubbled from the unsorted sublist and moved to the sorted sublist. By doing this, the sorted list increases in size and the unsorted list decreases in size [0][1][2][3][4] Pass 1: Operation Compare [ 3 ] to [ 4 ] and swap if [ 4 ] is less than [ 3 ] numbers [ 5 ] [0][1][2][3][4] Step 2: Compare [ 2 ] to [ 3 ] and swap if [ 3 ] is less than [ 2 ] [0][1][2][3][4] Step 3: Compare [ 1 ] to [ 2 ] and swap if [ 2 ] is less than [ 1 ] [0][1][2][3][4] Step 4: Compare [ 0 ] to [ 1 ] and swap if [ 1 ] is less than [ 0 ] [0][1][2][3][4] Step 1: Compare [ 3 ] to [ 4 ] and swap if [ 4 ] is less than [ 3 ] Step 1: Pass 2: [0][1][2][3][4] Step 2: Compare [ 2 ] to [ 3 ] and swap if [ 3 ] is less than [ 2 ]

=> sorted element [0][1][2][3][4] Pass 2 (continued): Operation Compare [ 1 ] to [ 2 ] and swap if [ 2 ] is less than [ 1 ] numbers [ 5 ] [0][1][2][3][4] Step 1: Compare [ 3 ] to [ 4 ] and swap if [ 4 ] is less than [ 3 ] [0][1][2][3][4] Step 3: Compare [ 2 ] to [ 3 ] and swap if [ 3 ] is less than [ 2 ] [0][1][2][3][4] Step 4: Compare [ 3 ] to [ 4 ] and swap if [ 4 ] is less than [ 3 ] [0][1][2][3][4] Done! Step 3: Sorted Array: Arrays Pass 3: Pass 4:

Arrays Bubble Sort Algorithm void bubbleSort (int list [ ], int last ) { void bubbleUp (int list[ ], int first, int last); int current; for ( current = 0 ; current < last ; current++) bubbleUp ( list, current, last); return; } void bubbleUp (int list [ ], int current, int last ) { int walker, tempData; for ( walker = last ; walker > current ; walker--) if (list[walker] < list[walker - 1] ) { tempData = list[walker] ; list[walker] = list[walker - 1]; list[walker - 1] = tempData; } return; }

Arrays Insertion Sort - A list (array) is divided into sorted and unsorted. In each pass, the first element of the unsorted sublist is picked up and transferred into the sorted sublist by inserting it at the appropriate place. By doing this, the sorted list increases in size and the unsorted list decreases in size [0][1][2][3][4] Pass 1: Operation Set temp to the value of [1], find the insertion point ( [0] ), shift elements to right of insertion point and copy temp to [0] numbers [ 5 ] [0][1][2][3][4] Pass 2: Insertion Sort: [0][1][2][3][4] Pass 3: [0][1][2][3][4] Pass 4: [0][1][2][3][4] Sorted array: Done! => sorted element Set temp to the value of [2], find the insertion point ( [0] ), shift elements to right of insertion point and copy temp to [0] Set temp to the value of [3], find the insertion point ( [0] ), shift elements to right of insertion point and copy temp to [0] Set temp to the value of [4], find the insertion point ( [3] ), shift elements to right of insertion point and copy temp to [3]

Arrays Insertion Sort Algorithm void insertSort (int list [ ], int last ) { void insertOne (int list[ ], int first); int current; for ( current = 1 ; current <= last ; current++) insertOne ( list, current); return; } void insertOne (int list [ ], int current) { int walker, located, temp; located = 0; temp = list[current]; for ( walker = current - 1; walker >= 0 && !located; ) if (temp < list[walker] ) { list[walker + 1] = list[walker]; walker-- ; } else located = 1 ; list [ walker + 1 ] = temp; return; }

Arrays Searching Arrays - Another common operation on arrays is the search operation. We search a list stored in an array to determine whether it contains an element that matches a given search key value. Sequential Search - The sequential search can be used to locate an item in any array. Generally you will use this technique only for small lists or lists that are not searched often. We start searching for the target value from the beginning of the list, and we continue until we find the target or we have reached the end of the list [0][1][2][3][4] Operation Compare [ 0 ] to key, stop if they match numbers [ 5 ] [0][1][2][3][4] Step 2: Sequential Search: [0][1][2][3][4] Step 3: [0][1][2][3][4] Key found: Step 1: Search key = 17 Compare [ 1 ] to key, stop if they match Compare [ 2 ] to key, stop if they match Done!

Arrays Sequential Search int seqSearch (int list [ ], int last, int target, int *locn ) { int looker; looker = 0; while ( looker < last && target != list[looker] ) looker++ *locn = looker; return ( target == list[looker] ); }

Arrays Binary Search - The binary search is a more efficient but requires the list to be sorted. The binary search starts by testing the data in the element at the middle of the array. This determines if the target is in the first half or the second half of the the list. If it is the first half we do not need to check the second half anymore. If it is the second half, we don’t need to test the first half any more. The process is repeated until we find the target or satisfy ourselves that it is not in the list. Operation Set first to 0 set last to 6 compute mid = 3 key > mid numbers [ 5 ] Step 2: Sequential Search: Step 1: Search key = 24 Set first to 4 compute mid = 5 key = mid Done! [0][1][2][3][5] firstlastmid 20 [4] 24 [6] [0][1][2][3][5] firstlastmid 20 [4] 24 [6] [0][1][2][3][5] 20 [4] 24 [6] Key found:

Arrays Two-Dimensional Arrays - Just as we can have arrays of integers, floating-point values, and characters, we can also have arrays of arrays. An array of one-dimensional arrays is called a two-dimensional array; an array of two dimensional arrays is called a three-dimensional array, and so on. scores [ 0 ] [ 0 ] 95 scores [ 0 ] [ 1 ] 82 scores [ 0 ] [ 2 ] 76 scores [ 1 ] [ 0 ] 92 scores [ 1 ] [ 1 ] 81 scores [ 1 ] [ 2 ] 99 scores [ 3 ] [ 0 ] 98 scores [ 3 ] [ 1 ] 69 scores [ 3 ] [ 2 ] 93 scores [ 2 ] [ 0 ] 89 scores [ 2 ] [ 1 ] 95 scores [ 2 ] [ 2 ] 95 Array declaration : int scores [ 4 ] [ 3 ]; Row 0 Row 1 Row 2 Row 3 Column 0Column 1Column 2 Array element value Array element reference Array element reference: scores [ i ] [ j ] Array name Row subscript Column subscript

Arrays Two-Dimensional Arrays initialization: int score [ 4 ] [ 3 ] = { { 90, 82, 76 }, { 92, 81, 99 }, { 89, 95, 95 }, { 98, 69, 93 } } Note commas between rows int score [ ] [ 3 ] = { { 90, 82, 76 }, { 92, 81, 99 }, { 89, 95, 95 }, { 98, 69, 93 } } To fill values from the keyboard use a nested loop: for ( row = 0 ; row < 4 ; row++) for (column = 0 ; column < 3; column ++) scanf(“%d”, &scores [ row ] [ column ] ); The first dimension can be omitted but all others must be specified.