Programming II Pointers and arrays by aalosaimi.

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
Advertisements

CHAPTER 10 ARRAYS II Applications and Extensions.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Dynamic Objects. COMP104 Dynamic Objects / Slide 2 Memory Management * Static Memory Allocation n Memory is allocated at compiling time * Dynamic Memory.
Dynamic Objects. COMP104 Dynamic Objects / Slide 2 Memory Management * Static Memory Allocation n Memory is allocated at compilation time * Dynamic Memory.
Pointers and dynamic objects COMP171 Fall Pointers and dynamic objects/ Slide 2 Topics * Pointers n Memory addresses n Declaration n Dereferencing.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
Pointers. COMP104 Pointers / Slide 2 Pointers * A pointer is a variable used for storing the address of a memory cell. * We can use the pointer to reference.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Pointers. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program execution.
Multidimensional Arrays C++ also allows an array to have more than one dimension. For example, a two-dimensional array consists of a certain number of.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
A First Book of ANSI C Fourth Edition
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable.
Variables and memory addresses
Arrays.
Module 1: Array ITEI222 - Advance Programming Language.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Lecture.
1 Multidimensional Arrays Chapter 13 2 The plural of mongoose starts with a "p" Initializing a multidimensional array Processing by.
Pointers and Arrays Dynamic Variables and Arrays.
APS105 Malloc and 2D Arrays (text Ch6.4, Ch10.2).
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
C++ Review Data Structures.
Chapter 7: User-Defined Functions II
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Two Dimensional Array Mr. Jacobs.
Hassan Khosravi / Geoffrey Tien
Basic Elements of C++.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Pointer Data Type and Pointer Variables II
Multi-dimensional Array
Passing Arguments to a Function
CSCE 210 Data Structures and Algorithms
Basic Elements of C++ Chapter 2.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Two Dimensional Arrays
Pointers and dynamic objects
Chapter 15 Pointers, Dynamic Data, and Reference Types
One-Dimensional Array Introduction Lesson xx
7 Arrays.
CS1201: Programming Language 2
Pointers, Dynamic Data, and Reference Types
Arrays Kingdom of Saudi Arabia
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointer Data Type and Pointer Variables III
Arrays Topics to cover: Arrays Data Types One-dimensional Arrays
Pointers.
Computing Fundamentals
CS1201: Programming Language 2
7 Arrays.
Dynamic Objects.
Arrays Arrays A few types Structures of related data items
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Pointers and dynamic objects
C++ Array 1.
CS31 Discussion 1H Fall18: week 6
Pointers and dynamic objects
Programming Fundamental
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
Dynamic Objects.
Dr. Khizar Hayat Associate Prof. of Computer Science
Presentation transcript:

Programming II Pointers and arrays by aalosaimi

Topic Passing arrays to functions Discover dynamic arrays Explore how dynamic arrays are used 2D arrays Explore how dynamic 2D-arrays are used by aalosaimi

Passing arrays to functions Syntax : Return_type functionName ( data_type * arrayName ) void myFunction(int *param) { . . . } Or Return_type functionName (data_type arrayName[length] ) void myFunction(int param[10]) { . . . } Rturn_type functionName (data_type arrayName[] ) void myFunction(int param[]) { . . . } by aalosaimi

Example double getAverage(int arr[], int size) { int i, sum = 0; for (i = 0; i < size; ++i) { sum += arr[i]; } return double(sum) / size;} int main () { int balance[5] = {1000, 2, 3, 17, 50}; cout << "Average value is: " << getAverage( balance, 5 ) << endl; return 0; } Average value is: 214.4 by aalosaimi

Dynamic arrays Dynamic arrays Static array limitation Solution Fixed size Not possible for same array to process different data sets of the same type Solution Declare array large enough to process a variety of data sets Problem: potential memory waste Dynamic array solution Prompt for array size during program execution by aalosaimi

Static array vs. Dynamic array Array size of ststic array: Can be specified with constant variable (const) const int size = 20; Constants cannot be changed Constants must be initialized when declared Also called named constants or read-only variables by aalosaimi

Declaration of Dynamic arrays Syntax P = new SomeType[Expression]; Where P is a pointer of type SomeType Expression is the number of objects to be constructed -- we are making an array Because of the flexible pointer syntax, P can be considered to be an array by aalosaimi

Declaration of Dynamic arrays Example Declaration of Dynamic arrays new int *p; p = new int; p new p = new int[100]; p new p = new int[n]; p by aalosaimi

Freeing (or deleting) Dynamic Arrays by aalosaimi

Example#1 #include <iostream> cout<<"0-stop.\nChoice>"; #include<string> cin>>choice; #include <clocale> switch(choice){ using namespace std ; case 1: cout<< "Mean=" << mean( grades, n )<<endl; void fill( string *, int * ,int &); break; int find (string * ,int &, string); case 2: double mean (int * ,int & ); cout <<"Enter the wanted name:"; string toLower(string ); cin>>name; loc =find( names, n,name); void main(){ if (loc !=-1 ) int n, loc, choice; cout<<name<<"'s grade is "<<grades[loc]<<endl; string name; cout << "How many students? "; else cin >> n; cout<< "This student is not found!\n"; int *grades = new int[n]; string *names= new string[n]; case 0: break; fill( names, grades ,n) ; default: do{ cout<< "Wrong choice !" ;} cout<<"Choose one of the following:\n"; }while(choice !=0); cout<<"1-Print the mean of the grades.\n"; } cout<<"2-serach about a specific student.\n"; by aalosaimi

Example #1(cont.) void fill( string *listNames, int *listGrades ,int &size) {for(int i = 0; i< size; i++){ cout<<"Enter the name followed by the grade fpr student#"<<i+1<<":"; cin>>listNames[i]; cin>>listGrades[i];}} int find (string * listNames ,int & size, string na) { for(int i = 0; i< size; i++) if(toLower(listNames[i]) == toLower(na)) return i; return -1; } double mean (int * listGrades ,int & size) { int sum=0; sum+=listGrades[i] ; return (double)sum/size;} string toLower(string s) { for ( int i=0; i<s.length() ;i++) s[i] = tolower(s[i]); return s; } by aalosaimi

output by aalosaimi

Example#2 #include <iostream> #include<string> using namespace std; cin>>name; void print ( string *, int *, const int&); cin>>grade; bool add ( string * & , int * & , int & , const string & , const int & ); if(add(nlist, glist , size, name, grade)) cout<<name<<"has been added sucessfully"<<endl; int find (string * ,int & , string& ); bool Delete ( string * & , int * &, int & , const string ); else cout<< "Duplicated names are not allowed!n"; break; case 2: void main(){ cout <<"Enter the wanted name:"; int choice; string name; int grade , size=0; string *nlist = 0; if (Delete(nlist , glist , size , name)) int *glist=0; cout<<name<<"has been deleted"<<endl; do{ cout<<"Choose one of the following:\n"; cout<< "This student is not found!\n"; cout<<"1-add a new student.\n"; cout<<"2-delete a student.\n"; case 3: print (nlist ,glist,size); break; cout<<"3-print the content.\n"; case 4: break; cout<<"4-Exit.\nChoice>"; default: cin>>choice; cout<< "Wrong choice !" ;} switch(choice){ }while(choice !=0); case 1: } cout<< "Enter the name followed by the grade of the new student:"; by aalosaimi

Example #2(cont.) void print ( string *listNames, int *listGrades, const int & size) {for(int i = 0; i< size; i++) cout<<listNames[i]<<"\t"<<listGrades[i]<<endl;} int find (string * listNames ,int & size, const string & na) { for(int i = 0; i< size; i++) if(listNames[i]==na) //assume all characters in lower case return i; // not found return -1; } by aalosaimi

Example #2(cont.) bool add ( string * & listNames, int * & listGrades, int & size, const string & n , const int & g ){ //prevent the duplication if ( find ( listNames , size , n)!=-1) return false; // create a new dynamic array 1 element larger than original array string * newListNames = new string [size + 1]; int * newListGrades = new int [size + 1]; // copy all elements from original array into new array for( int i = 0; i < size; i++ ){ newListGrades [ i ] = listGrades[ i ]; newListNames [i]=listNames[i];} // add the new entry onto the end of the new array newListGrades [ size ] = g; newListNames [size]=n; // increment size size++; // delete original array if( size ) {delete [] listNames; listNames=0; delete [] listGrades; listGrades=0;} //assign the new array to the original array listNames = newListNames; listGrades=newListGrades; return true;} by aalosaimi

Example #2 (cont.) bool Delete ( string * & listNames, int * & listGrades, int & size, const string n){ int loc; loc= find ( listNames , size , n); if ( loc==-1) return false; // only zero or one element in the array & it is the required element. if( size <= 1 ){ if( size ){ delete [] listNames; delete [] listGrades;} listGrades = NULL; listNames=NULL; size = 0; return true; } //if the size is more than one , decrement the size size--; //shift the elements up for ( int i= loc; i<size; i++){ listNames[i]= listNames[i+1]; listGrades [i] = listGrades[i+1];} return true;} by aalosaimi

A sample run (part of the output) by aalosaimi

Static Multidimensional Arrays C++ also allows an array to have more than one dimension. For example, a two-dimensional array consists of a certain number of rows and columns: const int NUMROWS = 3; const int NUMCOLS = 7; int Array[NUMROWS][NUMCOLS]; 1 2 3 4 5 6 18 9 -4 12 45 74 15 98 84 87 75 67 81 85 79 Array[2][5] 3rd value in 6th column Array[0][4] 1st value in 5th column The declaration must specify the number of rows and the number of columns, and both must be constants.

Processing a 2-D Array A one-dimensional array is usually processed via a for loop. Similarly, a two-dimensional array may be processed with a nested for loop: for (int Row = 0; Row < NUMROWS; Row++) { for (int Col = 0; Col < NUMCOLS; Col++) { Array[Row][Col] = 0; } Each pass through the inner for loop will initialize all the elements of the current row to 0. The outer for loop drives the inner loop to process each of the array's rows.

Static Multidimensional Arrays Initializing in Declarations int Array1[2][3] = { {1, 2, 3} , {4, 5, 6} }; int Array2[2][3] = { 1, 2, 3, 4, 5 }; int Array3[2][3] = { {1, 2} , {4 } }; If we printed these arrays by rows, we would find the following initializations had taken place: Rows of Array1: 1 2 3 4 5 6 Rows of Array2: 4 5 0 Rows of Array3: 1 2 0 4 0 0 for (int row = 0; row < 2; row++) { for (int col = 0; col < 3; col++) { cout << setw(3) << Array1[row][col]; } cout << endl;

Example: storing 2D Array in 1D Array int twod[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}}; int oned[12]; for(int i=0; i<3; i++){ for(int j=0; j<4 ; j++) oned[i*4+j] = twod[i][j]; } by aalosaimi

Dereferencing with 2-Dimensional Arrays- table[i] = &table[i][0] refers to the address of the ith row table table[ 0] or *( table + 0 ) table + 1 table[ 1] or *( table + 1 ) table + 2 table[ 2] or *( table + 2 ) *(table[i]+j) = table[i][j] int table[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; for(int i=0; i<3; i++){ for(int j=0; j<4; j++) cout << *(*(table+i)+j); cout << endl; } What is **table ? by aalosaimi

The concept of dynamic two-dimensional array Array of Pointers & Pointers to Array a p b c A pointer to an array An array of Pointers int a = 1, b = 2, c = 3; int *p[5]; p[0] = &a; p[1] = &b; p[2] = &c; int list[5] = {9, 8, 7, 6, 5}; int *p; P = list;//points to 1st entry P = &list[0];//points to 1st entry P = &list[1];//points to 2nd entry P = list + 1; //points to 2nd entry Dynamic 2D array is an array of pointers by aalosaimi

How To Create A Dynamic Two-dimensional Array (1) Suppose that we want to create a 4X6 matrix.How can we do that ? int *board[4]; for (int row = 0; row < 4; row++) board[row] = new int[6]; // each row of board has six columns. board by aalosaimi

Note Note that the expression new int[6] creates an array of six components of type int and returns the base address of the array. The assignment statement then stores the returned address into board[row]. It follows that after the execution of the previous for loop, board is a two-dimensional array of four rows and six columns. However, the way board is declared, the number of rows is fixed. So in reality, board is not a true dynamic two-dimensional array. by aalosaimi

How To Create A Dynamic Two-dimensional Array (2) Second approach to declare 2D array is int **board; // declares board to be a pointer to a pointer Suppose that you want board to be an array of 10 rows and 15 columns. To accomplish this, first we create an array of 10 pointers of type int and assign the address of that array to board. board = new int* [10]; Next, we create the columns of board. The following for loop accomplishes this. for (int row = 0; row < 10; row++) board[row] = new int[15]; by aalosaimi

A Dynamic 2D Array- example A dynamic array is an array of pointers to save space when not all rows of the array are full. int **table; 32 18 24 12 42 14 19 16 11 13 22 table[0] table[1] table[2] table[3] table[4] table[5] table table = new int*[6]; … table[0] = new int[4]; table[1] = new int[7]; table[2] = new int[1]; table[3] = new int[3]; table[4] = new int[2]; table[5] = NULL; by aalosaimi

A Dynamic 2D Array- Memory Deallocation Memory leak is a serious bug! Each row must be deleted individually Be careful to delete each row before deleting the table pointer. for(int i=0; i<6; i++) {delete [ ] table[i]; table [i]=0;} delete [ ] table; table =0; by aalosaimi

Create a matrix of any dimensions, m by n: Example: Create a matrix of any dimensions, m by n: void main(){ int m, n; cin >> m >> n >> endl; int** mat; mat = new int*[m]; for (int i=0;i<m;i++) mat[i] = new int[n]; … } Void main(){ int m, n; cin >> m >> n >> endl; int** mat; mat = imatrix(m,n); …} int** imatrix(nr, nc) { int** m; m = new int*[nr]; for (int i=0;i<nr;i++) m[i] = new int[nc]; return m;} Put it into a function: by aalosaimi

Example #include <iostream> using namespace std; void fill (int **p, int row ,int column); void print (int **p, int row ,int column); void main() { int ** board; int R, C; cout<<"enter the array size :" <<endl; cout << "number of rows : " <<endl;cin >>R; cout<<"number of columns : " <<endl; cin >> C; cout <<" ****************" <<endl; board = new int*[R]; for ( int i=0;i<R;i++) board[i]= new int[C]; fill (board,R,C); print(board ,R,C); } by aalosaimi

Example (cont.) void fill (int **p, int row ,int column) { for ( int i=0;i<row;i++) cout <<" enter "<<column<<" numbers to fill row number " << i<<endl; for (int j=0;j<column ;j++) cin>>p[i][j]; cout<<endl; } by aalosaimi

Example (cont.) void print(int **p, int row ,int column){ cout << " the board is : "<<endl; for (int i=0;i<row;i++) {for (int j=0;j<column ;j++) cout << p[i][j]<< " "; cout<< endl; } by aalosaimi