0% found this document useful (0 votes)
10 views28 pages

C++ Chapter 4

Chapter 4 covers arrays and string manipulations in C++. It explains the properties and declaration of one-dimensional and two-dimensional arrays, as well as how to initialize, access, and manipulate strings. The chapter also discusses string input/output, copying, and concatenation methods in C++.

Uploaded by

balewgizie1
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)
10 views28 pages

C++ Chapter 4

Chapter 4 covers arrays and string manipulations in C++. It explains the properties and declaration of one-dimensional and two-dimensional arrays, as well as how to initialize, access, and manipulate strings. The chapter also discusses string input/output, copying, and concatenation methods in C++.

Uploaded by

balewgizie1
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/ 28

Chapter 4

Arrays and String Manipulations


Introduction
Array
• A collection of identical data objects, which are stored in
consecutive memory locations under a common heading or a
variable name.
• In other words, an array is a group or a table of values referred
to by the same name.
• The individual values in the array are called elements.
• Array elements are also variables.
• Set of values of the same type, which have a single name
followed by an index.
• In C++, square brackets “ []” appear around the index right
after the name

2
Properties of Arrays

• Arrays in C++ are zero-bounded;


– that is the index of the first element in the array is 0 and
the last element is N-1, where N is the size of the array.
• It is illegal to refer to an element outside of the array
bounds, and your program will crash or have unexpected
results, depending on the compiler.
• Array can only hold values of one type.

3
One Dimensional Array
• You declare an array by writing the type, followed by the
array name and the subscript.
• The subscript is the number of elements in the array,
surrounded by square brackets.
 For example, int age[25];
– declares an array of 25 integers, named age.
– When the compiler sees this declaration, it sets aside
enough memory to hold all 25 elements.
– Because each integer requires 2 bytes, this declaration
sets aside 50 contiguous bytes of memory. 4
Array Elements
More generally, SomeArray[n] has n elements that are numbered
SomeArray[0] through SomeArray[n-1].

#include<iostream.h>
int main()
{
int numbers[5] ={10,20,30,40,50}; //array declaration & initialization
int sum,average; //declaring variables that store sum and average of array
elements
sum = 0,average=0; //initializing sum & average to 0

cout<<numbers[3]<<endl;
for (int i = 0; i <5; i++)
{
sum += numbers[i];
average = sum / 5;
} //end of for loop
cout<<"The Sum of Array Elements="<<sum<<endl;
cout<<"The Average of Array Elements="<<average;
return 0;
5 }
Array Declaration
• Declaring the name and type of an array and setting the
number of elements in an array is called dimensioning the
array.
 The array must be declared before one uses in like other
variables.
• In the array declaration one must define:
1. The type of the array (i.e. integer, floating point, char etc.)
2. Name of the array,
3. The total number of memory locations to be allocated or the
maximum value of each subscript. i.e. the number of elements in the array.

6
Cont’d…
 So the general syntax for the declaration is:
DataType name arrayname [array size];
int Student_list[55];
• Note: array size cannot be a variable whose value is set
while the program is running.

7
Initializing Arrays

• After the array name, you put an equal sign (=) and a list of
comma-separated values enclosed in braces.
 For example, int IntegerArray[5] = { 10, 20, 30, 40, 50 };
– declares IntegerArray to be an array of five integers.
– It assigns IntegerArray[0] the value 10, IntegerArray[1]
the value 20, and so forth.

8
Cont’d…

C++ allows the possibility of leaving empty the


brackets [ ], where the number of items in the
initialization bracket will be counted to set the
size of the array.

int day [] = { 1, 2, 7, 4, 12,9 };

The compiler will count the number of


initialization items which is 6 and set the size
of the array day to 6 (i.e.: day[6])

int day [6] = { 1, 2, 7, 4, 12,9 };

9
Cont’d…
Accessing Arrays
• To access members of the array, use the subscript operator.
 Example:
• int theNinethInteger = MyIntegerArray[8];

10
One-Dimensional Arrays
A one-dimensional array is a list of related variables. The general
form of a one-dimensional array declaration is:
type variable_name[size]
 type: base type of the array, determines the data type of each element in the

array
 variable_name: the name of the array

 size: how many elements the array will hold

Examples:
float float_numbers[];
char last_name[40];
int sample[10]; 0 1 2 3 4 5 6 7 8 9
0 1 4 9 16 25 36 49 64 81
11
Example: Loading and accessing the array sample with the numbers 0 through
9
#include<iostream.h>
int main()
{
int sample[10]; // reserves for 10 integers
int t;
for(t=0; t<10; t++) // initialize the array
{
cout << t << ' '; // display the index
}
cout<<endl;
for(t=0; t<10; t++)
{
sample[t] = t*t;
// display the array
cout << sample[t] << ' ';
}
return 0;
12
}
Two-Dimensional Arrays
A two-dimensional array is a list of one-dimensional arrays.

To declare a two-dimensional integer array two_dim of size 3, 4 we


would write:

int test[3][4];
This corresponds to a table with 3 rows and 4 columns(for example).

13
We can generate the array above by using this program:

#include<iostream.h>
int main()
{

int test[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};

for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
{
cout<<"test["<<i<<"]["<<j<<"]="<<test[i][j]<<endl;
}
}
return 0;
}
14
Part II
String
Manipulations

15
Introduction
 String in C++ is a sequence of character in which the last

character is the null character ‘\0’. The null character indicates

the end of the string.

 Any array of character can be converted into string type in C+

+ by appending this special/null character ‘\0’ at the end of

the array sequence.

 Hence if a string has n characters then it requires an n+1

element array (at least) to store it. Thus the character `a' is

stored in a single byte, whereas the single-character string "a"

16is stored in two consecutive bytes holding the character `a'


….CONTN’D
A string variable Str1 could be declared as follows:
char Str1[10];
The string variable Str1 could hold strings of length up to
nine characters since space is needed for the final null
character. Strings can be initialized at the time of
declaration just as other variables are initialized.
For example: char str1 [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char str2[] = "Hello";
For example:
char Str1[] = "Hello!";
char Str2[18] = "C++ Programming";

Would store
H the
e above
l l two
O strings
! \0 as follows:

Str1 C + + P r o g r a m m i n g \0

17 Str2
String Output
A string is output by sending it to an
output stream, for example:
char str1=“Hello!”;
cout << "The string str1 is " << Str1 <<
endl; //would print “ The string Str1 is
Hello!”

The setw(width) I/O manipulator can be


used before outputting a string, the string
will then be output right-justified in the
field width.
18
String Input
 When the input stream cin is used space characters, n space, tab,
newline etc. are used as separators and terminators.

 To read a string with several words in it using cin we have to call cin.

 To read in a name in the form of first name followed by a last name

#include<iostream.h>
int main()
{
char firstname[12], lastname[12];
cout << "Enter First name and Last name: ";
cin >> firstname>> lastname;
cout << "The Name Entered was " << firstname << " " << lastname;

return 0;
}
19
Cont…

#include <iostream.h>
int main()
{
const int max=80;
char str[max];
cout<<"Enter a string.\n";
cin>>str;
cout<<"You entered : "<<str;
return 0;
20
}
….Continued

Reading strings with multiple lines.


//reads multiple lines, terminates on '$' character
#include<iostream.h>
int 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;
return 0;
}
Type as many lines of input & enter the terminated
character $ when you finish typing & press Enter.
21
String constants
You can initialize a string to a constant value
when you define it. Here's an example'
#include<iostream.h>
int main()
{
char str[] = "Welcome to C++ programming
language";
cout<<str;
return 0;
}

22
Copying string
The strings copy performed 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.

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).

23
….Continued
Example:

#include <iostream.h>
#include <string.h>
int main()
{
char me[20] = "David";
cout << me << endl;
strcpy(me, "Are You or Not?");
cout << me << endl ;
return 0;
24
}
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);
 The first character of the source string is copied to the
location of the terminating null character of the destination
string.
 The destination string must have enough space to hold
25 both strings and a terminating null character.
Example of string Concatenating
#include <iostream.h>
using namespace std;
int main()
{
string s1, s2, result;
cout << "Enter string s1:";
cin>> s1;
cout << "Enter string s2:";
cin>>s2;
result = s1 + s2;
strcat(s2, s1);
cout << "Resultant String = "<< result;
return 0;
}
26
Example of string
Concatenating-2
#include <iostream.h>
using namespace std;

int main() {
char s1[] = "Hello";
char s2[] = " World";

// Concatenating s1 and s2
strcat(s1, s2);

cout << s1;


return 0;
}
27
ou !
k Y
ha n
T ?

You might also like