0% found this document useful (0 votes)
3 views53 pages

Understanding Arrays in C++

Best notes

Uploaded by

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

Understanding Arrays in C++

Best notes

Uploaded by

kbromgebretensay
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Chapter Three

Arrays and structure


Arrays
 An array is a collection of elements of the same type placed in
contiguous memory locations.
 An array is a data structure which is used to store a
homogeneous(same) data type elements/ items.
 It allows you to store multiple values under a single name and
access them using an index.
 The index must be an integer and indicates the position of the
element in the array. Thus the elements of an array are ordered
by the index.
 In short: An array in C++ is a fixed-size, contiguous block of
memory that stores multiple values of the same type, and its size
must be known before the program runs.
Arrays
Suppose a class has 27 students, and we need to
store all their grades. Instead of creating 27
separate variables, we can simply create an array:
double grade[27];
Here, grade is an array that can hold a maximum
of 27 elements of double type.
In C++, the size and type of arrays cannot be
changed after its declaration.
Properties of Arrays
 An array is a collection of data of the same data type, stored at a
contiguous memory location.
 Indexing of an array starts from 0. It means the first element is
stored at the 0th index, the second at 1st, and so on.
 Elements of an array can be accessed using their indices.
 Once an array is declared its size remains constant throughout the
program.
 An array can have multiple dimensions.
 The size of the array in bytes can be determined by the sizeof
operator using which we can also find the number of elements in
the array.
 We can find the size of the type of elements stored in an array by
subtracting adjacent addresses.
Types of Array
 One Dimensional Array
 Multi Dimensional Array
One Dimensional Array
 Declaration of Arrays
 Accessing Array Elements
 Initialization of arrays
 Copying Arrays
One Dimensional Array
 an array in which the components are arranged in a list form
 The general form of declaring a one-dimensional array is:
data_type array_name [size];
 Example:
int numbers[5]; // numbers is an array of 5 int values
 Here, The value inside the square bracket [5] tells the compiler how many
elements the array will contain.
 In this case, the array can store 5 consecutive integer values in memory.
 When the compiler sees this declaration, it reserves memory
for 5 integers next to each other.
 The diagram below shows how the elements
are represented in memory for the array int
numbers[5]:

 Each element in the array is stored in


consecutive memory locations, meaning they
Accessing 1-d array elements
 An array element is accessed by writing the name of
the array followed by the subscript in square brackets.
 The first element in an array in C++ always has the
index 0, and if the array has n elements the last
element will have the
index n-1.
 The general form (syntax) of accessing an array
component is:
array_name[index];
 So to access each elements in the array int numbers[5];
numbers[0]; ------- to access the first element.
numbers[1]; ------- to access the second element.
numbers[2]; ------- to access the third element.
numbers[3]; ------- to access the fourth element.
numbers[4]; ------- to access the fifth element
One Dimensional Array
Initialization of array elements(cont)
 Initialization during declaration:
You can assign values when declaring the array:
Example: int numbers[5] = {23, 45, 22, 4,
65};
If fewer values are given, the remaining
elements become 0
Example: int numbers[5] = {23, 45, 22};
When initializing arrays while declaring them
Not necessary to specify the size of the array
Example: int numbers[] = {23, 45, 22, 4, 65};
Here, The compiler sets the size based on the
number of elements.
One Dimensional Array
Initialization of array elements(cont)
 You can initialize array elements by taking input from
the user using cin: e.g. To set the second element by
taking value from the user:
cin >> numbers[1];
 Initialization Using a Loop
 Instead of assigning values to each element of an array
one by one, you can use a loop to insert all elements
efficiently. For example, if you have an array of 5 integers:
Example:
int numbers[5];
for (int i = 0; i < 5; i++) {
cin >> numbers[i]; // Read a value from the
user and store it in numbers[i]
}
One Dimensional Array
Displaying array elements
 A value of the array element can be displayed
like this
cout<<numbers[4];
 You can also display all the 5 elements of the
array by using loop like this
for (int i=0 ; i<5; i++)
cout<<numbers[i];
One Dimensional Array
Copying arrays
 The assignment operator cannot be applied to
array variables:
int SIZE = 10
int array1 [SIZE ] ;
int array2 [SIZE ] ;
array1 = array2 ; // Error
 You have to use the indexes to copy one
element of array to other element of array like
this:
array1 [2] = array2 [3];
 To make all elements of array1 to hold the
elements of array2, you should have to use
loop like this:
for (int i = 0 ; i < 10; i++)
Example
//To get the sum of the 5 elements of the
array numbers
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
int numbers[] = {23, 45, 22, 4, 65};

for (int i = 0; i < 5; i++)


{
sum = sum + numbers[i];
}

cout << "The sum is: " << sum << endl;

return 0;
Multidimensional Array
 An array may have more than one dimension.
Each dimension is represented as a subscript
in the array.
 A two dimensional array have two subscripts
A three dimensional array has three
subscripts, and so on.
 General syntax of declaring an n-
dimensional array is:
datatype array_name[size1][size2]...[sizeN];
where size1, size2, … are constant
expressions yielding positive integer values
Two Dimensional Array
 Declaration of Arrays
 Accessing Array Elements
 Initialization of arrays
 Copying Arrays
Two Dimensional Array
 Two-dimensional Array: a
collection of a fixed number of
components arranged in two
dimensions.
 All components are of the same type
 The syntax for declaring a
two-dimensional array is:
data_type array_name [rows]
[columns];
 Two-dimensional arrays are
Two Dimensional Array
Two Dimensional Array
Accessing array elements

The syntax to access a component of a two-


dimensional array is:
array_name[rows][columns];
where rows and columns are expressions
yielding nonnegative integer values
Two Dimensional Array
Initialization of array elements(cont)
 Like one-dimensional arrays
Two-dimensional arrays can be initialized
when they are declared
 To initialize a two-dimensional array when it is
declared
1. Elements of each row are enclosed within
braces and separated by commas
2. All rows are enclosed within braces
3. For number arrays, if all components of a row
are not specified, the unspecified
components are initialized to zero
Two Dimensional Array
Initialization of array elements(cont)

Example:
 Initialization of two-dimensional array
int test[2][3] = { {2, 4, 5}, {9, 0, 19}};
Two Dimensional Array
Initialization of array elements(cont)
 A value can be read into an array element
directly, using cin
cin >> numbers[1][0];
 You can also insert all the 6 elements of the
array by using loop like this. Let our array is
numbers[3][2];
for (int i=0 ; i<3; i++){
for(int j=0 ;j<2; j++){
cin>>numbers[i][j];}}
Two Dimensional Array
Display array elements
 A value of the array element can be displayed
like this
cout<<numbers[0][1];
 You can also display all the 6 elements of the
above array by using loop like this
for (int i=0 ; i<3; i++){
for(int j=0 ;j<2; j++){
cout<<numbers[i][j];}}
Two Dimensional Array
Copying arrays
 The assignment operator cannot be applied to
array variables:
const int ROWSIZE = 4
const int COLSIZE = 5
int array1 [ROWSIZE ] [COLSIZE ];
int array2 [ROWSIZE ] [COLSIZE ];
array1 = array1 ; // Error – Illegal
 You have to use the indexes to copy one element
of array to other element of array like this:
array1 [2] [3]= array2 [3][1];
 To make all elements of array1 to hold the
elements of array2, you should have to use loop
like this:
for (int i = 0 ; i < 4; i++)
for (int i = 0 ; i < 4; i++)
Example
#include <iostream>
using namespace std;
int main() {
int A[3][2] = { {23, 45}, {22, 4}, {65, 76} };
int B[2][3]; // Transpose will be 2x3

// Transpose
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
B[j][i] = A[i][j];
}
}
// Display Transposed Matrix
cout << "Transpose of A is:\n";
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << B[i][j] << " ";
}
cout << endl;
}

return 0;
}
Strings

String Representation and


Manipulation
Strings
The Standard C++ Library
String Class
 The string class in C++ is a part of the

Standard Library (<string>).


 It is used to store and manipulate sequences of

characters safely and efficiently.


 Unlike C-style character arrays, it automatically

manages memory, allows easy concatenation,


comparison, and provides many built-in
functions for common string operations.
 In short, A string is a dynamic, convenient way

to work with text in C++.


The Standard C++ Library
String Class
 Declaration of Strings

string str;
 Initialization of Strings

string str1 = "Hello";


C-style string
 A fixed-size array of characters ending with a null
character \0.
 Based on arrays of characters ending with a null character
('\0').
 To declare a C-style string:
char variable_name[size];
 variable_name is the name of the character array.
 size specifies the number of characters the array can hold
(including the null character '\0’).
 Example:
char Greeting[10];
 Greeting can hold up to 9 characters plus the null character.
 Memory is allocated automatically for 10 characters.
 Initially, the array may contain garbage values until assigned.
 So if you have a string with n characters, then you need
to have at least n+1 sized array to hold the string as well
as the null character.
String Initialization
char Greeting[6] = "Hello";
 "Hello" is automatically null-terminated (\0).
 Always ensure the array is large enough to hold
the string and the null character.
String Initialization
 You can initialize your string one character at a
time like this:
char myString[10];
myString[0] = ‘H‘;
myString[1] = ‘i‘;
myString[2] =H ‘ ‘;i C o m p s ! \0

myString[3] = ‘C‘;
myString[4] = ‘o‘;
myString[5] = ‘m‘;
myString[6] = ‘p‘;
myString[7] = ‘s‘;
myString[8] = ‘!‘;
String Initialization(cont)
 You can also initialize and declare strings
at the same time like this:
char Color[] = { 'B', 'l', 'a', 'c', 'k' };
char Country[] = “Ethiopia";
myString[10] = “Hi Comps!”;
myString[] = “Hi Comps!”;
 Note that the length of a string does not
include the terminating null character.
String Initialization(cont)
 You can also initialize strings by taking
input from the user :
cin>>myString[0];
 To take input from the user at a time you
can use loops like for loop:
for (int i; i<10; i++)
{
cin>>myString[i];
}
String Initialization(cont)
 You can also initialize strings by taking
input from the user:
cin>>myString; //only read string with a
single word
 But if u have a space character in between your
string, this won’t take characters after the
space character because it assumes that it gets
the null character which is the end of the string.
For eg if we insert “Hi Comps!”, the string
myString will only read “Hi” because there is a
space between “Hi” and “Comps!”.
String Initialization(cont)
 So to read strings with blanks/spaces from the
user, we use the function [Link]() in place of
cin>>:
 [Link](StringName, Size);
Eg. [Link](myString, 10);// reads strings with space
 But if your string is more than one line,
this won’t read strings more than a
single line because the function has a
default third argument which have the
value new line(“\n”) character. So when
it gets the new line the function will be
unable to read more strings.
String Initialization(cont)
 So to read strings more than one line from the user,
we use the function [Link]() in place of
[Link]():
 [Link](StringName, Size,
TerminatorCharacter);
Here the TerminatorCharacter is used to stop reading
lines.
So in order to specify the ending point of reading multiple
line, we are expected to set a character as a third
argument.
Eg. char myString[120];
[Link](myString, 120, ‘$’);
 The compiler will read multiple lines until it get the
dollar sign (“$”) or until the strings exceeds the size.
character
 For a string, if you want to declare a two-
dimension array of characters, the first
dimension specifies the number The second
dimension specifies the number of characters
that each string can hold. Here is an example:
char StudentName[4][10] = { “Abebe", “Kebede",
“Abebech", “Kebedech" };
cout << "Student Names";
cout << "\nStudent 1: " << StudentName[0];
cout << "\nStudent 2: " << StudentName[1];
cout << "\nStudent 3: " << StudentName[2];
cout << "\nStudent 4: " << StudentName[3];
Avoiding buffer over flow
 There is no built-in mechanism in C++ to keep a
program from inserting array elements outside an
array.
 If you insert characters greater than the string
size, then your string length will increase as per
the number of the characters.
 So we have to use the function setw() by putting
a prototype header #include<iomanip.h>
 Eg. cin>>setw(size)>>stringName;
Copying string
 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 header. So you should
have to put the header #include<string.h>
 strcpy(destinationString, sourceString);
 strcpy copies characters from the location
specified by sourceString to the location
specified by destinationString. It stops copying
characters after it copies the terminating null
character.
Copying Strings (cont)
 The return value is the value of the destinationString
parameter.
 Eg. char S1[20] = “Abebe";
cout << S1 << endl;//output will be Abebe
strcpy(S1, "YouAreNotMe");
cout << S1 << endl ;// output will be
YouAreNotMe
 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).
String copy(cont)
 There is also another function strncpy, is like
strcpy, except that it copies only a specified
number of characters.
 strncpy(destination, source, int n);
 It may not copy the terminating null
character.
strncpy()
[Link] CarName1[] = “Volse Wagen“;
char CarName2[] = "Toyota 4-Runner“;
cout << "The String Copy Operation“;
cout << "\nFirst Car: " << CarName1;//output–VolseWagen
cout << "\nSecond Car: " << CarName2; // output-Toyota 4
Runner
strncpy(CarName2, CarName1, 8);
cout << "\n\nAfter using strncpy() for 8 characters“;
cout << "\nFirst Car: " << CarName1;//output – Volse Wag
cout <<"\nSecond Car: “<< CarName2;//output-Volse Wa-
Runner
Concatenating strings
 You have to use 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 both strings and a terminating null character.
Concatenating strings(cont)
Eg.
char car1[30]= "Ford“;
Char car2[] = “Mercedes Benz“;
cout << "Originally, car1 = " << car1;//output-Ford
strcat(car1, car2);
cout << "\n After concatenating, car1= " << car1<<
endl;//output- FordMercedes Benz
Strncat()
 The function strncat is like strcat except that it
copies only a specified number of characters.
 strncat(destination, source, int n);
 It may not copy the terminating null character.
strncat() (cont)
Eg.
char car1[30]= "Ford“;
Char car2[] = “Mercedes Benz“;
cout <<"Originally, car1 = " << car1;//output-Ford
strncat(car1, car2,4);
cout <<"\n After concatenating, car1= " << car1<<
endl;//output-FordMerc
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
strcmp()
The result of comparing Andy and
Eg. Charles is -2
char FirstName1[] = "Andy“;
The result of comparing Charles and
char FirstName2[] = "Charles";
Andy is 2
char LastName1[] = "Stanley";
The result of comparing Stanley and
char LastName2[] = "Stanley";
Stanley is 0

int Value1 = strcmp(FirstName1, FirstName2);


int Value2 = strcmp(FirstName2, FirstName1);
int Value3 = strcmp(LastName1, LastName2);
cout << "The result of comparing " << FirstName1
<< " and " << FirstName2 << " is\t" << Value1 << endl;
cout << "The result of comparing " << FirstName2 << "
and " << FirstName1 << " is\t" << Value2 << endl;
cout << "The result of comparing " << LastName1 << "
and " << LastName2 << " is\t" << Value3;
Length of Strings
 To find the number of characters of a string, use
the strlen() function. Its syntax is:
 The strlen() function takes one argument, which is
the string you are considering. The function returns
the number of characters of the string.
Eg.
char Campus[] = “Main Campus“;
int Length = strlen(Campus);
cout << "The length of “<< Campus<< “ is :" <<
Length << " characters";
String Duplication
 The strdup() function is used to make a copy of
create a duplicate of that string. Its syntax is:
 char
NewStr=strdup(NameOfStringToBeDuplicated);
 Or char NewStr;
NewStr =
strdup(NameOfStringToBeDuplicated);
 This function takes as an argument the string you
want to duplication and returns the duplicated
string.
Strdup()
Eg.
char FirstName1[] = “Demilew";
char FirstName2[] = “Deribe";
char LastName1[] = “Adefris";
char LastName2[];
LastName2 = strdup(LastName1);
cout << "Father: " << FirstName1 << ' '
<<LastName1 << endl; //output- Demilew
Adefris
cout << “Son : " << FirstName2 << ' ' <<
LastName2;//output – Deribe Adefris
Converting a string into
Lowercase & Upercase
 The strlwr() function is used to convert a string to
lowercase. Its syntax is: strlwr(StringName);
[Link] s1[]= “Beletu is Ethiopian”;
cout<<strlwr(s1);//OP will be beletu is ethiopian
 This function takes, as argument, the string that
needs to be converted. During conversion, if a Latin
character were in uppercase, it would be converted
to lowercase. Otherwise, it would stay “as if”. This
means any symbol that is not a readable character
would not be converted like numbers and special
characters.
Converting a string into Upercase
 The strupr() function is used to convert a string to
uppercase. Its syntax is: strupr(StringName);
 [Link] s1[]= “Beletu is Ethiopian”;
cout<<strlwr(s1);//OP will be BELETU IS
ETHIOPIAN
 Each lowercase character in the function’s
argument, StringName, would be converted to
uppercase. Any character or symbol that is not in
lowercase would not be changed.

You might also like