Object-Oriented Programming Object-Oriented Programming (COM357J) Lecture Week 5 Arrays and Pointers An array is a set of data of the same type having common name. A particular data element is accessed by a subscript specified in brackets after array name. Example 10, 12, 13, 9, 2, 17 are values of integer type. The set of values is referred to as an array and the individual values are called elements and can be specified as follows x[0] x[1] x[2] x[3] x[4] x[5] 10 12 13 9 2 17 http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming x is an array of 6 elements of integer type. The elements 10, 12, 13, 9, 2, 17 are specified by the subscripts [0] through [5] respectively. Like all other programming languages, C++ provides arrays of following dimensions One-dimensional array Two- dimensional array Multidimensional array http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming One-dimensional arrays A list of data items can be given a variable name with one subscript. Such an array is called one-dimensional array. Syntax type array_name[size]; Type can be any base type and size defines the number of elements in the array. All arrays have as subscript of their first element. Example int x[6]; char p[10]; x is an integer type array with 6 elements, x[0] through x[5]. p is a character type array with 10 characters, p[0] through p[9]. http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Example /* Simple example of an array */ void main() { int x[5]; int element, t; for(t=0;t<=4;t++) { cout<< “Enter value of element ” << t << “\n”; cin >>element; x[t] = element; } for(t=0;t<=4;t++) cout<< “x[“<<t<<”] = ” <<x[t]; getch(); } http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Storage locations are reserved by the declaration. The subscript of an array can be integer constants, integer variables or expressions that yield integers. Example x[5] x[t] x[strlen(p)] x[i+j] The elements may be used in programs just like any other C++ variables. Example a = x[0]+5; x[4] = x[1] + x[2]; x[2] = x[5] + y[1]; Value[5] = x[i]*3; http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming C++ language treats character strings simply as arrays of characters. Each character is an element of the array. Example char name[6]; The name can be of maximum 6 characters long. Let the name be ABDUL. It will be stored as follows. Name [0] Name [1] Name [2] Name [3] Name [4] Name [5] ‘A’ ‘B’ ‘D’ ‘U’ ‘L’ ‘\0’ http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming When a compiler sees a character string, it terminates it with an additional null Character. Thus, the element Name[5] holds the null character ”\0’” at the end. For example, name[5] can mean John’\0’ http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Example /* Example of character array*/ # include <ctype.h> main( ) { char name[10]; int i ; cout<< “Enter your name \n”; cin>>name; cout<< “Your name in upper case letter\n”; i=0; while(name[i] != ‘\0’) { cout<< toupper(name[i]); i++; } cout<< “\n”; } http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Initialization of arrays The elements of arrays can be initialized in the same way as ordinary variables. The general form of initialization of arrays is as follows static type array_name[size]={list of values}; The values in the list are separated by comma. Example static float p[4]={1.7,2.5}; In the example, the elements are assigned values like p[0]=1.7, p[1]=2.5 and p[2] and p[3] will be assigned 0. http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming In the declaration, size may be omitted only when every element is initialized. Example static int R[ ]={1,3,5,6}; Character arrays may be initialized in the similar way. Example static char name[ ]={‘A’,’B’,’D’,’U’,’L’}; There is no shortcut method for initializing a large number of array elements. http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming To initialize such an array, it would be better to use loop. Example int array_large[100]; for(t=0;t<100;t++) { if(t>50) array_large[t]=1; else array_large[t]=0; } http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Example l6x13.cpp /* Example of an array, Finding the largest and the smallest element in the vector */ void main() { int t,n; float a[50], large, small; cout<< “Size of the vector :: ”; cin<<n; cout<< “\n”<<n; for(t=0;t<n;t++) {cout<< “Enter elements of vector” << t << “\n”; cin>>a[t]; } large =a[0]; /* initialize value to small and large element */ small = a[0]; /* finding the smallest and largest elements */ for(t=0;t<n;t++) { if(a[t]>large) large =a[t]; else if(a[t]<small) small =a[t]; } cout<< “Largest element in vector is = \n” <<large; cout<< “Smallest element in vector is = \n”<<small; getch(); } http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Two –dimensional arrays A two-dimensional array, in essence, is an array of one-dimensional arrays i.e. it can be viewed as a matrix consisting of rows and columns. Example a11 a21 a31 a12 a13 a22 a23 a32 a33 In mathematics, we represent a particular element in a matrix by two subscripts such as aij a denotes the matrix and aij represents the element in the i-th row and in the j-th column. http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming In C/C++, a matrix can be defined by using two-dimensional array. Syntax type array_name [row_size][column_size]; Each dimension of the array uses a subscript from 0 through n-1, where n is the size of the row or column. http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Example - l6x8.cpp /* Example of a two-dimensional array */ void main() { int i,j, matrix[3][4]; cout<< “Enter values of the elements of the matrix \n”; for(i=0;i<3;i++) for(j=0;j<4;j++) cin>>matrix[i][j]; /* display the elements */ for(i=0;i<3;i++) { for(j=0;j<4;j++) cout<< matrix[i][j]; cout<< “\n”; } } http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Initializing two-dimensional arrays The elements of arrays can be initialized in the same way as one-dimensional arrays. The general form of initialization of two-dimensional arrays is as follows static type array_name[size][size]={list of values }; Initialization is done row by row and commas separate the values in the list. Example static int matrix [2][3] ={1,5,6,2,9,11}; One pair of braces can separate the rows. http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming A two dimensional array can also be initialized in the form of a matrix. Commas are required after each brace that closes off a row, except for the last row of the matrix. If the values are missing in an initialize, they are automatically set to zero. Example static int table[2][3]= {{1,7,3}, {4,2,8}}; It can be written in matrix form as follows static int matrix[3][3]= {{1,2,3}, {4,5,6}, {7,8,9}}; Missing values are set to zero. static int matrix[2][3] ={1,5,7}; http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming When all the elements are to be initialized to zero, the following shortcut method can be used. Example static int matrix[3][3]={{0}, {0}, {0}}; http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Example /* Example of two dimensional array_adding two arrays */ #include<stdio.h> void main() { int A[3][3],B[3][3],C[3][3]; int t,j,m,n; /* Initialize matrix A */ for(t=0;t<3;t++) for(j=0;j<3;j++) cin>>A[t][j]; /* Print matrix A in matrix form */ for(t=0;t<3;t++) { for(j=0;j<3;j++) cout<<A[t][j]; cout<< “\n”; } cout<< “\n”; /* Initialize matrix B */ for(m=0;m<3;m++) for(n=0;n<3;n++) cin>>B[m][n]; /* Print matrix B in matrix form */ for(m=0;m<3;m++) { for(n=0;n<3;n++) cout<< B[m][n]; cout<< “\n”; } http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming cout<< “\n”; /* cheek if the matrix can be added */ if(t==m && j==n) { for(t=0;t<m;t++) for(j=0;j<n;j++) C[t][j] = A[t][j] +B[t][j]; cout<< “Sum of matrices A and B :: \n”; for(t=0;t<m;t++) { for(j=0;j<n;j++) cout<<C[t][j]; cout<< “\n”; } cout<< “\n”; } else cout<< “The two matrix cannot be added.\n”; } http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Multidimensional array Arrays of more than two dimensions are refereed to as multidimensional array. Arrays of more than three dimensions are rarely used because of the amount of memory required to hold them. Syntax type array_name[size1][size2]…..[sizeN] Example int x[3][2][4]; A three dimensional array is layers of two-dimensional array. http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Example int x[3][2][2]; The array x can be visualized as 1 1 1 3 http://www.scis.ulster.ac.uk/~siddique 2 4 2 2 Object-Oriented Programming Character strings as arrays The most common use of one-dimensional arrays is character strings. Any group of characters enclosed with double quotation marks is a constant string. The character strings are normally terminated by a null character, specified as ‘\0’. Example “Muchacha” http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming This is an array of 9 characters including a null character ‘\0’ at the end of the string as shown below. ‘M’ ‘u’ ‘c’ ‘h’ ‘a’ ‘c’ ‘h’ ‘a’ ‘\0’ Character strings are declared as arrays. The general form is as follows char string_name[size]; The size should be equal to the number of characters plus one for the null character. Example char name[10]; Character strings may be initialized when they are declared with the general form as follows static char string_name ={string}; http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Example static char city[7]={“London”}; It is the same as the following static char city[7]={‘L’,’o’,’n’,’d’,’o’,’n’,’\0’}; If an array is completely initialized, then its dimension does not need to be specified. Example static char city[ ]={“Sheffield”}; static int marks[ ]={45,47,61,55}; http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Pointers A pointer contains a memory address. This address is the location of another variable in memory. For example Address 5010 Variable 217 Price 5012 5014 5010 int price=217; &price=5010; ptr=&price; http://www.scis.ulster.ac.uk/~siddique Ptr Object-Oriented Programming A pointer enables programmer to access a variable that is defined outside the function. Pointers increase the execution speed. Use of pointer array to character string saves data storage space in memory. Pointers reduce length and complexity of a program e.g. linked list, graphs, binary tree etc. Declaration, Initialization and Accessing pointers Syntax data_type *pointer_name; http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming The following things are done by the above declaration Tells that pointer_name is a pointer variable. Pointer_name is associated with memory location. Data_type denotes a base type. Example int price=217; int *ptr; //declared ptr= &price; //must be initialised *ptr= price=217; A pointer must be initialized with the address of a variable before the pointer can be used. The general form of pointer initialization is as follows: pointer_name =&variable_name; http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Example int price=217; int *ptr; ptr= &price; Initialization of a pointer with an absolute address is prohibited. Example ptr=5010; /* Not valid */ A pointer can be initialized in its declaration itself. Declare variable first! Example int prince, *ptr=&price; /* valid */ int ptr=&price; /* not valid */ http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Example char string[10]; char *ptr =string; This assigns the starting address of the character array to ptr. Value of a variable can be accessed by using the pointer and this is done by unary operator *(asterisk) usually known as indirection operator. Example int price=217, value; int *ptr; ptr= &price; /* ptr points to address of variable price */ value = *ptr; /* *ptr yeilds the contents of address */ http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Pointer expressions Pointer variables can be used in expressions like ordinary variables. Example x= (*p) * (*q); y= *p - *q; *p= *p+10; p++; /* points to the memory location of the next element */ --q; sum +=*p; p =p+1; It is possible to compare two pointers in a relational expression. Example if(p<q) printf(“P points to lower memory location than q \n”); http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Example for(;ptr<=&x[4];ptr++) printf(“%x[%d] %d %d ”,i , *ptr, ptr); Example while(*ptr) printf(“%c”,*ptr++); Pointer and array Example (Prg L6x13.cpp) /* Example of pointers and array */ #include<stdio.h> void main() { int sum,t; int *ptr; static int x[5]={1,2,3,4,5}; ptr=x; /*Starting address of array is assigned to ptr */ sum=0; t=0; printf(“Element value address \n”); for( ; ptr<=&x[4]; ptr++,t++) { printf(“ x[%d] %d %u \n”,t,*ptr,ptr); sum +=*ptr; } cout<<“\n” << “Sum = ” << sum; } http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Example –(Prg L6x14.cpp) /* Example of pointer and arrays, finding the smallest element in an array */ void main(){ int small, i; int *ptr; int x[5]; cout<<“Enter elements of array ::\n”; for(i=0;i<5;i++) cin>>x[t]); ptr= x; /* ptr =&x[0] */ small =*ptr; ptr++; for(i=1;i<5;i++) { if(small>*ptr) small= *ptr; ptr++; } cout<<“The smallest number is ”<<small; getch(); } http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Example (Prg L6x15.cpp) /* Example of pointer and character strings */ #include<stdio.h> void main() { char string[10], *ptr; ptr= string; cout<<"Enter a string :: \n"; gets(string); while(*ptr) cout<<*ptr++; getch(); } http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Pointers in functions as parameters Address of a variable can be passed as parameter to a function in a normal fashion. When passing addresses to a function, the parameters receiving the addresses should be pointers. Process of calling a function using pointers to pass the address of variable is known as call by reference. General form is as follows main() { ……. func(&x,&y); ………. } func(type *p, type *q) { ………. } http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming The following points should be noted Formal parameters should be declared as pointer. When function is called, the addresses are passed as actual parameters (call by reference). Example L6x19.cpp void func( int *); main() { int x=20; cout<< "Call of function by reference \n"; func(&x); cout<< "\n"; getche(); } void func(int *p) { int a=5; *p=*p+a; cout << "\n a = " << a; cout << "\n p = "<< *p; } http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Example L6X17.cpp double disc(int *, int *, int *); void main() { int a=2, b=2, c=2; double d; d=disc(&a,&b,&c); cout<<"discreminant " << d <<"\n\n"; getche(); } double disc(int *a, int *b, int *c) { double *s; *s=(*b)*(*b)-4*(*a)*(*c); return *s; } http://www.scis.ulster.ac.uk/~siddique Object-Oriented Programming Pointer parameters are commonly used in string functions. Notice, for string array address sign is not required. Example (l6x18.cpp) void copy(char *, char *); main() { char name1[10] ,name2[10]; cout<< "Enter name2 :: \n"; cin>>name2; copy(name1, name2); cout<< "Copied name is " <<name1; getche(); } void copy(char *s1, char *s2) { while((*s1++ = *s2++) != '\0') ; } http://www.scis.ulster.ac.uk/~siddique