0% found this document useful (0 votes)
18 views61 pages

Fundamental of Programming CH5

Array

Uploaded by

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

Fundamental of Programming CH5

Array

Uploaded by

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

Computer Programming

Department of Computer Science

Target Group : Computer Science Dept

By:Bayisa G .

By: Bayisa G. [email protected]) |


CHAPTER FIVE
Arrays, Pointers and Strings
 What is an Array?
 a collection of a fixed number of components wherein all of the components
have the same data type (homogenous type)
– a set of elements all of the same type stored contiguously in memory
 a single name for a collection of data values all of the same data type
 subscript notation to identify one of the values
 Array declaration
 E.g: int pressure[];
– creates a name of type "int array"
– types int x and int x[ ] are different
– int x[ ]: type of the array
– int x: type of the individual values
By: Bayisa G. Computer Science Dept (Ambo University) 2
 How To Declare Arrays
• Syntax for declaring a one-dimensional array:
– intExp evaluates to a positive integer
• To declare an array in C++, you should specify the following things
– The data type of the values which will be stored in the array
– The name of the array (i.e. a C++ identifier that will be used to access
and update the array values)
– The dimensionality of the array:
 One dimensional (i.e. list of values ),
 Two-dimension array (a matrix or a table), etc.
– The size of each dimension
• If we would like to access a particular value stored in an array, we specify its
index (i.e. its position relative to the first array value)
– The first array index is always 0 and the second value is stored in index 1
etc.
By: Bayisa G. Computer Science Dept (Ambo University) 3
 Examples
• int myArray[5]; // An integer array named myArray with size 5
• float GPA[30]; // An array to store the GPA for 30 students
• int studentScores[30][5]; // A two-dimensional array to store the
scores of 5 exams for 30 students
myArray[5]

myArray[4]
 Arrays are contiguous memory
locations, and its name refers only myArray[3]

to the address of the first element myArray[2]

 When declaring an array, its size myArray[1]

must be known at compile-time


myArray[0]

By: Bayisa G. Computer Science Dept (Ambo University) 4


One-dimensional Arrays
 We use one-dimensional arrays to store and access list of data values in an
easy way by giving these values a common name, e.g.
int x[4]; // all values are named x
x[0] = 10; // the 1st value is 10
x[1] = 5; // the 2nd value is 5
x[2] = 20; // the 3rd value is 20
x[3] = 30; // the 4th value is 30
 Array Indices and Out-of-bound Run-time Error
int v[5];
cout<<v[5]; // this array contains 5 entries
 It is a common error to try to access the Nth entry, e.g. v[5] or V[N], since the
index of the last array entry is N-1, not N
By: Bayisa G. Computer Science Dept (Ambo University) 5
Initializing 1D Arrays
 There are two common ways to initialize one-dimensional arrays
 Using for loop, e.g. specify each element when array declared

int x[10];
for(int index = 0; index < 10; index++)
x[index] = index+1 ;
 Specifying list of values while declaring the 1D array, e.g.
int n[5] = { 1, 2, 3, 4, 5 };
int x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int y[ ] = {0, 0, 0}; // this array contains 3 entries with 0 values
 If not enough initializers, rightmost elements 0
 If too many, syntax error

By: Bayisa G. Computer Science Dept (Ambo University) 6


Initializing 1D Arrays...
 To set every element to 0
int n[5] = {0};
double z[100] = {0};
 this array contains 100 entries, all of which are initialized by 0
double w[20] = {5,3,1};
 this array contains 20 entries, the first three entries are initialized
by 5, 3, and1 respectively while the remaining 17 entries are
automatically initialized by 0
bool pass[10] = {true, true};
this array contains 10 entries. The first two entries are initialized to true,
while the remaining 8 entries are automatically initialized to false
 If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array
By: Bayisa G. Computer Science Dept (Ambo University) 7
Example: Total and average grade

By: Bayisa G.
Accessing 1D Array Components
 General syntax:

 where indexExp, called an index, is any expression whose value is a


nonnegative integer to specify the position of the component in the array
 [ ] is the array subscripting operator
 The array index always starts at 0
 E.g. int list[10];
 Storing values:
 Reading one value at a time from the user:
for (int index = 0; index < 10; index++)
cin >> list[index];
 Displaying values:
 Displaying one value per line to the user:
for (int index = 0; index < 10; index++)
cout << list[index] << endl;
By: Bayisa G. Computer Science Dept (Ambo University) 9
Accessing 1D Array Components...
list[5] = 34; list[3] = 10;
list[6] = 35;
list[5] = list[3] + list[6]

Array list after the execution of


the statement list[3] = 10;, list[6]
= 35;, list[5] = list[3] + list[6]

By: Bayisa G. Computer Science Dept (Ambo University) 10


Example

By: Bayisa G.
Example: Read Values and Print them in Reverse Order

By: Bayisa G. Computer Science Dept (Ambo University) 12


Example: Some Restrictions on Array Processing

• Aggregate operation: any operation that manipulates the entire array as a


single unit
– Not allowed on arrays in C++
• Example:

• Solution:

By: Bayisa G. Computer Science Dept (Ambo University) 13


Two-dimensional Array
 A two-dimensional array can be imagined as a bi-dimensional table of a uniform
concrete data type.
 Two-dimensional array: collection of a fixed number of components (of the same
type) arranged in two dimensions
 Sometimes called matrices or tables
 To declare bi-dimensional array:

 Where indexExp1 and indexExp2 are expressions with positive integer


values, and specify the row and column position
values(1, 1) values(1, 2) values(1, 3) values(1, 4) values(1, 5) values(1, 6)
values(2, 1) values(2, 2) values(2, 3) values(2, 4) values(2, 5) values(2, 6)
values(3, 1) values(3, 2) values(3, 3) values(3, 4) values(3, 5) values(3, 6)

 Example:
sales[5][3] = 25.75;
By: Bayisa G. Computer Science Dept (Ambo University) 14
Two-dimensional Array...

 Two-dimensional arrays can be initialized when they are declared:


 Elements of each row are enclosed within braces and separated by commas
 All rows are enclosed within braces
 For number arrays, unspecified elements are set to 0
By: Bayisa G. Computer Science Dept (Ambo University) 15
Multi-dimensional Array
 Multidimensional arrays can be described as arrays of arrays.
 To declare multi-dimensional array:
dataType arrayName[idexExp1][indexExp2]...[indexExpN]

 N-dimensional array
 C++ allows you to use as many dimensions as needed
 But be careful!
 The amount of memory needed for an array rapidly increases with each
dimension.
 For example:
char century [100][365][24][60][60];
declares an array with a char element for each second in a century, that is more
than 3 billion chars.
 So this declaration would consume more than 3 gigabytes of memory!

By: Bayisa G. Computer Science Dept (Ambo University) 16


Multi-dimensional Array...
 The simplest way to declare a multidimensional array is like this:
double a[32][10][4]; //three dimensional array
 This is a three-dimensional array with dimensions 32, 10, and 4.
 The statement
a[25][8][3] = 99.99
would assign the value 99.99 to the element identified by the multi-index (25,8,3).
 Initializing multidimensional arrays is similar to initializing single-dimension
arrays.
 A set of curly braces { } encloses each element. E.g. This is shorthand for:
matrix[0][0] = 1;
int matrix[2][4] = matrix[0][1] = 2;
{ matrix[0][2] = 3;
{ 1, 2, 3, 4 }, matrix[0][3] = 4;
{ 10, 20, 30, 40 } matrix[1][0] = 10;
}; matrix[1][1] = 20;
matrix[1][2] = 30;
matrix[1][3] = 40;
By: Bayisa G. Computer Science Dept (Ambo University) 17
Processing Multi-dimensional Array
 Initialization during declaration: elements of each row are enclosed within braces
and separated by commas
 All rows are enclosed within braces
 For number arrays, if all components of a row aren’t specified, unspecified ones are set to 0
 Ways to process a two-dimensional array:
 Process entire array
 Row processing: process a single row at a time
 Column processing: process a single column at a time
 Each row and each column of a two-dimensional array is a one-dimensional
array; to process, use algorithms similar to processing one-dimensional arrays

By: Bayisa G. Computer Science Dept (Ambo University) 18


Processing Multi-dimensional Array...

 To initialize row number 4 (i.e., fifth row) to 0

By: Bayisa G. Computer Science Dept (Ambo University) 19


Processing Multi-dimensional Array...
 To initialize the entire matrix to 0 and output the components of matrix:

 To input data into each component of matrix:

By: Bayisa G. Computer Science Dept (Ambo University) 20


Sum by Row
• To find the sum of row number 4 of matrix:

• To find the sum of each individual row:

By: Bayisa G. Computer Science Dept (Ambo University) 21


Sum by Column

• To find the sum of each individual column:

By: Bayisa G. Computer Science Dept (Ambo University) 22


Largest Element in Each Row and Each Column

By: Bayisa G. Computer Science Dept (Ambo University) 23


Pointers in C++
 What is a Pointer?
 A pointer is a reference to another variable (memory location) in a program
– Variable in a program is something with a name, the value of which can
vary.
– The way the compiler and linker handles this is that it assigns a specific
block of memory within the computer to hold the value of that variable.
– For a C++ program, the memory of a computer is like a succession of
memory cells, each one byte in size, and each with a unique address.
– These single-byte memory cells are ordered in a way that allows data
representations larger than one byte to occupy memory cells that have
consecutive addresses.
• address depends on computer/operating system

By: Bayisa G. Computer Science Dept (Ambo University) 24


 When we declare a variable we inform the compiler of two things, the name
of the variable and the type of the variable.
 For example, we declare a variable of type integer with the name v by
writing:
int v;
 On seeing the "int" part of this statement the compiler sets aside 4 bytes of
memory to hold the value of the integer.
 It also sets up a symbol table. In that table it adds the symbol v and the
relative address in memory where those 4 bytes were set aside.
 Thus, later if we write: v = 101; we expect that, at run time when this
statement is executed, the value 101 will be placed in that memory location
reserved for the storage of the value of v.
 In C++ we refer to a variable such as the integer v as an "object".
 In a sense there are two "values" associated with the object v

By: Bayisa G. Computer Science Dept (Ambo University) 25


 One is the value of the integer stored there (101 in the above example) and
the other the "value" of the memory location, i.e., the address of v.
 Variables are allocated at addresses in computer memory (address depends
on computer architecture)
 Name of the variable is a reference to that memory address
 A pointer variable contains a representation of an address of another variable
(P is a pointer variable in the following):

By: Bayisa G. Computer Science Dept (Ambo University) 26


Reference operator (&)
 As soon as we declare a variable, the amount of memory needed is assigned for
it at a specific location in memory (its memory address).
 We generally do not actively decide the exact location of the variable within the
panel of cells that we have imagined the memory to be - Fortunately, that is a
task automatically performed by the operating system during runtime.
 However, in some cases we may be interested in knowing the address where
our variable is being stored during runtime in order to operate with relative
positions to it.
 The address that locates a variable within memory is what we call a reference to
that variable.
 This reference to a variable can be obtained by preceding the identifier of a
variable with an ampersand sign (&), known as reference operator, and which
can be literally translated as "address of".
 For example:
ted = &andy;
By: Bayisa G. Computer Science Dept (Ambo University) 27
Reference operator (&)
 This would assign to ted the address of variable andy
 since when preceding the name of the variable andy with the reference operator (&) we are
no longer talking about the content of the variable itself, but about its reference (i.e., its
address in memory).
 Let’s assume that andy is placed during runtime in the memory address 1776.
 This number (1776) is just an arbitrary assumption we are inventing right now in order to
help clarify some concepts in this tutorial
 Consider the following code fragment:
andy = 25;
fred = andy;
ted = &andy;

By: Bayisa G. Computer Science Dept (Ambo University) 28


Dereference operator (*)
 Using a pointer we can directly access the value stored in the variable which it
points to.
 To do this, we simply have to precede the pointer's identifier with an asterisk (*),
which acts as dereference operator and that can be literally translated to "value
pointed by".
 Therefore, following with the values of the previous example, if we write:
beth = *ted;
 (that we could read as: "beth equal to value pointed by ted") beth would take the value 25,
since ted is 1776, and the value pointed by 1776 is 25.

By: Bayisa G. Computer Science Dept (Ambo University) 29


Dereference operator (*)
 You must clearly differentiate that the expression ted refers to the value 1776,
while *ted (with an asterisk * preceding the identifier) refers to the value stored
at address 1776, which in this case is 25.
 Notice the difference of including or not including the dereference operator
beth = ted; // beth equal to ted ( 1776 )
beth = *ted; // beth equal to value pointed by ted ( 25 )
– & is the reference operator and can be read as "address of"
– * is the dereference operator and can be read as "value pointed by"
 Earlier we performed the following two assignment operations:
andy = 25;
ted = &andy;
 Right after these two statements,
andy == 25
&andy == 1776
ted == 1776
*ted == 25
By: Bayisa G. Computer Science Dept (Ambo University) 30
Pointer Variable Declaration
 Due to the ability of a pointer to directly refer to the value that it points to, it
becomes necessary to specify in its declaration which data type a pointer is
going to point to.
 It is not the same thing to point to a char as to point to an int or a float.
 Pointers are declared as follows:
<type> * variable_name ;
 Example:
 int * xPtr; // xPtr is a pointer to data of type integer
 char * cPtr; // cPtr is a pointer to data of type character
 float * Q; // Q is a float pointer
 Each one is intended to point to a different data type, but in fact all of them are
pointers and all of them will occupy the same amount of space in memory
 Nevertheless, the data to which they point to do not occupy the same amount of
space nor are of the same type: the first one points to an int, the second one to
a char and the last one to a float.
By: Bayisa G. Computer Science Dept (Ambo University) 31
Example 1
 The first pointer program

 Output:
firstvalue is 10
secondvalue is 20
 Notice that even though we have never directly set a value to either firstvalue or secondvalue,
both end up with a value set indirectly through the use of mypointer.

By: Bayisa G. Computer Science Dept (Ambo University) 32


Example 2
 Here is an example a little bit more elaborated:

 Output:
firstvalue is 10
secondvalue is 20
By: Bayisa G. Computer Science Dept (Ambo University) 33
Pointers and Arrays
 The concept of array is very much bound to the one of pointer.
 In fact, the identifier of an array is equivalent to the address of its first element,
as a pointer is equivalent to the address of the first element that it points to, so
in fact they are the same concept.
 For example, supposing these two declarations:
int numbers [20];
int* p;
 The following assignment operation would be valid:
p = numbers;
 After that, p and numbers would be equivalent and would have the same
properties.
 The only difference is that we could change the value of pointer p by another
one, whereas numbers will always point to the first of the 20 elements of type
int with which it was defined.

By: Bayisa G. Computer Science Dept (Ambo University) 34


Pointers and Arrays
 Therefore, unlike p, which is an ordinary pointer, numbers is an array, and an
array can be considered a constant pointer.
 Therefore, the following allocation would not be valid:
numbers = p;
 Because numbers is an array, so it operates as a constant pointer, and we
cannot assign values to constants.
 If we declare an array A[4] and a
pointer a
 a is equal to the address of the first
element of A
• a == & A[0]
 Accessing array elements with pointers:
 Element A[i] can be accessed by
*(a+i)
 This is called pointer/offset notation
 Output: 10, 20, 30, 40, 50,
By: Bayisa G. Computer Science Dept (Ambo University) 35
Pointers and Arrays
 In the previous slides about arrays we used brackets ([ ]) several times in order
to specify the index of an element of the array to which we wanted to refer.
 Well, these bracket sign operators [ ] are also a dereference operator known as
offset operator.
 They dereference the variable they follow just as * does, but they also add the
number between brackets to the address being dereferenced.
 For example:
a[5] = 0; // a [offset of 5] = 0
*(a+5) = 0; // pointed by (a+5) = 0
 These two expressions are equivalent and valid both if a is a pointer or if a is an
array.

By: Bayisa G. Computer Science Dept (Ambo University) 36


Pointer Initialization
 When declaring pointers we may want to explicitly specify which variable we
want them to point to:
int number;
int *tommy = &number;
 The behavior of this code is equivalent to:
int number;
int *tommy;
tommy = &number;
 When a pointer initialization takes place we are always assigning the reference
value to where the pointer points (tommy), never the value being pointed
(*tommy).
 You must consider that at the moment of declaring a pointer, the asterisk (*)
indicates only that it is a pointer, it is not the dereference operator (although
both use the same sign: *).
 Remember, they are two different functions of one sign.
By: Bayisa G. Computer Science Dept (Ambo University) 37
Pointer Initialization
 Thus, we must take care not to confuse the previous code with:
int number;
int *tommy;
*tommy = &number;
 that is incorrect, and anyway would not have much sense in this case if you
think about it.
 As in the case of arrays, the compiler allows the special case that we want to
initialize the content at which the pointer points with constants at the same
moment the pointer is declared:
char * terry = "hello";
 In this case, memory space is reserved to contain "hello" and then a pointer to
the first character of this memory block is assigned to terry.
 If we imagine that "hello" is stored at the memory locations that start at
addresses 1702, we can represent the previous declaration as:

By: Bayisa G. Computer Science Dept (Ambo University) 38


Pointer Initialization

 It is important to indicate that &terry contains the value 1702, and not 'h' nor
"hello", although 1702 indeed is the address of both of these.
 The pointer terry points to a sequence of characters and can be read as if it was
an array (remember that an array is just like a constant pointer).
 For example, we can access the fifth element of the array with any of these two
expression: *(terry+4)
terry[4]
 Both expressions have a value of 'o' (the fifth element of the array).
By: Bayisa G. Computer Science Dept (Ambo University) 39
Pointer to Pointers
 C++ allows the use of pointers that point to pointers, that these, in its turn, point
to data (or even to other pointers).
 In order to do that, we only need to add an asterisk (*) for each level of
reference in their declarations:
char a;
char * b;
char ** c;
a = 'z';
b = &a;
c = &b;
 This, supposing the randomly chosen memory locations for each variable of
7230, 8092 and 10502, could be represented as:

By: Bayisa G. Computer Science Dept (Ambo University) 40


Pointer to Pointers
 The value of each variable is written inside each cell; under the cells are their
respective addresses in memory.
 The new thing in this example is variable c, which can be used in three different
levels of indirection, each one of them would correspond to a different value:
c has type char** and a value of 8092 (memory location of b)
*c has type char* and a value of 7230 (memory location of a)
**c has type char and a value of 'z' (equals to ‘z’)

By: Bayisa G. Computer Science Dept (Ambo University) 41


Void Pointers
 The void type of pointer is a special type of pointer.
 In C++, void represents the absence of type, so void pointers are pointers that
point to a value that has no type (and thus also an undetermined length and
undetermined dereference properties).
 This allows void pointers to point to any data type, from an integer value or a
float to a string of characters.
 But in exchange they have a great limitation: the data pointed by them cannot
be directly dereferenced (which is logical, since we have no type to dereference
to), and for that reason we will always have to cast the address in the void
pointer to some other pointer type that points to a concrete data type before
dereferencing it.
 One of its uses may be to pass generic parameters to a function.

By: Bayisa G. Computer Science Dept (Ambo University) 42


Void Pointers
int V = 101;
void *G = &V;
int *P = (int*)G;
cout << "G = "<< G << endl;
cout << "(int*)G = " << (int*)G <<endl;
cout << "P = " << P << endl;
cout << "*P = " << *P << endl;

OUTPUT
G = 0x40583ff6cc
(int*)G = 0x40583ff6cc

P = 0x40583ff6cc
*P = 101

By: Bayisa G. Computer Science Dept (Ambo University) 43


Null Pointers
 A null pointer is a regular pointer of any pointer type which has a special value
that indicates that it is not pointing to any valid reference or memory address.
 This value is the result of type-casting the integer value zero to any pointer type.
int * p;
p = 0; // p has a null pointer value
 Do not confuse null pointers with void pointers.
 A null pointer is a value that any pointer may take to represent that it is pointing
to "nowhere", while a void pointer is a special type of pointer that can point to
somewhere without a specific type.
 One refers to the value stored in the pointer itself and the other to the type of
data it points to.

By: Bayisa G. Computer Science Dept (Ambo University) 44


C++ Strings
 One of the most useful data types supplied in the C++ libraries is the string.
 A string is a variable that stores a sequence of letters or other characters, such
as "Hello" or "May 10th is my birthday!".
 E.g. string testString = "This is a string.";
 Often, we use strings as output, and cout works exactly like one would expect:
cout << testString << endl;
 will print the same result as
cout << "This is a string." << endl;
 Strings are represented by C++ as a sequence of characters in memory.
 A string is simply a character array and can be manipulated as such.
 Formatted Input: Stream extraction operator
cin >> stringObject;
 the extraction operator >> formats the data that it receives through its
input stream; it skips over whitespace
By: Bayisa G. Computer Science Dept (Ambo University) 45
C++ Strings
 Unformatted Input: getline function for a string
getline( cin, s)
 does not skip over whitespace and delimited by newline
 reads an entire line of characters into s
 Example: string s = “ABCDEFG”;
getline(cin, s); //reads entire line of characters into s
char c = s[2]; //assigns ‘C’ to c
s[4] = ‘*’; //changes s to “ABCD*FG”
string s; //s contains 0 characters
string s1( "Hello" ); //s1 contains 5 characters
string s2 = “Hello”; //s2 contains 5 characters
string s3( 8, 'x' ); //s3 contains 8 'x' characters
string s4 = s3; //s4 contains 8 'x' characters
string s5(s2, 3, 2); //s5 copies a substring of s2; it contains ”lo”

By: Bayisa G. Computer Science Dept (Ambo University) 46


String Basic Operations
 Counting the number of characters in a string
 The length() method returns the number of characters in a string, including
spaces and punctuation.
 E.g. string small, large;
small = "I am short";
large = "I, friend, am a long and elaborate string indeed";
cout << "The short string is " << small.length() << " characters."
<< endl;
cout << The long string is " << large.length()<< " characters."
<< endl;
 The above program produce the following output.
The short string is 10 characters.
The long string is 48 characters.

By: Bayisa G. Computer Science Dept (Ambo University) 47


String Basic Operations
 Passing, returning, assigning strings
 C++ strings are designed to behave like ordinary primitive types with regard
to assignment.
 Assigning one string to another makes a deep copy of the character
sequence.
 E.g. string str1 = "hello";
string str2 = str1; // makes a new copy
str1[0] = 'y'; // changes str1, but not str2
 Comparing two strings
 You can compare two strings for equality using the == and != operators.
 E.g. cout << "Enter your name (or 'quit' to exit): ";
string userName; cin>>userName;
if (userName == "Julie") {
cout << "Hi, Julie! Welcome back!" << endl;
} else cout << userName<<“, Who are you?”;
By: Bayisa G. Computer Science Dept (Ambo University) 48
String Basic Operations
 Extracting substrings
 Sometimes you would like to create new strings by extracting portions of a
larger one.
 The substr member function creates substrings from pieces of the receiver
string.
 You specify the starting position and the number of characters.
 For example, str.substr(start, length) returns a new string consisting of
the characters from str starting at the position start and continuing for
length characters.
 E.g. string oldSentence = "The quick brown fox jumped WAY over the
lazy dog";
int len = oldSentence.length();
string newSentence = oldSentence.substr(0, 30);
cout << "Modified sentence: " << newSentence << endl;
• OUTPUT:Modified sentence: The quick brown fox jumped WAY
By: Bayisa G. Computer Science Dept (Ambo University) 49
Character Sequences
 Because strings are in fact sequences of characters, we can represent them
also as plain arrays of char elements.
 The special character ' \0' (NULL) is used to indicate the end of a string.
 Example: The following program creates a character array four elements long.
 Note that we had to allocate one character for the end-of-string marker.

By: Bayisa G. Computer Science Dept (Ambo University) 50


Character Sequences
 The string may be initialized with a string literal, like this:
char str[] = "Finfine";
 Note that this array has 8 elements: ‘F’, ‘i’, ‘n’, ‘f’, ‘i’,‘n’, ‘e’,and ‘\0’.
 The entire string may be output as a single object, like this:
cout << str;
 The system will copy characters from str to cout until the NULL character ‘\0’ is
encountered.
 The entire string may be input as a single object, like this:
cin >> buffer;
 The system will copy characters from cin into buffer until a white space
character is encountered. The user must ensure that buffer is defined to be a
character string long enough to hold the input.
 But also, if we want to initialize an array of characters with some predetermined
sequence of characters we can do it just like any other array:
char str[] = { 'F', 'i', 'n', 'f', 'i','n', 'e' };
By: Bayisa G. Computer Science Dept (Ambo University) 51
Character Sequences
 This little demo program shows that the NULL character ‘\0’ is appended to the
string:

 Output:

By: Bayisa G. Computer Science Dept (Ambo University) 52


Character Sequences
 String constants consist of text enclosed in double quotes (").
 You may have already noticed that we've used string constants extensively for
output with the cout standard class.
 You must use the standard library function strcpy to copy the string constant
into the variable. (strcpy copies the whole string including the end-of string
character.)
 To initialize the variable name to "Sam" you would write:
char name[4];
strcpy(name, "Sam"); // Legal
 NOTE
 The line:
#include <cstring>
is needed to inform C++ that you are using the string function library.

By: Bayisa G. Computer Science Dept (Ambo University) 53


Character Sequences

 C++ uses variable-length strings. For example, the declaration:


char string[50];
strcpy(string, "Sam");
creates an array (string) that can contain up to 50 characters.
By: Bayisa G. Computer Science Dept (Ambo University) 54
Character Sequences
 C++ supports a range of string-manipulation functions.
 The most common are:
 strcpy() : copy characters from one string to another
 strcat() : concatenation of strings
 strlen() : length of a string
 strcmp() : comparison of strings

Function Description
strcpy(string1, string2) Copies string2 into string1
strcat(string1, string2) Concatenates string2 onto the end of
string1
length = strlen(string) Gets the length of a string
strcmp(stringl, string2) 0 if string1 equals string2; otherwise,
nonzero
By: Bayisa G. Computer Science Dept (Ambo University) 55
Character Sequences
 There are several standard routines that work on string variables.

By: Bayisa G. Computer Science Dept (Ambo University) 56


Character Sequences
 Comparing strings

By: Bayisa G. Computer Science Dept (Ambo University) 57


Character Sequences
 Length of strings

By: Bayisa G. Computer Science Dept (Ambo University) 58


Reading Strings
 The general form of a cin statement is:
cin >> variable;
 This works for all types of simple variables such as int, float, and char.
 When you read in strings, sometimes you want to read a whole line at a time
 There is a special function, getline, which can be used to read in the whole line
 It will even automatically discard the newline character at the end.

By: Bayisa G. Computer Science Dept (Ambo University) 59


Reading Strings
 getline could also be useful if you wanted to read user input only up to another
character, such as a comma (the user still has to hit enter before the program
will actually accept the data, though):
getline( cin, my_string, ',' );
 Now if the user types: Hello, World
 The value "Hello" will go into my_string.The rest of the text, in this case, "World",
will remain in the input buffer until your program reads it with another input
statement.

By: Bayisa G. Computer Science Dept (Ambo University) 60


THE END
THANK YOU!

«NEXT»
Ξ Structures and
Enumeration

Bayisa G. CS (Ambo University) 61

You might also like