Review of Arrays and Pointers

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Chapter 7: Arrays In this chapter, you will learn about
1 Lecture 9  Arrays  Declaration  Initialization  Applications  Pointers  Declaration  The & and * operators  NULL pointer  Initialization  Readings:
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
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
 Pearson Education, Inc. All rights reserved Arrays.
1 Introduction to Arrays Problem: –Input 5 scores, compute total, average –Input Example –test scores,employees,temperatures.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
 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.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR
Chapter 8 Arrays and Strings
ARRAY Prepared by MMD, Edited by MSY1.  Introduction to arrays  Declaring arrays  Initializing arrays  Examples using arrays  Relationship with pointers.
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 
 Pearson Education, Inc. All rights reserved Arrays.
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.
Arrays Array – Group of contiguous memory locations Each memory location has same name Each memory location has same type.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
Chapter 8: Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
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.
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.
Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
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.
 2005 Pearson Education, Inc. All rights reserved Arrays.
Lecture #15 ARRAYS By Shahid Naseem (Lecturer). 2 ARRAYS DEFINITION An array is a sequence of objects of same data type. The objects in an array are also.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Lecture 4: Chapter 7 - Arrays Outline Declaring and Creating Arrays Examples Using Arrays References and Reference Parameters Passing Arrays to Methods.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
7.1 Introduction Arrays Arrays are data structures consisting of data items of the same type “Static” entities They remain the same size once they are.
Arrays Chapter 7.
Chapter 11 - JavaScript: Arrays
Arrays Chapter 7.
Data Structures I (CPCS-204)
An Introduction to Programming with C++ Sixth Edition
Arrays 2.
Computer Programming BCT 1113
Lecture 7 Arrays 1. Concept of arrays Array and pointers
© 2016 Pearson Education, Ltd. All rights reserved.
Chapter 6 Arrays DDC 2133 Programming II.
Chapter 7 Part 1 Edited by JJ Shepherd
Chapter 7 Arrays.
Module 2 Arrays and strings – example programs.
Arrays … The Sequel Applications and Extensions
Chapter 7 Single-Dimensional Arrays
Java How to Program, Late Objects Version, 10/e
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
7 Arrays.
CNG 140 C Programming (Lecture set 8)
Chapter 5 Arrays Introducing Arrays
EKT150 : Computer Programming
Arrays Outline Introduction Arrays Declaring Arrays
25 Searching and Sorting Many slides modified by Prof. L. Lilien (even many without an explicit message indicating an update). Slides added or modified.
MSIS 655 Advanced Business Applications Programming
24 Searching and Sorting.
Data Structures (CS212D) Week # 2: Arrays.
Arrays Chapter 7.
Arrays Week 2.
CIS16 Application Development and Programming using Visual Basic.net
7 Arrays.
ICS103: Programming in C Searching, Sorting, 2D Arrays
Arrays.
Presentation transcript:

Review of Arrays and Pointers Data Structures (CG 211) Lecture 1 Review of Arrays and Pointers

Data Structures Data structure Types of data structures A particular way of storing and organising data in a computer so that it can be used efficiently Types of data structures Based on memory allocation Static (or fixed sized) data structures (Arrays) Dynamic data structures (Linked lists) Based on representation Linear (Arrays/linked lists) Non-linear (Trees/graphs)

Array: motivation You want to store 5 numbers in a computer Define 5 variables, e.g. num1, num2, ..., num5 What, if you want to store 1000 numbers? Defining 1000 variables is a pity! Requires much programming effort Any better solution? Yes, some structured data type Array is one of the most common structured data types Saves a lot of programming effort (cf. 1000 variable names)

What is an Array? A collection of data elements in which all elements are of the same data type, hence homogeneous data An array of students’ marks An array of students’ names An array of objects (OOP perspective!) elements (or their references) are stored at contiguous/ consecutive memory locations Array is a static data structure An array cannot grow or shrink during program execution – its size is fixed

Basic concepts Array name (data) Index/subscript (0...9) The slots are numbered sequentially starting at zero (Java, C++) If there are N slots in an array, the index will be 0 through N-1 Array length = N = 10 Array size = N x Size of an element = 40 Direct access to an element

All elements in the array must have the same data type Homogeneity All elements in the array must have the same data type Index: 1 2 3 4 5 6 7 8 9 Value: 5 10 18 30 45 50 60 65 70 80 Index: 1 2 4 3 Value: 5.5 10.2 18.5 45.6 60.5 Index: 1 2 4 3 Value: ‘A’ 10.2 55 ‘X’ 60.5 Not an array

Contiguous Memory Array elements are stored at contiguous memory locations No empty segment in between values (3 & 5 are empty – not allowed) Index: 1 2 3 4 5 6 7 8 9 Value: 5 10 18 30 45 50 60 65 70 80 Index: 1 2 3 4 5 6 7 8 9 Value: 5 10 18 45 60 65 70 80

Declaring and Creating Arrays Arrays are objects that occupy memory Created dynamically with keyword new int c[] = new int[ 12 ]; Equivalent to int c[]; // declare array variable c = new int[ 12 ]; // create array We can create arrays of objects too String b[] = new String[ 100 ];

Using Arrays Array_name[index] For example, in Java System.out.println(data[4]) will display 0 data[3] = 99 will replace -3 with 99

Using Arrays Array_name[index] For example, in Java System.out.println(data[4]) will display 0 data[3] = 99 will replace -3 with 99

Using Arrays Using an array initializer Use initializer list Items enclosed in braces ({}) Items in list separated by commas int n[] = { 10, 20, 30, 40, 50 }; Creates a five-element array Index values of 0, 1, 2, 3, 4 Do not need keyword new

Using Arrays (Cont.) To declare an array follow the type with (empty) []s int[] grade; //or int grade[]; //both declare an int array In Java arrays are objects so must be created with the new keyword To create an array of ten integers: int[] grade = new int[10]; Note that the array size has to be specified, although it can be specified with a variable at run-time

Examples Using Arrays (Cont.) Calculating the value to store in each array element Initialize elements of 10-element array to even integers

Examples Using Arrays (Cont.) InitArray.java Line 10 Declare array as an array of ints Line 12 Create 10 ints for array Line 16 Use array index to assign array value

Examples Using Arrays (Cont.)

Examples Using Arrays (Cont.) Summing the elements of an array Array elements can represent a series of values We can sum these values

Examples Using Arrays (Cont.) Histogram.java Line 9 Declare array with initializer list Line 19 For each array element, print associated number of asterisks

Examples Using Arrays (Cont.)

Some more concepts data[ -1 ] always illegal data[ 10 ] illegal   (10 > upper bound) data[ 1.5 ] always illegal data[ 0 ] always OK data[ 9 ] OK Q. What will be the output of? data[5]  + 10 data[3] = data[3] + 10

Array’s Dimensionality One dimensional (just a linear list) e.g., Only one subscript is required to access an individual element Two dimensional (matrix/table) e.g., 2 x 4 matrix (2 rows, 4 columns) 5 10 18 30 45 50 60 65 70 80 Col 0 Col 1 Col 2 Col 3 Row 0 20 25 60 40 Row 1 30 15 70 90

Multidimensional arrays Tables with rows and columns Two-dimensional array Declaring two-dimensional array b[2][2] int b[][] = { { 1, 2 }, { 3, 4 } }; 1 and 2 initialize b[0][0] and b[0][1] 3 and 4 initialize b[1][0] and b[1][1] int b[][] = { { 1, 2 }, { 3, 4, 5 } }; row 0 contains elements 1 and 2 row 1 contains elements 3, 4 and 5

Multidimensional arrays (Cont.) Creating multidimensional arrays Can be allocated dynamically 3-by-4 array int b[][]; b = new int[ 3 ][ 4 ]; Rows can have different number of columns int b[][]; b = new int[ 2 ][ ]; // allocate rows b[ 0 ] = new int[ 5 ]; // allocate row 0 b[ 1 ] = new int[ 3 ]; // allocate row 1

Multidimensional arrays (Cont.) Column 0 Column 1 Column 2 Column 3 Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ] Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ] Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ] Column index Row index Array name

Multidimensional arrays (Cont.) InitArray.java Line 16 Declare array1 with six initializers in two sublists Line 17 Declare array2 with six initializers in three sublists

Multidimensional arrays (Cont.) InitArray.java Line 34 array[row].length returns number of columns associated with row subscript Line 35 Use double-bracket notation to access two-dimensional array values

Searching Arrays: Linear Search and Binary Search Finding elements in large amounts of data Determine whether array contains value matching key value Linear searching Binary searching

Searching Arrays: Linear Search and Binary Search (Cont.) Compare each array element with search key If search key found, return element index If search key not found, return –1 (invalid index) Works best for small or unsorted arrays Inefficient for larger arrays

Linear Search LinearSearch.java Line 11 Declare array of ints

Linear Search(Cont.) LinearSearch.java Lines 39-42 Allocate 100 ints for array and populate array with even ints Line 50 Loop through array Lines 53-54 If array element at index matches search key, return index

Linear Search(Cont.) LinearSearch.java Line 61 Invoked when user presses Enter Line 68 Invoke method linearSearch, using array and search key as arguments

Binary Search Binary search Efficient for large, sorted arrays Eliminates half of the elements in search through each pass Compare middle array element to search key If element equals key Return array index If element is less than key Repeat search on first half of array If element is greater then key Repeat search on second half of array Continue search until element equals search key (success) Search contains one element not equal to key (failure)

Binary Search (Cont.) BinarySearch.java Line 14 Declare array of ints Declae array of ints

Binary Search (Cont.) BinarySearch.java Lines 48-51 Allocate 15 ints for array and populate array with even ints Line 56 Invoked when user presses Enter

Binary Search (Cont.) BinarySearch.java Line 65 Invoke method binarySearch, using array and search key as arguments

Binary Search (Cont.) BinarySearch.java Lines 93-94 If search key matches middle array element, return element index Lines 97-98 If search key is less than middle array element, repeat search on first array half Lines 101-102 If search key is greater than middle array element, repeat search on second array half Lines 112-137 Method build-Output displays array contents being searched

Binary Search (Cont.) BinarySearch.java Line 128 Display an asterisk next to middle element

Binary Search (Cont.)

Sorting Motivation List of numbers List of alphabets Generally, to arrange a list of elements in some order List of numbers 10 20 50 30 40 60 25 (Unsorted list) 10 20 25 30 40 50 60 (Sorted list, ascending) 60 50 40 30 25 20 10 (Sorted list, descending) List of alphabets P A K I S T A N (Unsorted list) A A I K N P S T (Sorted list, ascending) T S P N K I A A (Sorted list, descending)

Sorting Algorithms Bubble Sort Selection Sort There are few more sorting algorithms; you can find them in a book on data structures and algorithms (or on the Web)

Bubble Sort Algorithm: Informal Repeatedly compare the elements at consecutive locations in a given list, and do the following until the elements are in required order: If elements are not in the required order, swap them (change their position) Otherwise do nothing

Bubble Sort in Action: Phase 1 3 15 45 40 8 12 5 22 14 3 15 45 40 8 12 5 22 14 3 15 45 40 8 12 22 5 14 3 15 45 40 8 22 12 5 14 3 15 45 40 22 8 12 5 14 3 15 45 40 22 8 12 5 14 3 15 45 40 22 8 12 5 14 3 45 15 40 22 8 12 5 14 45 3 15 40 22 8 12 5 14 8 comparisons

Bubble Sort in Action: Phase 2 45 3 15 40 22 8 12 5 14 45 3 15 40 22 8 12 14 5 45 3 15 40 22 8 14 12 5 45 3 15 40 22 14 8 12 5 45 3 15 40 22 14 8 12 5 45 3 15 40 22 14 8 12 5 45 3 40 15 22 14 8 12 5 45 40 3 15 22 14 8 12 5 7 comparisons

Bubble Sort in Action: Phase 3 45 40 3 15 22 14 8 12 5 45 40 3 15 22 14 8 12 5 45 40 3 15 22 14 12 8 5 45 40 3 15 22 14 12 8 5 45 40 3 15 22 14 12 8 5 45 40 3 22 15 14 12 8 5 45 40 22 3 15 14 12 8 5 6 comparisons

Bubble Sort in Action: Phase 4 45 40 22 3 15 14 12 8 5 45 40 22 3 15 14 12 8 5 45 40 22 3 15 14 12 8 5 45 40 22 3 15 14 12 8 5 45 40 22 3 15 14 12 8 5 45 40 22 15 3 14 12 8 5 5 comparisons

Bubble Sort in Action: Phase 5 45 40 22 15 3 14 12 8 5 45 40 22 15 3 14 12 8 5 45 40 22 15 3 14 12 8 5 45 40 22 15 3 14 12 8 5 45 40 22 15 14 3 12 8 5 4 comparisons

Bubble Sort in Action: Phase 6 45 40 22 15 14 3 12 8 5 45 40 22 15 14 3 12 8 5 45 40 22 15 14 3 12 8 5 45 40 22 15 14 12 3 8 5 3 comparisons

Bubble Sort in Action: Phase 7 45 40 22 15 14 12 3 8 5 45 40 22 15 14 12 3 8 5 45 40 22 15 14 12 8 3 5 2 comparisons

Bubble Sort in Action: Phase 8 45 40 22 15 14 12 8 3 5 45 40 22 15 14 12 8 5 3 1 comparison

Bubble Sort Algorithm in Java void bubbleSort(int List[]) { int temp; int size = List.length; for (i = 0; i < size - 1; i++) { for (j = 0; j < size – (i + 1); j++) if (List[j] > List[j+1]) { //swap temp = List[j]; List[j] = List[j+1]; List[j+1] = temp; }

Review of Arrays and Pointers in C

One-Dimensional Arrays Array x Array Element 1 3 5 7 9 x[1] x[2] x[3] x[4] x[0] Syntax datatype name[size]; /* not initialized */ datatype name[size]={initialization list}; /* initialized */ Example int x[5]; /* not initialized */ int x[5]={1,3,5,7,9}; /* initialized */ Arrays 2

Two-Dimensional Arrays # of columns (second subscript) # of Rows (first subscript) 1 3 5 7 2 4 4 3 1 4 4 4 Syntax datatype name[size][size]; /* not initialized */ datatype name[size][size]={{ initialization list}, {initialization list}}; Example int x[3][4]; /* not initialized */ int x[3][4]={{ 1,3,5,7}, {2,4,4,3}, {1,4,4,4}}; /* initialized */ Arrays 3

Multi-Dimensional Arrays Syntax datatype name[size][size]...; /* not initialized */ datatype name[size][size]...={{ initialization list}, {initialization list}, ...}; /* initialized */ Arrays 4

Exercise 1 #include<stdio.h> int main(void) Write a program to calculate the sum of a two dimensional array (elements). #include<stdio.h> int main(void) {int score[3][2], row, col, total=0; for (row=0; row<3; row++) for (col=0; col<2; col++) scanf("%i", &score[row][col] ); /* filling the array */ for (row = 0; row<3; row++) total+=score[row][col]; /* calculating */ printf("The total is %i\n", total); return(0);} Arrays 5

Exercise 2 Write a program to calculate the sum of each row of a two dimensional array. #include<stdio.h> int main(void) {int score[3][2]={{90,96},{100,80},{90,80}}, row, col, total=0; for (row=0; row<3; row++) {for (col=0; col<2; col++) total+=score[row][col]; printf("The total for row# %i is %i\n", row, total); total=0;} /*clear total to calculate next row*/ return(0);} Arrays 6

Exercise 3 Write a program to calculate the sum of each column of a two dimensional array. #include<stdio.h> int main(void) {int score[3][2]={{90,96},{100,80},{90,80}}, row, col, total=0; for (col=0; col<2; col++) {for (row=0; row<3; row++) total+=score[row][col]; printf("The total for col# %i is %i\n", col, total); total=0;} /*clear total to calculate next column*/ return(0);} Arrays 7

One-Dimensional Arrays Array x Array Element 1 3 5 7 9 x[1] x[2] x[0] x[3] x[4] Syntax datatype name[size]; /* not initialized */ datatype name[size]={initialization list}; /* initialized */ Example int x[5]; /* not initialized */ int x[5]={1,3,5,7,9}; /* initialized */ Arrays 2

Two-Dimensional Arrays # of columns (second subscript) # of Rows (first subscript) 1 3 5 7 2 4 4 3 1 4 4 4 Syntax datatype name[size][size]; /* not initialized */ datatype name[size][size]={{ initialization list}, {initialization list}}; Example int x[3][4]; /* not initialized */ int x[3][4]={{ 1,3,5,7}, {2,4,4,3}, {1,4,4,4}}; /* initialized */ Arrays 3

Exercise 4 Write a program that fills each element of a size 2x3 array to the sum of the subscripts of that element. #include <stdio.h> #define row_limit 2 #define col_limit 3 int main(void) {int x[row_limit][col_limit], i, j; for (i=0; i<row_limit; i++) /* filling array */ for (j=0; j<col_limit; j++) x[i][j]=i+j; printf("The array contents are:\n"); /* displaying array */ for (i=0; i<row_limit; i++) {for (j=0; j<col_limit; j++) printf("%i ", x[i][j]); printf("\n"); } return(0);} Arrays 4

Exercise 5 Write a program that computes the two diagonal sums of a 3x3 array. #include <stdio.h> #define n 3 int main(void) {int x[n][n]={{1,15,11},{3,9,1},{5,8,3}}, sum1=0, sum2=0, i, j, k; k=n-1; for (i=0; i<n; i++) {for (j=0; j<n; j++) {if (i==j) sum1+=x[i][j]; /* first diagonal */ if (k==j) sum2+=x[i][j];} /* second diagonal */ k--; } printf("The sum of the first diagonal is %i\n", sum1); printf("The sum of the second diagonal is %i\n", sum2); return(0);} Arrays 5

Exercise 6 Write a program that computes the totals for each even column, and the totals for each odd row. The size of the array is 4x2. Arrays 6

Solution #include <stdio.h> #define row_limit 4 #define col_limit 2 int main(void) {int x[row_limit][col_limit]={{1,1},{2,2},{5,8},{34,11}}, row_odd=0, col_even=0, i, j; for (i=0; i<row_limit; i++) {if (i%2!=0) {for (j=0; j<col_limit; j++) row_odd+=x[i][j]; printf("The sum for row#%i is %i\n", i, row_odd); row_odd=0;}} for (j=0; j<col_limit; j++) {if (j%2==0) {for (i=0; i<row_limit; i++) col_even+=x[i][j]; printf("The sum for column#%i is %i\n", j, col_even); col_even=0;}} return(0);} Arrays 7

Exercise 7 Modify the previous program to compute the total for all odd rows and the total for all even columns. Arrays 8

Solution #include <stdio.h> /* modification to previous program */ #define row_limit 4 #define col_limit 2 int main(void) {int x[row_limit][col_limit]={{1,1},{2,2},{5,8},{34,11}}, row_odd=0, col_even=0, i, j; for (i=0; i<row_limit; i++) {if (i%2!=0) for (j=0; j<col_limit; j++) row_odd+=x[i][j];} {if (j%2==0) col_even+=x[i][j];} printf("The sum for odd rows is %i\n", row_odd); printf("The sum for even columns is %i\n", col_even); return(0);} Arrays 9

Pointers

Pointers

● Allocate 1 byte of memory Variable  ● Allocate 1 byte of memory char a; ● Memory allocated at some particular address char *ptr; ptr = &a;   ● All pointers are of the same size ○ they hold the address ○ generally 4 bytes