Tuesday 23 October 2012

Arrays and Strings in C++ Structure

Arrays and Strings in C++
Unit 3 Arrays and Strings in C++
Structure
3.1 Introduction
3.2 Introduction to Arrays
Self Assessment Questions
3.3 Multidimensional Arrays
Self Assessment Questions
3.4 Strings and String related Library Functions
Self Assessment Questions
Summary
Terminal Questions
3.1 Introduction
This unit has the following objectives
· To understand what are arrays and how they are useful in C++ programming
· To learn to create and use multidimensional arrays
· To understand how strings are represented and used in C++
3.2 Introduction to Arrays
Arrays are used when you want to store related data of same type together with the same name so that you can access them easily. Arrays can be defined as datastructures that allow to store group of data of same datatype. You can retrieve data stored in the array in any order. For example, let us suppose you want to write a program which will help you to compute average marks scored by students in a class of 60. To allow this computation, your program should store marks scored by 60 students in a class separately, so that you can do any kind of computation when required. It would be tedious, if you had to create 60 different variables to store marks of 60 students and manage them separately. Arrays solves this problem, by grouping data of similar type with same name but can be referred separately through the position or the index number.
Arrays should be declared like any other variable. However array size should be specified during declaration which determines how many elements the array can store. The following is a declaration of an integer array named data which can store 20 integers.
int data[20];
Please note that in the above declaration, data is the name of the array followed by the size of the array enclosed within square brackets.The datatype of data stored by the array can be any default datatypes supported by c++ or user defined datatypes.
Elements in the array can be accessed through index numbers. The data in the array are stored with index numbers 0,1, and so on. Since the index number starts with 0 the last index number of an array of size n will be n-1. The elements stored in the array are accessed by using the array name followed by the index number within the square brackets. For example, in the above array, the integers in the array can be accessed as data[0], data[1] and so on till data[19]. This makes it very easy to store and access large number of data. The code can be simplified by including common statements that needs to be performed on the array elements inside a loop and making the loop variable as the variable that stores the index variable.
The following programs shows how you can store and retrieve data from the array
//max.cpp
#include<iostream.h>
void main()
{
int max=0, a[50];
for (int i=0; i<50;i++)
{
cin>>a[i];
if (a[i]>max)
max=a[i];
}
cout<<”Largest number in the array is”<<max;
}
In the above program, a is an array that stores 50 integers. The program accepts 50 integers from the user, and stores in an array and finds out the maximum number in the array. The a[i] represents a particular element in the array and i is the index number. As the iteration varies, the value stored in i also varies.
Another interesting aspect of the array is that all the elements in the arrays are allotted consecutive spaces in the memory by the operating system.
The following program sorts an array. Here nested for loops are used to enable this.
//sort.cpp
# include<iostream.h>
void main()
{
int a[10],temp;
for (int i=0; i<10;i++)
{
cin>>a[i];
}
cout<<"Array after sorting is ";
for(int j=0; j<9;j++)
for(i=0;i<9;i++)
{ if (a[i]>a[i+1])
{temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
for (i=0; i<10;i++)
{
cout<<a[i]<<endl;
}
}
Array elements can be initialized. All the elements in the array should be initialized. Every data should be separated by a comma and all elements enclosed within flower brackets as shown below
int data[5] = {3,5,7,4,9};
In the above initialization, data[0] is initialized to 3, data[1] is initialized to 5 and so on..
3
data[0]
5
data[1]
7
data[2]
4
data[3]
9
data[4]
Self Assessment Questions
1. Arrays group data of __________ type
2. An array declared as int a[10] can store __________ integers
3. a[5] represents the _________ integer in the above array.
4. Array elements are accessed through _______________
3.3 Multidimensional Arrays
The arrays can be multidimensional as well to store the required data. For example a two dimensional array can be created to store data about a matrix. A 3x4 matrix that has 12 data elements can be created using the following declaration
int mat[3][4];
The above array has 3 rows and four columns. The elements in the array can be accessed by two indexes. To refer to an element in the first row and second column mat[0][1] has to be used as the index starts from zero.
The following program accepts from the user two 2x3 matrices and adds the two matrices.
//matrix.cpp
# include <iostream.h>
void main()
{ int a[2][3], b[2][3], c[2][3];
int i,j;
cout<<”Enter the elements for the first 2x3 matrix”;
for (i=0;i<2;i++)
for (j=0;j<3;j++)
{ cin>>a[i][j];}
cout<<”Enter the elements for the second 2x3 matrix”;
for (i=0;i<2;i++)
for (j=0;j<3;j++)
{
cin>>b[i][j];
c[i][j]=a[i][j]+b[i][j];
}
cout<<”The resultant matrix is”;
for ( i=0;i<2;i++)
{
for ( j=0;j<3;j++)
{
cout<<c[i][j]<<” “;
}
cout<< endl;
}
}
Multi dimensional arrays can also be initialized as follows
int a[2][2] = {{ 3,4},
{ 2, 7}}
Every row elements are initialized by enclosing them in separate flower brackets.In the above example elements 3 and 4 will be initialized to a[0][0] and a[0][1] respectively.
Self Assessment Questions
1. An array with the declaration int x[4][5] can store ________ numbers
2. In the above array the number in the third row and fourth column can be accessed by ____________
3. int a[ ] [ ] is a valid declaration. True/False
3.4 Strings and String related Library Functions
Strings are nothing but character arrays. Strings are usually used to store data such as employee name, address, product description, password etc. The size of the string is defined during declaration like any other array. One basic difference between other arrays and strings is that the compiler stores an extra null character (‘/0’) for every string to mark the end of the string. This enables a good means of identifying the end of the string as string variables usually store variable length values. Strings, unlike other arrays can be input without using a loop. When inputting strings using cin statement, the compiler stops taking input from the user once it encounters space or linefeed (pressing enter key). For example, consider the following program statements:
char str[10];
cin>>str;
If the user inputs “HELLO” and presses enter key , the contents for the str variable will be as follows:
H
str[0]
E
str[1]
L
str[2]
L
str [3]
O
str[4]
/0
str[5]
The strings can be also initialised as arrays. However they can be initialized by enclosing the characters in the string constant with double quotes instead of initializing it character by character. For example, the following statement initializes the str variable to “hello”:
char str[10]=”hello”;
Strings can also be defined without specifying the size, but in that case they have to be initialized to a string constant as shown in the following example.
char str[]=”hello world”
However, there is no built in mechanism in C++ that disallows the user to enter characters than the string maximum size. The extra characters entered by the user will be truncated. To keep a check on the number of characters, setw() function can also be used. To use this function, iomanip.h header file should be included.
#include<iostream.h>
#include<iomanip.h>
const int size=10;
void main()
{
Char str[size];
Cout<<”enter a string”;
Cin>>setw(size)>>str;
}
The above program allows user to enter only 9 characters(one character saved for null character).While inputting strings, cin stops reading once it encounters space or linefeed character( when user presses enter). To read blanks between the strings or to read multiple lines of text, get function which is a member function of cin can be used.The following statement will allow user to input a maximum of 39 characters which can even include blanks. It will stop reading once it encounters linefeed character.
cin.get(str, 40);
To read multiple line of text from the user, you have to specify a terminating character which will be used to recognize end of input. In the following example, the terminating character is $.
cin.get(str,40,$);
The above example will allow users to enter a maximum of 39 characters which can include embedded blanks and linefeed.
C++ has several string related library functions that are used to manipulate strings. Some of these are discussed below. To use these functions, header file string.h has to be included. Some of the library functions such as strlen, strcpy, strrev, strcmp is discussed below.
Strlen Function
Strlen function is used to find the length of the string. The syntax of the strlen function is strlen(string variable). The function returns the length of the string or the number of characters in the string which is a integer.
Example :
int len;
char str[10]=”hello”;
len=strlen(str);
In the above example, the number of characters in the string str(five in this case) is stored in the integer variable named len
Strrev function
Strrev function arranges the characters in the string variable in reverse order except for the null character. The syntax of strrev function is strrev(string variable). It returns the reversed string. For example, in the following program statement, the output will be olleh
The null character will be the last character of the string.
char str[10]=”hello”;
cout<<strrev(str);
Strcpy function
Strcpy function copies the contents of one string to another. The syntax of strcpy function is strcpy(destination string, source string). The function returns the destination string value after copying. For example, in the following program statement, the contents of the string str will be copied to string name
char str[10]=”ravi”;
char name[10];
strcpy(name,str);
The strcpy can also use string constants to be assigned to a string variable like in the following statement.
strcpy(name,”ravi”);
In the above statement the string constant ravi is assigned to the string variable name. The assignment of a string variable cannot be done using an assignment operator. It should be done using strcpy function. The following statement in a program will provide an compilation error:
name=”ravi”; //wrong statement
Strcmp function
Strcmp function is used to compare two strings. The syntax of strcmp is strcmp(string1,string2). Every character of string1 will be compared with corresponding character of string2. The ASCII values of the character will be used to decide the return value. The function returns an integer and the value returned will differ based on the conditions as shown below:
If string1 < string2, value returned will be <0
If string1==string2, value returned will be 0
If string1> string2, value returned will be greater than zero.
Thus, a return value 0 implies that strings are equal and a non zero return value implies than the two strings are not equal. Please note that the above function is case sensitive. Strcmpi() function can be used if the two strings have to be compared without case sensitiveness.
The following program implements strcmp function
# include <iostream.h>
# include<string.h>
const char str[6] = “XYZPQR”
void main()
{
char pass[6];
int flag=0;
for(int i=0;i<3;i++)
{
cout<<”Please enter your password”;
cin>>pass;
if (strcmp(str, pass)==0)
{
cout<<”Welcome”;
flag=1;
break;
}
else
cout<<”Invalid password, try again”<<endl;
}
}
if (flag==0)
cout<<”Access denied”;
}
Self Assessment Questions
1. char str[ ]; is a valid statement. True/False
2. char str[20] will allow maximum of ________ characters to stored in the string.
3. _________ member function of cin allows user to input embedded blanks and linefeed within the string.
4. _________ libray function can be used to copy the contents of one string to another string.
Summary
Arrays are used to store large volumes of similar data together. The array elements can be accessed by specifying array name followed by the number which indicates the position of the element in the array. Arrays of basic datatypes such as integers, characters etc and user defined datatypes such as structures, objects can be defined.
Arrays can be multidimensional to store data that are related.
Strings are character arrays that are handled slightly differently than other arrays. Every string has a null character ‘’ as its last character which marks the end of the string. There are several string related library functions that can be used to manipulate strings.
Terminal Questions
1. Write a program that stores 100 numbers in the array. The user should be able to search a particular number in the array. Implement sequential search for this purpose.
2. Implement the above program for binary search. Please note that binary search works with the sorted arrays only.
3. Write a program that accepts a 3x3 matrix from the user and finds the transpose of it.
4. Write a program to check whether a string is a palindrome or not. Please note that palindrome is one which remains the same if you reverse the characters in the string. For example “MADAM”.
Answers to SAQs in 3.2
1. same
2. ten
3. sixth
4. array name followed by index number in square brackets
Answers to SAQs in 3.3
1. 20
2. a[2][3]
3. False
Answers to SAQs in 3.4
1. False
2. 19 characters
3. get()
4. strcpy()
Answers to TQs
1. //seqsearch.cpp
# include<iostream.h>
void main()
{ int a[100], num;
int i, flag=0;
cout<<”please enter the numbers for the array”;
for( i=0;i<100;i++)
{ cin>>a[i];
}
cout<<”Enter the number to be searched”;
cin>>num;
for(i=0;i<100;i++)
{
if (a[i]==num)
{ cout<<num<<” is found”;
flag=1;
break;
}
}
if (flag==0)
cout<<num <<” not found”;
}
2. # include<iostream.h>
void main()
{ int a[10],temp;
int i,j,flag=0;
int start,end;
int search, mid;
cout<<"Please enter ten array elements";
for (i=0; i<10;i++)
{
cin>>a[i];
}
cout<<"Please enter the number to be searched";
cin>>search;
// Array sorting
for(j=0; j<9;j++)
for(i=0;i<9;i++)
{ if (a[i]>a[i+1])
{temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
start=0;
end=9;
do
{
mid=(start+end)/2;
if (a[mid]==search)
{cout<<search <<"found";
flag=1;
break;
}
if (a[mid]>search)
end=mid;
else if (a[mid]<search)
start=mid;
} while ((start<end)&&(mid!=start));
if (flag==0)
cout<<search<<" not found";
}
3. // transpose.cpp
# include<iostream.h>
void main()
{
int a[3][3], at[3][3];
int i,j;
cout<<”Enter the elements for the 3x3 matrix”;
for (i=0;i<3;i++)
for (j=0;j<3;j++)
{
cin>>a[i][j];
at[j][i]=a[i][j];
}
cout<<”The transpose is”;
for ( i=0;i<3;i++)
{
for ( j=0;j<3;j++)
{
cout<<at[i][j]<<” “;
}
cout<< endl;
}
}
4. // palindrome.cpp
# include<iostream.h>
# include <string.h>
void main()
{
char a[10];
int i,j,len;
int flag=0;
cout<<”Please enter the text to be checked”;
cin>>a;
len=strlen(a);
for(i=0, j=len-1;i<len/2;i++,j--)
{
if(a[i]!=a[j])
{flag=1;
break;}
}
if (flag==0)
cout<<” The text you have entered is a palindrome”;
else
cout<<”The text is not a palindrome”;
}
  • 0 likes

No comments:

Post a Comment