chapter four - befetrin.files.wordpress.com file · web viewchapter four. arrays, pointers and...

24

Click here to load reader

Upload: phamkhue

Post on 27-Apr-2019

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

Chapter FourArrays, Pointers and Strings

4. Arrays, Pointers and StringsIn the previous chapter we were discussing the different statements (instructions) used to perform different operations on a set of data. Generally when we write a computer program to solve a particular problem, the program will contain two essential parts. These are description of actions that are to be performed and description of data that are to be manipulated. Actions are performed by so called statements that we have been discussing so far and data are described by declarations and definitions. We already discussed how to declare variables and constants of fundamental data types in chapter two. We have also written several example programs to illustrate this.

In all the programs we have been writing so far, we have used one name to refer to one location in a computer’s memory. However there are many situations where we would like to repeat a sequence of operations on a set of related entities.

In the previous chapter we have written a program to accept list of numbers from the user and compute things like (average, sum, largest, smallest, difference between largest and smallest etc) of the numbers. In our examples we used a single variable to accept the different numbers and perform the above computations. In this case each time after accepting a new value from the user the previous value of the variable will be updated by the new value. After accepting all the numbers from the user what we will get in the variable is only the last number. Suppose that we want to store the accepted values for latter usage even after performing the above computations. In the first approach numbers entered before the last number will be lost. What can we do? Are we going to define separate variable for each value to be accepted? What if the number of values to be accepted is too large (e.g. 1000 even more)? In programming this is impractical.

One way to do this would be to have a group of array of locations in the memory, all of which are identified by the same name but with an index or subscript to identify individual locations. Individual items within an array are called array elements. Array elements are distinguished from one anther by a subscript. A subscript is a number inside square bracket, [], that differentiates one element of the array from the other.

4.1.Arrays

Defn :- An array is a group of logically related data items of the same data type addressed by a common name, and all the items are stored in contiguous (physically adjacent) memory locations.

Like other variables in C++, an array must be defined before it can be used to store information. Like other definitions array definition specifies a variable type and name. In addition to this it also includes additional feature – size. The size specifies how many data items the array will contain. It is specified with in square bracket in the array

1

Page 2: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

definition. An array can have one or more dimensions. The dimension specifies the number of subscript (index) values the array has.

4.2. One dimensional arrayA one dimensional array is an array which has one subscript (index) value and is referred to as a list. A one dimensional array is defined using the following syntax. data_type arrayname [size];

In the definition the arrayname must be a valid C++ identifier, followed by an integer value enclosed in square bracket.

The integer value indicates the maximum number of elements the array can hold. The following are valid array definition statements

int marks[100]; float salary[25]; char name[50]; int a[10], b[12], c[25]; defines multiple arrays of the same type double d1, num [10]; a normal variable and an array can be declared in single statement

The individual elements of an array are accessed and manipulated using the array name followed by their index.

The first element of an array has an index of 0. The last element of an array is indexed at n-1 where n is array size

Accessing array elementsOnce an array variable is defined, its element can be accessed by using an index. The syntax for accessing array elements is ArrayName [index] Ex: int number[10]; //defines number to be array of 10 elements cout<<”Enter the numbers:”; //prompts for the numbers for(int i=0;i<10;i++) cin>>number[i]; //read the ith number and store it at the ith location in the array

We use loops, usually for loop is used, to read the elements of an array. i, array index, indicates the element of the array, which has to be accessed.

Ex:cout<<number[4]; //displays the 5th number on the screenfor (int j=0;j<10;j++) cout<<number[i]; //displays the number at the ith location in the array number

2

Page 3: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

EX: The following reads elements of an array which has 5 elements for ( int i=0; i<5; i++) { cout<<"Enter person"<< i+1<<"age:"; cin>>age[i]; } age[i]++; //increments the value of the ith item array age age[1]=11; //assigns 11 to the second element age[2]=25; //assigns 25 to the third element

Note:- The expression age [3] is equivalent to 4th person age;

Initialization at Definition Arrays can be initialized at the point of their definition as follows:

data_type array_name[size]={list of value separated by comma}; EX: int age[5] = {19,21,16,1,50};

The array size may be omitted when the array is initialized during array definition as follows:

int age[] = {19,21,16,1,50};In such cases, the compiler assumes the array size to be equal to the number of elements enclosed within the curly braces.

Note:C++ dose not check for the validity of the array index value while accessing the array elements. If the program tries to store something not within the size of an array, neither the compiler nor the run-time will indicate the error. Such a situation may cause over writing of data or code leading to a serious error. Therefore the programmer has to take extra care to use indexes within the array limits!

EX: void main( ) { int age[40]; It defines age to be an array of 40 integer and then age[50]=11; modifies the 51th element which is not with in the limit }

3

Page 4: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

The following shows memory representation for the array defined as int age[4]; age[0] age[1]

age[2]

age[3]

EX: The following program finds the ages of the elder and the youngest person in a family. #include<iostream.h> #include<conio.h> void main( ) { int i,n; int age[25],younger,elder; cout<<"How many family members do you have?\n"; cin>>n; for ( i=0; i<n; i++ ) { cout<<"Enter person"<<i+1<<"age:"; cin>>age[i]; } younger=age[0]; elder=age[0]; for( i=1; i<n; i++ ) { if (age[i]<younger) younger=age[i]; else if ( age[i]>elder) elder=age[i]; } cout<<"age of elder person is "<<elder; cout<<"age of youngest person is"<<younger; getch(); }

4

Page 5: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

Ex: Write a program that accepts list of numbers from the keyboard and counts the number of elements below the average.

#include<iostream.h>#include<conio.h>const int max=20;void main( ){ clrscr( ) float number[max], sum=0.0, average; int i,n,count=0; cout<<” How many numbers are there in the list?\n” cin>>n; cout<<”\nEnter the numbers\n”; for(i=0;i<n;i++) { cin>>number[i]; sum+=number[i]; } average=sum/n; for(i=0;i<n;i++) if(number[i]<average) count++; cout<<”\n\nAverage=”<<average; cout<<”\n\nThe number of elements below average->”<<count; getch( );}

Sorting Array ElementsSorting is the process of arranging set of values in some order relation (ascending, descending). Arrays are used to store set of values that are going to be sorted. There are different sorting algorithms. The following program uses the most popularly known sorting algorithm (bubble sort).The bubble sort works as follows:In each pass the first two items in a list are compared and placed in the correct order. Items two and three are compared and then reordered, followed by items three and four, then four and five, and so on. The sort continues until a pass with no swap (exchange) occurs.

#include<iostream.h>void main( ){ int i, j, n, a[25], flag, temp; cout<<”How many numbers to sort(<=25)?”; cin>>n; cout<<”Enter the numbers one by one”; for(i=0;i<n;i++)

5

Page 6: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

cin>>a[i]; //Sorting starts here using bubble sort for(i=0;i<n-1;i++) { flag=1; for(j=0;j<(n-1-i);j++) { if(a[j]>a[j+1]) { flag=0; temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } if(flag) break;

}cout<<”\n Sorted list:”;for(i=0;i<n;i++) cout<<a[i];

}

Note: At this point you should be able how to populate and access one dimensional Array. It is very important to know it.

4.3. N - Dimensional Array (reading assignment) Definition A multidimensional array is an array which can have many subscripts and is defined as follows: data_type array_name [s1] [s2] ...[sn]; Two dimensional array The general format for defining two-dimensional array is data_type array_name[row_size] [colomn_size];

Matrix is a two dimensional array Two subscripts are required to access each element of a matrix.

EX: int mark[4] [3]; float b[3] [3];

The expression mark [0][0], accesses the first element of the matrix mark and mark [3][2] accesses the last row and last column.

The representation of a two dimensional array (e.g. mark) in memory can be shown as follows.

6

Page 7: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

mark[0][0] mark[0][1] mark[0][2] mark[1][0] mark[1][1] mark[1][2] mark[2][0]

mark[2][1] mark[2][2]

mark[3][0]

mark[3][1] mark[3][2]

Accessing Two Dimensional Array Elements The elements of two dimensional arrays can be accessed by the following way.

ArrayName [j][k]Where j shows the row number and k shows the column number of the current element. The subscripts must be integer constants or variables or they can be expressions generating integer results.Ex

cout<<mark[2][2];

7

10 1101 02

322030 31

2212

00

21

Page 8: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

EX: Addition and subtraction of matrices #include<iostream.h> void main () { int a[5] [5],b[5] [5],c[5] [5]; int i,j,m,n,p,q; cout<<"Enter row and column size of A " cin>>m>>n; cout<<"Enter row and column size of B" cin>>p>>q; if ( (m = = p ) && ( n = = q ) ) { cout<<"these matrices can be added or subtracted"; cout<<"Enter A’s elements"; for( i = 0; i<m; ++i ) for( j = 0; j<n; ++j) cin>>a[i] [j]; cout<<"Enter B’s elements “; for( i = 0; i<p; i++ ) for( j = 0; j<q; j++) cin>>b[i] [j]); for( i = 0; i<m; i++) for(j = 0; j<n; j++) c[i][j] = a[i][j] + [i][j]; cout<<"sum of A and B is"; for( i = 0; i<m; ++i ) { for( j = 0; j<n; ++j ) cout<<c[i][j]<<" "; cout<<endl; for( i = 0; i<m; i++ ) for( j = 0; j<n; j++ ) c[i][j] = a[i][j]-b[i][j]; cout<<"Difference of Aand B is"; for( i=0; i<m; ++i) { for( j=0; j<n; ++j) { cout<<setw(2)<<c[i][j]<<" "; } cout<<endl; } } }

8

Page 9: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

Initialization at Definition A two dimensional array can be initialized during its definition as follows: data-type matrix-name[row-size] [col-size]={ { elements of first row }, { elements of second row }, . . . { elemens of (n-1)th row } }; EX: int a[3] [3]= { {1,2,3 }, { 4,3,1}, { 3,1,2 } }; The first subscript (size of the row) can be omitted .Hence, the example can be

written as int a[] [3]= { {1,2,3}, {4,3,1}, {3,1,2} }; The inner braces can be omitted, permitting numbers to be written in one continuous

sequence as follows: int a[] [3]={1,2,3,4,3,1,3,1,2};

4.4. Strings A string is an array of characters whose end is marked by the NULL ('\0')

character. Strings are used in programming languages for storing and manipulating

text, such as words, names and sentences. String constants are enclosed in double quotes EX: "Hello World" A string is stored in memory by using the ASCII codes of the characters that

form the string. Representation of the string "Hello World" in memory is as follows

h e

l l o w

9

Page 10: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

o r l d \0 character string terminated by null character

DefinitionAn array of characters representing a string is defined as follows: char array_name [size]; The size of the array must be an integer value EX: char name [50]; In the above example, the length of this string can not exceed 49 since one storage

location must be reserved for the end of the string marker (the NULL character \0). Ex: #include<iostream.h> void main() { char name[50]; cout<<"Enter your name<49-max>:"; cin>>name; cout<<"your name is"<<name; }

Initialization at the point of Definition The string variable can be initialized in two ways

I. char array-name[size]={list of values separated by comma}; EX: char month [] = {'A', 'p', 'r', 'i' ,'l', 'lo'};

II. C++ offers another style for initializing an array of characters EX: char month [] = "April";

Special characters can be embedded with in a string. When manipulated using C++ I/O operators, they are interpreted as special characters and action is taken a according to their defined meaning.

4.5. String ManipulationsC++ has several built-in function such as strlen(), strcar(), strlwl(), for string manipulation. To use these functions, the header string.h must be include in the program as. #include<string.h>1) String length

The string function strlen( ) return the length of a given string. A string constant or an array of characters can be passed as an argument. The length of the string excludes the end-of- character (NULL).

10

Page 11: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

EX: #include<iostream.h> #include<string.h> void main( ) { char s1[25]; cout<<"Enter your name:"; cin>>s1; cout<<"your name is composed of :"<<strlen(s1)<<” characters” }

2 ) String copy The string function strcpy() copies the content of one string to another. It takes

two arguments; the first argument destination string array and the second is the source string array.

EX: #include<iostearm.h> #include<string.h> void main( ) { char s1[25],s2[25] cout<<"Enter a string:"; cin>>s1; strcpy(s2,s1); cout<<”strcpy(s2,s1)”<<s2 } 3) String concatenationThe string function strcat() concatenates two strings resulting a single string. It takes two arguments which are the destination and the source strings. The destination and the source strings are concatenated and the resultant is stored in the destination (first) string.EX: #include<iostream.h> #include<string.h> void main( ) { char s1[40],s2[25]; cout<<”Enter string s1:”; cin>>s1; cout<<”Enter string s2:”; cin>>s2; strcat(s1,s2); cout<<”strcat(s1,s2):”<<s1; }

11

Page 12: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

4) String comparisonThe string function strcmp( ) compares two strings, character by character. It accepts two strings as parameters and returns an integer whose value is < 0 if the first string is less than the second = = 0 if both are identical >0 if the first string is greater than the second Whenever two corresponding characters in the string differ, the string which has the character with the higher ASCII value is greater. For example consider the string “hello” and “Hello”. The first character itself differs. The ASCII code for h is 104, while the ASCII code for H is 72. Since the ASCII code for h is greater, the string “hello” is greater than the string “Hello”. Once a differing character is found there is no need to compare remaining characters in the string. Ex:#include<iostream.h>#include<string.h>void main( ){ char s1[25],s2[25]; cout<<”Enter string s1:”; cin>>s1; cout<<”Enter string s2:”; cin>>s2; int status=strcmp(s1,s2); cout<<”strcmp(s1,s2): if(status= =0) cout<< s1<<” is equal to “<<s2; else if(status > 0) cout<<s1<<” is greater than “<<s2; else cout<<s1<<” is less than “<<s2;} 5) String to Upper/Lower caseThe functions strlwr() and strupr() convert a string to lower case and upper case respectively and return the address of the converted string.Ex: #include<iostream.h>#include<string.h>void main( ){ char s1[25],temp[25]; cout<<”Enter a string”; cin>>s1; strcpy(temp,s1); cout<<”strupr(temp):”<<strupr(temp)<<”\n”; cout<<”strlwr(temp):”<<strlwr(temp); }

12

Page 13: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

4.6. Array of strings An array of strings is a two dimensional array of characters and is defined as follows: char array_name[row_size][column_size];For instance the statement char person[10][15];defines an array of string which can store names of ten persons and each name can not exceed 14 characters.

EXERCISES1. Write a program that accepts a one dimensional array of integers from the user

and computes the average of the numbers2. Write an interactive program for calculating grades of N students from 3 tests and

present the result in the following format.

------------------------------------------------------------------------------------------ Sl/No Scores Average Gr------------------------------------------------------------------------------------------

XX XX XX XX XX X3. Write a program that reads in a two-dimensional array of integers with n rows and

n columns and interchanges the rows and columns of the array.Ex: 4 3 2 1 4 5 0 8

5 7 4 9 3 7 5 8 0 5 6 2 becomes 2 4 6 0 8 8 0 4 1 9 2 4

4. Write a program that reads a two dimensional array of integers, with n rows and n columns. The value of n is supplied by the user. Your program then computes whether the array satisfies any of the following conditions.

i. the array is symmetric. This would be the case if, for all i and j, we have a [i,j]=a[j,i]; where a denotes the name of the array

ii. The array is diagonal. This would be the case if, whenever i != j, we have a[i,j]=0, where a denotes the name of the array.

iii. The array is upper triangular. This would be the case if, for all i and j;, if i>j, then a [i,j]=0.

5. Write a program that accepts a line of text from the keyboard and counts the number of occurrence of each character in the text

6. Write a program to accept a line of text from the keyboard and count the number of vowels and consonants

7. Write a program that accepts an array of names from the user and sorts the names in alphabetical order.

8. Write a program that accepts list of numbers and displays the number which has the highest frequency.

13

Page 14: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

4.7. Pointers A pointer is an entity, which contains a memory address. Dynamic memory allocation is a programming concept where in the use of

pointers becomes indispensable. Pointer variable is a variable used to store memory address. It is similar to any

other variable and has to be defined before using it, to hold an address. Just like, an integer variable can hold only integers, each pointer variable can hold only pointer to specific data type such as int, char, float, double, etc

The allocation of memory space for data storage during the course of program execution is called dynamic memory allocation. Dynamic variables so created can only be accessed with pointers.

The usage of pointers is essential in the following situations: Accessing array elements. Passing arguments to functions by address when modification of formal

arguments is to be reflected on actual arguments. (covered in coming course) Passing arrays and strings to functions. (covered in coming course) Creating data structures such as linked lists, trees, graphs, etc. (covered in coming

course) Obtaining memory from the system dynamically. (covered in coming course)

Address Operator (&)The address operator & (ampersand) is used to obtain the address of a program variable. All the variables defined in a program (including pointer variables) reside at specific address. When used as prefix to the variable name, the ‘&’ operator is used to return the address of the variable. Ex.

int a = 100;int b = 200;int c = 300;------cout<<”Address”<<&a<<”contains value “<<a<<endl;cout<<”Address”<<&b<<”contains value”<<a<<endl;cout<<”Address”<<&c<<”contains name”<<a<<endl;

Pointer Variables

Rules for variables names hold true for pointer variables.

Pointer DefinitionWhen a pointer variable is defined, the C++ compiler needs to know the type of variable the pointer points to.

14

Page 15: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

Syntax of pointer variable definitionDatatype *ptrVar;Datatype can be char, short, int, float, etc.

The character star (*) following the data type informs the compiler that the variable ptrVar is a pointer variable. The pointers so created can hold the address of any variable of the specified type.

Dereferencing of pointers Dereferencing is the process of accessing and manipulating data stored in the

memory location pointed to by a pointer. The operator * (asterisk) is used to dereference pointers

The following shows the syntax for Dereferencing pointers. *pointer variable

Runtime Memory Management (covered in coming courses)Whenever an array is defined, a specified amount of memory is set aside at compile time, which may not be utilized fully or may not be sufficient. If a situation arises in which the amount of memory required is unknown at compile time, the memory allocation can be performed during execution. Such a technique of allocating memory during runtime on demand is known as dynamic memory allocation. (Can you point out such a situation? For example when you develop real life problem solving C++ programs)

C++ provides the following two special operators to perform memory management dynamically

new operator for dynamic memory allocation delete operator for dynamic memory deal location

The new operator

the new operator offers dynamic memory allocation

Syntax

Datatype * new datatype [size]

return type new data number pointer to data type operator type items to be

allocated; optional.It is an value

the operator new allocates a specified amount of memory during runtime and returns a pointer that memory location. It computes the size of the memory to be allocated by

size (datatype)*integersize the new operator returns NULL, if mem allocation is unsuccessful.

15

Page 16: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

1. int*aa = new int[100];=> creates a memory space for an array 100 integers. Will refer to the

element, a [1] to the second element 2. float *d;

d = new float [size];

3. double *d;d = new double [size];

4. char *city;city = new char [city name size]

5. struct data{

int day;int month;int year;

};date*date-ptr;

The delete operator

The new operators counterpart, delete, ensure the safe and efficient use of memory. This operator is used to return the memory allocated, by the new operator back to the memory pool. Memory thus released, will be reused by other parts of the program.

Syntax: delete pointer variable;

1. delete a;2. delete b;3. delete c;4. delete city;5. delete date.ptr;

Ex. The following of dynamic allocation and deal location using new and delete operators.

# include<iostream.h> void Addnectors (int a, int b, int*c){ for (int i=0; {<size;iff};

c[i] = a[i] + b[i];*}void [cadvector (int*vector, int size{

16

Page 17: Chapter Four - befetrin.files.wordpress.com file · Web viewChapter Four. Arrays, Pointers and Strings. Arrays, Pointers and Strings. In the previous chapter we were discussing the

for (int I =0; <<size; iff)count<<vector[i]<<” “;

}void main( ){ int vee-size; int **,*y,*z;

cout <<”enter size of vector”;cin>>vec-sizex = new int (vec-size];y = new int [vec-size];z = new int [vec-size];cout <<”Enter elements of vectorRead vector (x, vec-size);Addvectors (x, y,z,vec-size);Cout<<”summation of x and y isShowvector (z, vec-size);delete x;delete y;delete z;

}

Ex:#include <iostream.h>#include<conio.h>void main (){

float age;int sm, count, n,I;int**;clrscr( );cout<<”how many numbers to be added:”cin>>n;sm=0;for (I=1; I<=n;iff){

x=new int;cout <<”enter the first number:”cin>>**;

}aug = sm/n;cout <<”the average of the list is:” <<aug;getch ( );

}

17