Arrays and Strings: Chapter Four
Arrays and Strings: Chapter Four
Arrays and Strings: Chapter Four
Array definition
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 definition. An array can have one or more dimensions. The dimension specifies the number of subscript (index) values the array has.
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 to3[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 with in 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]; age[50]=11; age[50]=++; }
It defines age to be an array of 40 integer and then modifies the 51th element which is not with in the limit
The following shows memory representation for the array defined as int age[4];
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(); }
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( ); }
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]; }
The representation of a two dimensional array (e.g. mark) in memory can be shown as follows
mark[0][0] mark[0][1] 00 10 20 30 01 11 21 31 02 12 22 32 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] mark[0][2]
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 As elements"; for( i = 0; i<m; ++i ) for( j = 0; j<n; ++j) cin>>a[i] [j]; cout<<"Enter Bs 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; } } }
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};
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 o r l d \0 * character string terminated by null character
Definition
- An 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]; * the length of this stirng 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; }
String Manipulations
C++ has several built-in function such as strlen( ),strcar( ),strlwl( ),---; for string pulation. 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
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 concatenation
The 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
4) String comparison
The 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 Hell. 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; }
12
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. EXERCISES 1. Write a program that accepts a one dimensional array of integers from the user and computes the average of the numbers 2. 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 X 3. 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