Chapter 5 - Array, Pointers and String
Chapter 5 - Array, Pointers and String
Chapter 5 - Array, Pointers and String
Manipulations
COMPUTER PROGRAMMING
Section 1: Array in C++
Array in C++
The variables we’ve used so far can store a single value. In this
section, we’ll discuss a new type of variable capable of storing a
number of values.
Problem:
Need some way to hold all the individual data items after processing
them
Homogeneous
Contiguous (Adjacent)
Have random access to any element
Ordered (numbered from 0 to n-1)
Number of elements does not change - MUST be a constant when
declared
int x[6];
1. One Dimensional Here,
data_type array_name[number_of_elements];
The number_of_elements, or else the length/size of
the array, is specified by a positive integer constant
When declaring an array, the compiler allocates a
expression enclosed in brackets. All the elements are
memory block to store the values of its elements.
of the same type; it may be of any type (e.g., int,
float, char, …).
These values are stored one after another in
consecutive memory locations.
For example, the statement: int arr[1000]; declares
the array arr with 1000 elements of type int.
Typically, this memory block is allocated in a region
called stack and it is automatically released when the
To realize the importance of arrays, imagine that if
function that declares the array terminates.
C++ did not support this type of aggregate variable,
we’d have to declare 1000 different integer
variables.
Declaring Arrays
Multiple arrays of the same type can be declared in a single
declaration
Use a comma-separated list of names and sizes
The C++ standard does not allow the size to be specified at runtime. As
said, it must be a constant expression known at compile time. However,
there are C++ compilers that allow the programmer to use a variable for
the declaration. Thus, don’t be surprised if the compiler you are using
compiles the left-side code with dynamic array size.
Exercises
If we assume that the memory address of the first element is at position 100,
the value of the first element is stored in positions 100-103, the value of the
second element in positions 104-107, and the value of the third one in
positions 108-111.
To find the size of the allocated memory, we can use the sizeof operator. For
example, the value of sizeof(arr) is 12.
Fig.7.1 | Array of 12 elements
The index specifies the position of the element within the array, and it must
be an integer constant, variable, or expression.
In an array of n elements, the first one is stored in position [0], the second
one in position [1], and the last one in [n-1].
Array
Index
Position number used to refer to a specific location/element
Also called subscript
Place in square brackets [ ]
Must be positive integer or integer expression
First element has index zero, last element has index n-1
A popular error of novice programmers is to forget that index numbering starts from
zero. Remember, in an array of n elements, the first element is stored in position zero,
not one, and the last one in position n-1, not n.
Example: Program that accepts 5
integers from user
#include <iostream>
int main()
{
int i, arr[5];
for(i = 0; i < 5; i++)
{
std::cout << "Enter number: ";
std::cin >> arr[i];
}
for(i = 4; i >= 0; i--)
std::cout << arr[i] << '\n';
return 0;
}
Example 2: Accept list of marks and prints
all marks greater than average mark
#include<iostream> average = total / 5;
using namespace std; int ct = 0;
Int main() while (ct < 5)
{ {
int counter = 0,total = 0; if (n[ct] > average)
Int n[5]; cout << n[ct];
float average; ct = ct + 1;
while (counter < 5) }
{ }
cout << "enter a number ";
cin >> n[counter];
total = total + n[counter];
counter = counter + 1;
}
Initializing Array
int a[3][4];
int arr[3][3] =
{
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
Alternatively, we can omit the inner braces and write:
int arr[3][3] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
Once the compiler fills one row, it continues with the next one. However, the
preferred way is always to use the inner braces so that the initialization of each
row is clearly shown.
Legal initializations or not?
Answer: ________________
int arr[3][3] =
{ int arr[3][3] = {{10, 20, 30}};
{10, 20},
{40, 50},
{70}
};
Example
the outer for loop iterates over the rows, while the inner one iterates over the columns of the 2D array,
So, for each iteration of the outer loop, i increases and takes us to the next 1D array. Also, the inner loop
traverses over the whole 1D array at a time,
And accordingly, we print the individual element arr[ i ][ j ].
Create and add two matrices
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
m3[i][j]=m1[i][j]+m2[i][j];
}
}
Declaring Multidimensional Arrays 31
may not run in your computer, unless the available stack size is large
enough to hold the values.
Syntax :
dataType *identifier; //To declare a variable
In the general case, if the type is T, the type of T* is “pointer to T”.
z some double
double *z;
int x;//variable x
int *p;//pointer p
p
x = 123;
p = &x;
Address of Operator (&)
...
...
Must be initialized, cannot be changed
Dereferencing operator(*)
A pointer must have a value before you can dereference it (follow the
pointer).
int *p; int x;
*p=3; int *p =&x;
*p=3;
this is fine
p points to x
Location and Value Comparisons
cout << *array; is like cout << array[0]; ptr + 1 is equivalent to &arr[1];
ptr + 2 is equivalent to &arr[2];
ptr + 3 is equivalent to &arr[3];
ptr + 4 is equivalent to &arr[4];
…Pointers and Arrays
The close relationship between pointers and arrays is
based on the fact that the name of an array can be
used as a pointer to its first element.
int *p;
int a[10];
p = &a[2]; //p is “the address of a[2] ”
for (int i=0; i<3; i++)
p[i]++; //p[i] is the same as a[i+2]
Exercise: What will be the output
for the following program
#include <iostream>
int main()
{
int i, *ptr1, *ptr2, arr[] = {10, 20, 30, 40, 50, 60, 70};
int a[5];
Section 3: Character and String
Manipulation
STRINGS
CTYPE Built in Functions for Characters
Character Macro Description
isalpha Returns true (a nonzero number) if the argument is a letter of the alphabet.
Returns 0 if the argument is not a letter.
isalnum Returns true (a nonzero number) if the argument is a letter of the alphabet or a
digit. Otherwise it returns 0.
isdigit Returns true (a nonzero number) if the argument is a digit 0–9. Otherwise it
returns 0.
islower Returns true (a nonzero number) if the argument is a lowercase letter.
Otherwise, it returns 0.
isprint Returns true (a nonzero number) if the argument is a printable character
(including a space). Returns 0 otherwise.
ispunct Returns true (a nonzero number) if the argument is a printable character other
than a digit, letter, or space. Returns 0 otherwise.
isupper Returns true (a nonzero number) if the argument is an uppercase letter.
Otherwise, it returns 0.
isspace Returns true (a nonzero number) if the argument is a whitespace character.
Whitespace characters are any of the following:
Example
if (isalpha(input))
#include <iostream>
cout << "That's an alphabetic character.\n";
int main() if (isdigit(input))
cout << "That's a numeric digit.\n";
{
if (islower(input))
char input; cout << "The letter you entered is
lowercase.\n";
cout << "Enter any character: "; if (isupper(input))
cout << "The letter you entered is
cin>>input; uppercase.\n";
if (isspace(input))
cout << "The character you entered
cout << "That's a whitespace character.\n";
is: " << input << endl;
return 0;
cout << "Its ASCII code is: " << }
For example, if the compiler encounters the string literal "text", it allocates five
bytes to store the four characters of the string plus one for the null character. A
string literal may be empty. For example, the string literal "" is stored as a single
null character.
String
1. String Literals:
“Hello World”
“xyz 123 *&^#$!”
2. C-Style strings:
char s[20];
C-Style Strings 59
The first is the null character with ASCII code 0,
while the second is the zero character with
ASCII code 48.
A C-style string is stored in an array of char; To store a C-style string in a variable, we use
C-style strings should always end in ‘\0’; an array of characters.
cout << "String = " << s << endl; An array can be initialized with a string,
when it is declared. For example, with the
declaration:
char str[5] = "text";
Internal Storage of C++ Strings
std::cout << "My name is: " << name << '\n';
A flexible way to initialize the array is to omit its length and
let the compiler compute it.
As with an ordinary array, if the number of the characters is less than the size of the
array, the remaining elements are initialized to 0. If it is greater, the compilation fails.
str[1] becomes 'e' and the rest elements are initialized to 0, or equivalently to '\0'.
All str elements are initialized to '\0'. When declaring an array of characters to store a C-style
string, don’t forget to reserve an extra place for the null
character.
Exercise
Or
string lastname = “Marx”;
String Operators: Assignment 66
anothername = lastName;
string firstName(“Abebe”);
string lastName(“Kebede”);
string fullname = firstName + lastname;
Library Functions Working with
Strings
The C++ library has numerous functions for handling C-strings .
These functions perform various tests and manipulations.
strcpy(a,b); strncpy(a,b,3);
cout<<a; // Code cout<<a; //Codgraming is fun
USING #include<cstring>
converts string to
strlwr()
lowercase
converts string to
strupr()
uppercase
#include <iostream>
#include <cstring>
using namespace std;
strcpy() copies the string pointed to by src into
int main() {
the memory pointed to by dest. Once the null
char str1[] = "String test"; character is copied, strcpy() terminates and
char str2[] = "Hello"; returns the dest pointer.
char one[10];
Since src is declared as const, strcpy() cannot
strncpy(one, str1, 9); modify the string.
one[9] = '\0';
If the source and destination strings overlap the
behaviour of strcpy() and strncpy() is undefined.
cout<< one <<endl;
strncpy(one, str2, 2);
cout << one << endl;
strcpy(one, str2);
cout << one << endl;
}
char source[ ]{ "Copy this!" };
String Copy char dest[5]; // note that the length of dest is only 5 chars!
strcpy(dest, source);
Because strcpy() does not check if the string pointed to by src fits into the memory
pointed to by dest, it is the programmer’s responsibility to ensure that the destination
memory is large enough to hold all characters.
Otherwise, the memory past the end of the dest will be overwritten causing the
unpredictable behaviour of the program.
Since strncpy() specifies the maximum number of the copied characters it is safer than
strcpy().
String Compare
#include <iostream>
#include <cstring>
using namespace std;
int 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;
return 0;
}
Exercise
if(k == 0)
cout << "Same texts\n";
else
{
int main() cout << "Different texts\n";
{
if(strncmp(str1, str2, 3) == 0)
char str1[100], str2[100];
int k; cout << "But the first 3 chars are the same\n";
cout << "Enter first text: ";
cin.getline(str1, sizeof(str1)); }
return 0;
cout << "Enter second text: ";
}
cin.getline(str2, sizeof(str2));
k = strcmp(str1, str2);
/* We could omit the declaration of k and write: if(strcmp(str1, str2) == 0) */
CTYPE String or String Class?
In rare case that you do need to work with fixed buffer sizes C-style
strings (e.g. for memory-limited devices) would be recommended
than well-tested 3rd party string library.
Comparison
if (index != -1) {
cout << "The character 'l' is found at index " << index <<
endl; }
String Input
When the input stream cin is used space characters, newline , tab,
etc. are used as separators and terminators.
skips over any leading spaces
terminates reading a value when it finds a white-space character
char name[20];
cout<<“enter your name”;
cin>>name;
cout << "Enter your name: ";
Input: My name is Abebe cin.get(p1.name, 50); // for CTYPE
Output: My
getline(cin, str); // for string class
Example
#include<iostream>
using namespace std;
int main()
{
string fullname;
cout<<"Enter your full name";
//cin>>fullname; // Accepts input until the first space
//cin.get(fullname, 30); // works for 30 characters input (CTYPE)
getline(cin, fullname); // string class based approach
cout<<"Hi, "<<fullname;
}
String Input …
#include <iostream>
using namespace std;
int main()
{
char line[80];
int count = 0;
Write a program that reads a string and stores it in a string object. Then, the
program should display a message to indicate if it is a palindrome or not,
that is, if it can be read the same in either direction. For example, the string
level is a palindrome, since it is read the same in both directions.
Comments: The loop compares the characters from the first character up to
the middle one with the characters from the last one back to the middle.
That’s why the loop is executed from 0 up to len/2. The last character is
stored in str[len-1].
End of Chapter 5