0% found this document useful (0 votes)
7 views45 pages

Chapter 4

Uploaded by

abebemako302
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views45 pages

Chapter 4

Uploaded by

abebemako302
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

ü Variables in a program have values associated with them.

ü During program execution these values are accessed by using the


identifier associated with the variable in expressions etc.
ü If only a few values were involved a different identifier could be
declared for each variable, but now a loop could not be used to
enter the values.
ü Using a loop and assuming that after a value has been entered and
used no further use will be made of it allows the following code
to be written. This code enters six numbers and outputs their sum:
ü This code enters six numbers and outputs their sum:
sum = 0.0;
for (i = 0; i < 6; i++){
cin >> x;
sum += x;
}
PThis of course is easily extended to n values where n can be as
large as required.
PHowever if it was required to access the values later the above
would not be suitable.
PIt would be possible to do it as follows by setting up six individual
variables:
float a, b, c, d, e, f;
ü and then handling each value individually as follows:
sum = 0.0;
cin >> a;
sum += a;
cin >> b;
sum += b;
cin >> c;
sum += c;
cin >> d;
sum += d;
cin >> e;
sum += e;
cin >> f;
sum += f;
ü which is obviously a very tedious way to program.
ü If there were 10000 values imagine the tedium of typing the
program (and making up variable names and remembering which
is which)!
PTo get round this difficulty all high-level programming languages
use the concept of a data structure called an Array.
PAn array is a data structure which allows a collective name to be
given to a group of elements which all have the same type.
PAn individual element of an array is identified by its own unique
index (or subscript).
PThe index must be an integer and indicates the position of the
element in the array.
PThus the elements of an array are ordered by the index.
PTypes of array one dimensional and multi dimensional array.
PAn array declaration is very similar to a variable declaration.
PSyntax :
Type Array_name[ No of elements]
P The number of elements must be an integer.
PFor example data on the average temperature over the year in
Ethiopia for each of the last 100 years could be stored in an array
declared as follows:
float annual_temp [100];
P This declaration will cause the compiler to allocate space for 100 consecutive
float variables in memory.
P The number of elements in an array must be fixed at compile time.
P It is best to make the array size a constant and then, if required, the program
can be changed to handle a different size of array by changing the value of the
constant,
const int NE = 100;
float annual_temp[NE];
ü It would not work if an ordinary variable was used for the size in the array
declaration since at compile time the compiler would not know a value for it.
P The first element in an array always has the index 0, and if the array has n
elements the last element will have the index n-1.
P An array element is accessed by writing the identifier of the array followed
by the subscript in square brackets.
P Thus to set the 15th element of the array above to 1.5 the following assignment
is used:
annual_temp[14] = 1.5; Note that since the first element is at index 0, then
the ith element is at index i-1.
P Hence in the above the 15th element has index 14.
P A value can be read into an array element directly, using cin
cin >> count[i];
ü The element can be increased by 5,
count[i] = count[i] + 5; or, using the shorthand form of the assignment
count[i] += 5;
 Array elements can form part of the condition for an if statement, or indeed,
for any other logical expression:
if (annual_temp[j] < 10.0) cout << "It was cold this year " << endl;
P loop statements are the usual means of accessing every element in an array.
P Here, the first NE elements of the array annual_temp are given values from the
input stream cin.
for (i = 0; i < NE; i++) cin >> annual_temp[i];
P The following code finds the average temperature recorded in the first ten
elements of the array.
sum = 0.0;
for (i = 0; i <10; i++)
sum += annual_temp[i];
av1 = sum / 10;
P An array can be initialized in a similar manner with variable.
P For example initializing an array to hold the first few prime numbers could be
written as follows:
int primes[ ] = {1, 2, 3, 5, 7, 11, 13};
P If the array is given a size then this size must be greater than or equal to the
number of elements in the initialization list. For example:
int primes[10] = {1, 2, 3, 5, 7};
ü would reserve space for a ten element array but would only initialize the first
five elements.
P Example Program
P A set of positive data values (200) are available. It is required to find the
average value of these values and to count the number of values that are more
than 10% above the average value.
P Since the data values are all positive a negative value can be used as a sentinel
to signal the end of data entry.
P Obviously this is a problem in which an array must be used since the values
must first be entered to find the average and then each value must be
compared with this average.
P Hence the use of an array to store the entered values for later re-use.
P An initial algorithmic description is:
Ø initialize.
Øenter elements into array and sum elements.
Ø evaluate average.
Ø scan array and count number greater than 10% above average.
Ø output results.
Ø This can be expanded to the complete algorithmic description:
ü This can be expanded to the complete algorithmic description:
Ø set sum to zero.set count to zero.set nogt10 to zero.
Ø enter first value.
Ø while value is positive {
Ø put value in array element with index count.
Ø add value to sum.
Ø increment count.
Ø enter a value. }
Ø average = sum/count.
Ø for index taking values 0 to count-1
Ø if array[index] greater than 1.1*average
Ø then increment nogt10.
Ø output average, count and nogt10.
P The assignment operator cannot be applied to array variables:
const int SIZE=10
int x [SIZE] ;
int y [SIZE] ;
x=y; // Error - Illegal
ü Only individual elements can be assigned to using the index operator, e.g.,
x[1] = y[2];.
P To make all elements in 'x' the same as those in 'y' (equivalent to assignment),
a loop has to be used.
// Loop to do copying, one element at a time
for (int i = 0 ; i < SIZE; i++)
x[i] = y[i];

P This code will copy the elements of array y into x, overwriting the original
contents of x.
P A loop like this has to be written whenever an array assignment is needed.
ü An array may have more than one dimension.
ü Each dimension is represented as a subscript in the array.
ü Therefore a two dimensional array has two subscripts, a three dimensional
array has three subscripts, and so on.
ü Arrays can have any number of dimensions, although most of the arrays that
you create will likely be of one or two dimensions.
ü A chess board is a good example of a two-dimensional array. One dimension
represents the eight rows, the other dimension represents the eight columns.
ü Syntax
Type Multi_arrayName [ ] [ ];
P To initialize a multidimensional arrays , you must assign the list of values to
array elements in order, with last array subscript changing while the first
subscript holds steady.
P The program initializes this array by writing
int theArray[5][3] ={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
P for the sake of clarity, the program could group the initializations with braces,
as shown below.
int theArray[5][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13,
14,15} };
P If a one-dimensional array is initialized, the size can be omitted as it can be
found from the number of initializing elements:
int x[] = { 1, 2, 3, 4} ;
ü This initialization creates an array of four elements.
P Note however:
int x[][] = { {1,2}, {3,4} } ; // error is not allowed.
ü and must be written
int x[2][2] = { {1,2}, {3,4} } ;
PString is nothing but a sequence of character in which the last
character is the null character ‘\0’.
PThe null character indicates the end of the string.
PAny array of character can be converted into string type in C++
by appending this special character at the end of the array
sequence.
PSyntax

char StringName[ ];
PFor example a string variable s1 could be declared as follows:
char s1[10];
PThe string variable s1 could hold strings of length up to nine
characters since space is needed for the final null character.
PStrings can be initialized at the time of declaration just as other
variables are initialized. For example:
char s1[] = "example";
char s2[20] = "another example"
ü would store the two strings as follows:
s1 |e|x|a|m|p|l|e|\0|
s2 |a|n|o|t|h|e|r| |e|x|a|m|p|l|e|\0|?|?|?|?|
ü Note that the length of a string does not include the terminating
null character.
ü A string is output by sending it to an output stream, for example:
cout << "The string s1 is " << s1 << endl;
ü would print
The string s1 is example
ü When the input stream cin is used space characters, newline etc.
are used as separators and terminators.
ü Thus when inputting numeric data cin skips over any leading
spaces and terminates reading a value when it finds a white-
space character (space, tab, newline etc. ).
ü This same system is used for the input of strings, hence a string
to be input cannot start with leading spaces, also if it has a space
character in the middle then input will be terminated on that
space character.
ü To read a string with several words in it using cin we have to call cin once
for each word.
ü For example to read in a name in the form of a First_name followed by a
Last_name we might use code as follows:
char firstname [12], lastname[12];
cout << "Enter name ";
cin >> firstname ;
cin >> lastname;
cout << "The name entered was "
<< firstname << " "
<< lastname;
ü To read text containing blanks we use another function, cin.get( ).
#include<iostream.h>
void main()
{
const int max=80;
char str[max];
cout<<"\n Enter a string;";
cin.get(str , max); // max avoid buffer overflow
cout<<"\n You entered : "<<str;
}
Reading multiple lines
ü We have solved the problem of reading strings with embedded blanks,
but what about strings with multiple lines?
ü It turns out that the cin.get() function can take a third argument to
help out in this situation.This argument specifies the character that
tells the function to stop reading.
ü The default value of this argument is the newline('\n')character, but if
you call the function with some other character for this argument, the
default will be overridden by the specified character.
ü In this example, we call the function with a dollar sign ('$') as the third
argument
//reads multiple lines, terminates on '$' character
#include<iostream.h>
void main(){
const int max=80;
char str[max];
cout<<"\n Enter a string:\n";
cin.get(str, max, '$'); //terminates with $
cout<<\n You entered:\n"<<str; }
String constants
PYou can initialize a string to a constant value when you define it.
Here's an example'
#include<iostream.h>
void main(){
char str[] = "Welcome to C++ programming language";
cout<<str;
}
Copying string the hard way
ü The best way to understand the true nature of strings is to deal with them
character by character
#include<iostream.h>
#include<string.h> //for strlen()
int main(){
const int max=80;
char str1[]='‘ my Captain! our fearful trip is done";
char str2[max];
for(int i=0; i<strlen(str1);i++)
str2[i]=str1[1];
str2[i]='\0';
cout<<endl;
cout<<str2;
}
Copying string the easy way
ü You can copy strings using strcpy or strncpy function.
ü We assign strings by using the string copy function strcpy.
ü The prototype for this function is in string.h.
strcpy(destination, source);
ü strcpy copies characters from the location specified by source to the location
specified by destination.
ü It stops copying characters after it copies the terminating null character.
ü The return value is the value of the destination parameter.
Copying string the easy way
ü You must make sure that the destination string is large enough to hold all of
the characters in the source string (including the terminating null character).
Example:
#include <iostream.h>
#include <string.h>
void main(){
char me[20] = "David";
cout << me << endl;
strcpy(me, "YouAreNotMe");
cout << me << endl ;
return;
}
PThere is also another function strncpy, is like strcpy, except
that it copies only a specified number of characters.
strncpy(destination, source, int n);
P It may not copy the terminating null character.
It may not copy the terminating null character.
Example
#include <iostream.h>
#include <string.h>
void main() {
char str1[] = "String test";
char str2[] = "Hello";
char one[10];
strncpy(one, str1, 9);
one[9] = '\0';
cout << one << endl;
strncpy(one, str2, 2);
cout << one << endl;
strcpy(one, str2);
cout << one << endl;
}
Concatenating strings
ü In C++ the + operator cannot normally be used to concatenate
string, as it can in some languages such as BASIC; that is you
can't say: str3 = str1 + str2;
ü You can use strcat() or strncat
ü The function strcat concatenates (appends) one string to the end
of another string.
strcat(destination, source);
ü Example:
#include <iostream.h>
#include <string.h>
void main() {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strcat(str1, "def");
cout << str1 << endl;
char str2[] = "xyz";
strcat(str1, str2);
cout << str1 << endl;
str1[4] = '\0';
cout << str1 << endl;
}
P The function strncat is like strcat except that it copies only a specified
number of characters.
strncat(destination, source, int n);
P It may not copy the terminating null character.
Example:
#include <iostream.h>
#include <string.h>
void main() {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strncat(str1, "def", 2);
str1[5] = '\0';
cout << str1 << endl;
char str2[] = "xyz";
strcat(str1, str2);
cout << str1 << endl;
str1[4] = '\0';
cout << str1 << endl;
}
Comparing strings
ü Strings can be compared using strcmp or strncmp functions
ü The function strcmp compares two strings.
strcmp(str1, str2);
strcmp returns: < 0 if str1 is less than str2
= 0 if str1 is equal to str2
> 0 if str1 is greater than str2
Example:
#include <iostream.h>
#include <string.h>
void main() {
cout << strcmp("abc", "def") << endl;
cout << strcmp("def", "abc") << endl;
cout << strcmp("abc", "abc") << endl;
cout << strcmp("abc", "abcdef") << endl;
cout << strcmp("abc", "ABC") << endl;
PThe function strncmp is like strcmp except that it compares
only a specified number of characters.
strncmp(str1, str2, int n);
P strncmp does not compare characters after a terminating null
character has been found in one of the strings.
Example:
#include <iostream.h>
#include <string.h>
void main()
{
cout << strncmp("abc", "def", 2) << endl;
cout << strncmp("abc", "abcdef", 3) << endl;
cout << strncmp("abc", "abcdef", 2) << endl;
cout << strncmp("abc", "abcdef", 5) << endl;
cout << strncmp("abc", "abcdef", 20) << endl;
}
Thank you!!!

You might also like