Arrays Why we need data structure? Simple data types use a single memory cell to store a variable. Sometimes (for example scores of a class) it is more.

Slides:



Advertisements
Similar presentations
Numeric Types & Ranges. ASCII Integral Type Numerical Inaccuracies Representational error – Round-off error – Caused by coding a real number as a finite.
Advertisements

Introduction to C Programming
Chapter 9 Data Structures: Arrays and Structs Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Enumerated Types 4 Besides the built-in types, ANSI C allows the definition of user-defined enumerated types –To define a user-define type, you must give.
5 5 Arrays. OBJECTIVES In this lecture we will learn:  Case switch  To use the array data structure to represent a set of related data items.  To declare.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
1 CS 201 Passing Function as Parameter & Array Debzani Deb.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
1 Lecture 9  Arrays  Declaration  Initialization  Applications  Pointers  Declaration  The & and * operators  NULL pointer  Initialization  Readings:
 2006 Pearson Education, Inc. All rights reserved Arrays.
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
Chapter 9: Arrays and Strings
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
1 Chapter 7 Arrays. 2 Outline and Objective In this chapter we will Learn about arrays One-dimensional arrays Two-dimensional arrays Learn about searching.
Searching Arrays Linear search Binary search small arrays
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
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.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
Arrays Why we need data structure?
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
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR
 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.
Chapter 8 Arrays and Strings
1 DATA STRUCTURES: LISTS. 2 LISTS ARE USED TO WORK WITH A GROUP OF VALUES IN AN ORGANIZED MANNER. A SERIES OF MEMORY LOCATIONS CAN BE DIRECTLY REFERENCED.
Algorithm and Programming Array Dr. Ir. Riri Fitri Sari MM MSc International Class Electrical Engineering Dept University of Indonesia 15 March 2009.
Chapter 8 Arrays Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University of.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman CP 202 Chapter
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
ARRAYS 1 Week 2. Data Structures  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently 
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.
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 Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
1 Arrays and Vectors Chapter 7 Arrays and Vectors Chapter 7.
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.
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.
IN THE NAME OF ALLAH WHO IS THE MOST BENEFICENT AND MOST MERCIFUL.
 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.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
1 Chapter 7 Arrays. 2 Outline and Objective In this chapter we will Learn about arrays One-dimensional arrays Two-dimensional arrays Learn about searching.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Unit 6 Data Types and Arrays. Key Concepts Explicit and automatic conversion ASCII Enumerated types Function parameters Arrays Loops and arrays Passing.
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.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
Problem Solving and Program Design in C Chap. 7 Arrays Chow-Sing Lin.
Objectives You should be able to describe: One-Dimensional Arrays
Computer Programming BCT 1113
Chapter 7 Arrays.
Arrays and Records.
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
7 Arrays.
Data Structures (CS212D) Week # 2: Arrays.
7 Arrays.
ICS103: Programming in C Searching, Sorting, 2D Arrays
Presentation transcript:

Arrays Why we need data structure? Simple data types use a single memory cell to store a variable. Sometimes (for example scores of a class) it is more efficient to group data items together in main memory. C++ allows to group related data items together into a single composite data structure. Array is one such data structure. Array => A collection of data items of the same type.

Declaring & Referencing Arrays Array => collection of two or more adjacent memory cells (array elements). To set up an array in memory, we must declare - the name of the array and - the number of cells associated with it. int x[5]; Instructs the compiler to associate 5 memory cells with the name x Array x x[0]x[1]x[2]x[3] x[4] Subscripted variable => x[0] Read as x sub zero. array subscript

Array Subscripts Array subscript=> integer enclosed in brackets => its value in the range: 0 - (array_size - 1). Use of array subscript => to differentiate between the individual array elements. => to specify which array element is to be manipulated. We can use any expression of type int as an array subscript. typedef enum { monday, tuesday, wednesday, thursday,friday} class_days_t; int score[NUM_CLASS_DAYS]; Five class days

Array subscript typedef enum { monday, tuesday, wednesday, thursday,friday} class_days_t; int score[NUM_CLASS_DAYS]; We can use enumeration constants monday through friday as array subscripts since the they are represented by the integers 0 through 4. array subscript array value score [monday] score [tuesday] score [wednesday] score [thursday] score [friday]

Array Initialization If there are fewer initializers than elements in the array, the remaining elements are automatically initialized to zero. Example: int n[10] = {0}; Note: Arrays are not automatically initialized to zero. The programmer must at least initialize the first element to zero. Then the remaining elements will be automatically initialized to zero. Initialize an array with declaration: int odd_num[5] = {1, 3, 5, 7, 9}; int odd_num[] = {1, 3, 5, 7, 9}; Syntax error: int n[5] = {3, 5, 7, 9, 11, 12} 5 array elements6 initializers

Sequential Access We can access the elements of an array in sequence by using an indexed for loop. - Loop control variable runs from zero to one less than the array size. - Loop counter is used as an array index(subscript) to access each element in turn. Example: int cube[5], i; The for loop for (i = 0; i < 5; ++i) cube[i] = i * i * i; initializes this array :

Compute the Sum and the Sum of the Squares of all Data sum = x[0] +x[1] + x[2] + x[3] + x[4] + x[5] =  x[i]; sum_sqr = x[0] 2 +x[1] 2 + x[2] 2 + x[3] 2 + x[4] 2 + x[5] 2 =  x[i] 2 ; int i, sum = 0; int sum_sqr = 0; for (i = 0; i < MAX_ITEM; ++i) { sum += x[i]; or sum = sum + x[i]; sum_sqr += x[i] * x[i]; or sum_sqr = sum_sqr + x[i] * x[i]; }

Array Elements as Function Arguments #include int main() { int x[5] = {2, 4, 7, 9, 1}; cout << “The first element is: “ << x[0] << endl; } Another function: cin >> x[2]; Result: The first element is: 2 The scanned value will be stored in the array element x[2]. Array x

Array as Function Arguments We can also pass arrays as function arguments. An array name with no subscript appears in the argument list of the function. The address of the initial array element is stored in the function’s corresponding formal parameter. void fill_array ( int list[], // list of n integers int n, // number of list elements int in_value) // initial value { int i; for ( i = 0; i < n; ++i) list[i] = in_value; }

Array as Function Arguments Data Areas Before Return from fill_array(x, 5, 1) list n in_value i [0] [1] [2] [3] [4] x Calling function Data Area Function fill_array Data Area

Array as Function Arguments The function manipulates the original array, not its own personal copy. So an assignment to one of the array elements by a statement in the function changes the contents of the original array. list[i] = in_value; ANSI C++ provides a qualifier const to notify the C++ compiler that - the array is only an input to the function and - the function should not be allowed to modify array elements. - the elements of the array become constant in the function body. - any attempt to modify an element of the array in the function body results in a compile time error. Example: int get_max(const int list[], // input- list of n integers int n) // input- number of list elements

Returning an Array Result In C++, it is not legal for a function’s return type to be an array. It requires the use of an output parameter to send the result array back to the calling function. Example: void add_arrays(const int arg1[], // input const int arg2[], // input int argsum[], // output int n) // input { for (i = 0; i < n; ++i) argsum[i] = arg1[i] + arg2[i]; // adds corresponding elements // of arg1 and arg2 }

Why we apply Static to a Local Array Declaration? We can apply static to a local array declaration so that - the array is not created and initialized each time the function is called, and - the array is not destroyed each time the function is exited in the program. - this reduces program execution time particularly for programs with frequently called functions that contain large arrays.

Stacks A stack is a data structure in which only the top element can be accessed. Example: A stack of plates in cafeteria. A customer always takes the top plate. When a plate is removed, the plate beneath it moves to the top. C+2C+2 Stack of three charactersTop of the stack Push => storing an item in a stack pop => removing an item from a stack

Function push void push(char stack[], // input/output - the stack char item, // input - data being pushed onto the stack int *top, // input/output - pointer to top of stack int max_size) // input - maximum size of stack { if (*top < max_size - 1) { ++(*top); stack[*top] = item; }

Function Pop char pop(char stack[], // input/output - the stack int *top) // input/output - pointer to top of stack { char item; // value popped off the stack if (*top >= 0) { item = stack[*top]; --(*top); } else item = STACK_EMPTY; return (item); }

How to create a stack using Array? char s[STACK_SIZE]; int s_top = -1; The statements : push(s, ‘2’, &s_top, STACK_SIZE); push(s, ‘+’, &s_top, STACK_SIZE); push(s, ‘C’, &s_top, STACK_SIZE); create the stack : pop(s, &s_top); create the stack: C+2C

Searching an Array We search an array to determine the location of a particular value (target). Example: We need to search an array to determine the score of a particular student. Two popular techniques: linear search and binary search Linear search: To search an array, first we need to know the array element value we are seeking ( target). Then we have to examine each array element whether it matches the target by using a loop. When the target is found, the search loop should be exited.

Algorithm for Searching (Linear) an Array 1Assume the target has not been found. 2Start with the initial array element. 3Repeat while the target is not found and there are more array elements 4 if the current element matches the target 5 Set a flag to indicate that the target has been found. else 6 Advance to the next array element. 7if the target was found 8 Return the target index as the search result. else 9 Return -1 as the search result.

Function for Linear Searching of an Array constant NOT_FOUND = -1; int search(const int arr[], int target, int n) { int i = 0, found = 0, where; while (!found && i < n) // Compare each element to target { if (arr[i] == target) found = 1; else ++i; } if (found) // Returns index of element matching target or where = i; // NOT_FOUND else where = NOT_FOUND; return (where); }

Binary Search The binary search algorithm eliminates half of the elements in the array being searched after each comparison. The algorithm locates the middle element of the array and compares it to the target. If they are equal, the target is found and the array subscript of that element is returned. If they are not equal, the problem is reduced to searching one half of the array. If the target is less than the middle element of the array, the first half of the array is searched. Otherwise the second half of the array is searched. If the target is not found in the specified subarray, the algorithm is repeated on one quarter of the original array. The search continues until the target is equal to the middle element of a subarray, or until the subarray contains one element that is not equal to the target.

Function for Binary Searching of an Array int binarySearch( int list[], int target, int low, int high ) { int middle; while ( low <= high ) { middle = ( low + high ) / 2; if ( target == list[middle] ) return middle; else if ( target < list[middle] ) high = middle - 1; else low = middle + 1; } return -1; }

Comparison of Linear and Binary Search Linear search compares each element of the array with the target. On average, therefore the program will compare the target with half of the elements of the array. Linear search works well for small arrays or for unsorted arrays. However, for large arrays linear searching is inefficient. For a large and sorted array, the high speed binary search technique can be used. In a worst case scenario, searching in an array of 1024 elements will take only 10 comparisons using a binary search. An array of one billion elements takes a maximum of 30 comparisons to find the target = 1024  = 1024 * 1024 * 1024 

Sorting an Array Many programs execute more efficiently if the data are sorted before processing. Example: Your grade reports can be sorted according to your student ID numbers. A bank sorts all checks by account number. Selection sort is a fairly simple but not very efficient sorting algorithm. To perform a selection sort of an array of n elements, first you have to locate the smallest element in the array. Then switch the smallest element with the element at subscript 0. Then locate the smallest element in the subarray with subscripts 1 through n -1. Then switch the the smallest (second smallest) element in the second position. And so on.

Algorithm for Selection Sort 1for each value of fill from 0 to n -2 2 Find index_of_min, the index of the smallest element in the unsorted subarray list[fill] through list[n -1]. 3 if fill is not the position of the smallest element (index_min) 4 Exchange the smallest element with the one at position fill.

Function select_sort int get_min_range (int list[], int first, int last); void select_sort (int list[], int n) { int fill, temp, index_of_min; for (fill = 0; fill < n -1; ++fill) { index_of_min = get_min_range(list, fill, n -1); if (fill != index_of_min) { temp = list[index_of_min]; list[list_of_min] = list[fill]; list[fill] = temp; }

Selection Sort Trace of selection sort Fill is 0. Find the smallest element in subarray list[0] through list[3] and swap it with list[0] Fill is 1. Find the smallest element in subarray list[1] through list[3] - no exchange needed. Fill is 2. Find the smallest element in subarray list[2] through list[3] and swap it with list[2].

Multidimensional Array Multidimensional array => array with two or more dimensions. We use two dimensional arrays to represent tables of data, matrices, and other two-dimensional objects. A two dimensional object is a tic-tac-toe board. The array declaration: char tictactoe[3][3]; or char tictactoe[][3]; The array initialization: char tictactoe [3][3] = {{‘ ‘, ‘ ‘, ‘ ‘}, {‘ ‘, ‘ ‘, ‘ ‘}, {‘ ‘, ‘ ‘, ‘ ‘}}; OOX OX OX X X Column Row tictactoe[0][2]

Array with Several Dimensions int enroll [MAXCRS][5][4] course campusyear Problem: College offers 100 (MAXCRS) courses at five different campuses. We numbered the freshman year 0, the sophomore year 1, and so on. Find the number of juniors in all classes at all campuses. Students will be counted once for each course in which they are enrolled. int i, j, num_junior; // number of juniors num_junior = 0; for ( i = 0; i < MAXCRS; ++i) for ( j = 0; j < 5; ++j) num_junior += enroll[i][j][2]; Used to store the enrollment data for a school.