Arrays Pointers and String
Arrays Pointers and String
1
Chapter Two
2. Arrays and Strings
2.1. Introduction
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. In none of the programs written so far
have very many variables been used to represent the values that were required. Thus even though programs
have been written that could handle large lists of numbers it has not been necessary to use a separate identifier
for each number in the list. This is because in all these programs it has never been necessary to keep a note of
each number individually for later processing. For example in summing the numbers in a list only one variable
was used to hold the current entered number which was added to the accumulated sum and was then overwritten
by the next number entered. If that value were required again later in the program there would be no way of
accessing it because the value has now been overwritten by the later input.
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:
sum = 0.0;
for (i = 0; i < 6; i++)
{
cin >> x;
sum += x;
}
This of course is easily extended to n values where n can be as large as required. However if it was required to
access the values later the above would not be suitable. It would be possible to do it as follows by setting up six
individual variables:
float a, b, c, d, e, f;
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? To extend this solution so that it would work with more
than six values then more declarations would have to be added, extra assignment statements added and the
2
program re-compiled. If there were 10000 values imagine the tedium of typing the program (and making up
variable names and remembering which is which)!
To get round this difficulty all high-level programming languages use the concept of a data structure called an
Array.
An array can be thought of as a collection of numbered boxes each containing one data item. The number
associated with the box is the index of the item. To access a particular item the index of the box associated with
the item is used to access the appropriate box. 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.
For 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];
This declaration will cause the compiler to allocate space for 100 consecutive float variables in memory. The
number of elements in an array must be fixed at compile time. 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,
3
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.
An array element is accessed by writing the identifier of the array followed by the subscript in square brackets.
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. Hence in the above the 15th
element has index 14.
An array element can be used anywhere an identifier may be used. Here are some examples assuming the
following declarations:
count[i] = count[i] + 5;
count[i] += 5;
Array elements can form part of the condition for an if statement, or indeed, for any other logical expression:
for statements are the usual means of accessing every element in an array. Here, the first NE elements of the
array annual_temp are given values from the input stream cin.
Notice that it is good practice to use named constants, rather than literal numbers such as 10. If the program is
changed to take the average of the first 20 entries, then it all too easy to forget to change a 10 to 20. If a const is
used consistently, then changing its value will be all that is necessary.
4
For example, the following example finds the average of the last k entries in the array. K could either be a
variable, or a declared constant. Observe that a change in the value of k will still calculate the correct average
(provided k<=NE).
sum = 0.0;
for (i = NE – k; i < NE; i++)
sum += annual_temp[i];
av2 = sum / k;
Important – C++ does not check that the subscript that is used to reference an array element actually lies in the
subscript range of the array. Thus C++ will allow the assignment of a value to annual_temp[200], however the
effect of this assignment is unpredictable. For example it could lead to the program attempting to assign a value
to a memory element that is outside the program’s allocated memory space. This would lead to the program
being terminated by the operating system. Alternatively it might actually access a memory location that is
within the allocated memory space of the program and assign a value to that location, changing the value of the
variable in your program which is actually associated with that memory location, or overwriting the machine
code of your program. Similarly reading a value from annual_temp[200] might access a value that has not
been set by the program or might be the value of another variable. It is the programmer’s responsibility to
ensure that if an array is declared with n elements then no attempt is made to reference any element with a
subscript outside the range 0 to n-1. Using an index, or subscript, that is out of range is called Subscript
Overflow. Subscript overflow is one of the commonest causes of erroneous results and can frequently cause
very strange and hard to spot errors in programs.
Note that the array has not been given a size, the compiler will make it large enough to hold the number of
elements in the list. In this case primes would be allocated space for seven elements. 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:
would reserve space for a ten element array but would only initialize the first five elements.
5
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.
Since the data values are all positive a negative value can be used as a sentinel to signal the end of data entry.
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. Hence the use of an array to store the entered
values for later re-use.
In the above the variable nogt10 is the number greater than 10% above the average value. It is easy to argue that
after exiting the while loop, count is set to the number of positive numbers entered. Before entering the loop
count is set to zero and the first number is entered, that is count is one less than the number of numbers entered.
Each time round the loop another number is entered and count is incremented hence count remains one less than
the number of numbers entered. But the number of numbers entered is one greater than the number of positive
numbers so count is therefore equal to the number of positive numbers.
A main() program written from the above algorithmic description is given below:
void main()
{
const int NE = 200; // maximum no of elements in array
float sum = 0.0; // accumulates sum
int count = 0; // number of elements entered
int nogt10 = 0; // counts no greater than 10%
// above average
float x; // holds each no as input
float indata[NE]; // array to hold input
6
float average; // average value of input values
int i; // control variable
// calculate average
average = sum/count;
// Output results
cout << “Number of values input is “ << n;
cout << endl
<< “Number more than 10% above average is “
<< nogt10 << endl;
}
Since it was assumed in the specification that there would be less than 200 values the array size is set at 200. In
running the program less than 200 elements may be entered, if n elements where n < 200 elements are entered
then they will occupy the first n places in the array indata. It is common to set an array size to a value that is
the maximum we think will occur in practice, though often not all this space will be used.
The following program simulates the throwing of a dice by using a random number generator to generate
integers in the range 0 to 5. The user is asked to enter the number of trials and the program outputs how many
times each possible number occurred.
An array has been used to hold the six counts. This allows the program to increment the correct count using one
statement inside the loop rather than using a switch statement with six cases to choose between variables if
separate variables had been used for each count. Also it is easy to change the number of sides on the dice by
changing a constant. Because C++ arrays start at subscript 0 the count for an i occurring on a throw is held in
the i-1th element of this count array. By changing the value of the constant die_sides the program could be used
to simulate a die_sides-sided die without any further change.
#include <iostream.h>
7
#include <stdlib.h> // time.h and stdlib.h required for
#include <time.h> // random number generation
void main()
{
const int die_sides = 6; // maxr-sided die
int count[die_sides]; // holds count of each
// possible value
int no_trials, // number of trials
roll, // random integer
i; // control variable
float sample; // random fraction 0 .. 1
This code will copy the elements of array y into x, overwriting the original contents of x. A loop like this has to
be written whenever an array assignment is needed.
8
Notice the use of a constant to store the array size. This avoids the literal constant ‘10’ appearing a number
times in the code. If the code needs to be edited to use different sized arrays, only the constant needs to be
changed. If the constant is not used, all the ‘10’s would have to be changed individually – it is easy to miss one
out.
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.
Suppose the program contains a class named square. The declaration of array named board that represents
would be
Square board[8][8];
The program could also represent the same data with a one dimensional, 64-square array. For example, it could
include the statement
Square board[64];
Such a representation does not correspond as closely to the real-world object as the two dimensional array,
however.
Suppose that when the game begins. The king id located in the fourth position in the first row. Counting from
zero that position corresponds to board[0][3] in the two dimensional array, assuming that the first subscript
corresponds to the row, and the second to the column.
9
Int theArray[5][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12},
{13, 14,15} };
The compiler ignores the inner braces, which clarify how the numbers are distributed.
Each value should be separated by comma, regardless of whither inner braces are include. The entire
initialization must set must appear within braces, and it must end with a semicolon.
int x[] = { 1, 2, 3, 4} ;
This initialization creates an array of four elements.
Note however:
int x[][] = { {1,2}, {3,4} } ; // error is not allowed.
And must be written
int x[2][2] = { {1,2}, {3,4} } ;
In C++ strings of characters are held as an array of characters, one character held in each array element. In
addition a special null character, represented by `\0’, is appended to the end of the string to indicate the end of
the string. 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” is stored in two consecutive bytes
holding the character `a’ and the null character.
10
A string variable s1 could be declared as follows:
char s1[10];
The string variable s1 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:
11
Note that the last two elements are a relic of the initialization at declaration time. If the string that is entered is
longer than the space available for it in the character array then C++ will just write over whatever space comes
next in memory. This can cause some very strange errors when some of your other variables reside in that
space!
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 Christian name followed by a surname we might use code as follows:
Thus it will read strings consisting of a single word, but anything typed after a space is thrown away.
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 the next example, we call the function with a dollar sign (‘$’) as the third argument
//reads multiple lines, terminates on ‘$’ character
#include<iostream.h>
void main(){
12
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; }
now you can type as many lines of input as you want. The function will continue to accept characters until you
enter the terminated character $ (or ntil you exceed the size of the array. Remember, you must still press Enter
key after typing the ‘$’ character .
However, it is possible to tell the >> operator to limit the number of characters it places in an array.
#include<iostream.h>
void main(){
char str[] = “Welcome to C++ programming language”;
cout<<str;
}
if you tried to the string program with strings that contain more than one word , you may have unpleasant
surprise. 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()
void main()
{
const int max=80;
char str1[]=’’ Oh, Captain, my Captain!”
our fearful trip is done”;
char str2[max];
13
for(int i=0; i<strlen(str1);i++)
str2[i]=str1[1];
str2[i]=’\0’;
cout<<endl;
cout<<str2;
}
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.
Example:
#include <iostream.h>
#include <string.h>
void main(){
char me[20] = “David”;
cout << me << endl;
strcpy(me, “YouAreNotMe”);
cout << me << endl ;
return;
}
There is also another function strncpy, is like strcpy, except that it copies only a specified number of
characters.
Strncpy(destination, source, int n) ;
14
}
The function strcat concatenates (appends) one string to the end of another string.
Strcat(destination, source);
o The first character of the source string is copied to the location of the terminating null character of the
destination string.
o The destination string must have enough space to hold both strings and a terminating null character.
Example:
#include <iostream.h>
#include <string.h>
void main() {
char str1[30];
strcpy(str1, “abc”);
cout << str1 << endl;
strcat(str1, “def”);
cout << str1 << endl;
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.
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;
}
15
2.5.7. 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;
}
The function strncmp is like strcmp except that it compares only a specified number of characters.
Strncmp(str1, str2, int n);
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;
}
3. Pointers
A pointer is simply the address of a memory location and provides an indirect way of accessing data in
memory. A pointer variable is defined to ‘point to’ data of a specific type. For example:
int num;
we can write:
ptr1 = #
The symbol & is the address operator; it takes a variable as argument and returns the memory address of that
variable. The effect of the above assignment is that the address of num is assigned to ptr1. Therefore, we say
that ptr1 points to num. Figure 5.Error! Bookmark not defined. illustrates this diagrammatically.
16
ptr1 num
Figure: A simple integer pointer.
Given that ptr1 points to num, the expression
*ptr1
dereferences ptr1 to get to what it points to, and is therefore equivalent to num. The symbol * is the dereference
operator; it takes a pointer as argument and returns the contents of the location to which it points.
In general, the type of a pointer must match the type of the data it is set to point to. A pointer of type void*,
however, will match any type. This is useful for defining pointers which may point to data of different types, or
whose type is originally unknown. A pointer may be cast (type converted) to another type. For example,
Two operators are used for allocating and deallocating memory blocks on the heap. The new operator takes a
type as argument and allocated a memory block for an object of that type. It returns a pointer to the allocated
block. For example,
Memory allocated from the heap does not obey the same scope rules as normal variables. For example,
in
17
when Foo returns, the local variable str is destroyed, but the memory block pointed to by str is
not. The latter remains allocated until explicitly released by the programmer.
The delete operator is used for releasing memory blocks allocated by new. It takes a pointer as
argument and releases the memory block to which it points. For example:
Note that when the block to be deleted is an array, an additional [] should be included to indicate
this.
Should delete be applied to a pointer which points to anything but a dynamically-allocated
object (e.g., a variable on the stack), a serious runtime error may occur. It is harmless to apply
delete to the 0 pointer.
Dynamic objects are useful for creating data which last beyond the function call which creates
them. Listing 5.1 illustrates this using a function which takes a string parameter and returns a copy
of the string.
Listing 5.1
1 #include <string.h>
5 strcpy(copy, str);
6 return copy;
7 }
Annotation (analysis)
1 This is the standard string header file which declares a variety of functions for manipulating
strings.
4 The strlen function (declared in string.h) counts the characters in its string argument up to
(but excluding) the final null character. Because the null character is not included in the count,
we add 1 to the total and allocate an array of characters of that size.
5 The strcpy function (declared in string.h) copies its second argument to its first, character by
character, including the final null character.
Because of the limited memory resources, there is always the possibility that dynamic memory
may be exhausted during program execution, especially when many large blocks are allocated and
none released. Should new be unable to allocate a block of the requested size, it will return 0 instead.
It is the responsibility of the programmer to deal with such possibilities.
18
as integer arithmetic, because the outcome depends on the size of the object pointed to. For
example, suppose that an int is represented by 4 bytes. Now, given
char *str = "HELLO";
int nums[] = {10, 20, 30, 40};
int *ptr = &nums[0]; // pointer to first element
str++ advances str by one char (i.e., one byte) so that it points to the second character of "HELLO",
whereas ptr++ advances ptr by one int (i.e., four bytes) so that it points to the second element of
nums. Figure 5.1 illustrates this diagrammatically.
str ptr
str++ ptr++
It follows, therefore, that the elements of "HELLO" can be referred to as *str, *(str + 1),
*(str + 2), etc. Similarly, the elements of nums can be referred to as *ptr, *(ptr + 1), *(ptr +
2), and *(ptr + 3).
Another form of pointer arithmetic allowed in C++ involves subtracting two pointers of the
same type. For example:
int *ptr1 = &nums[1];
int *ptr2 = &nums[3];
int n = ptr2 - ptr1; // n becomes 2
Pointer arithmetic is very handy when processing the elements of an array. Listing 5.2 shows as
an example a string copying function similar to strcpy.
Listing 5.2
1 void CopyString (char *dest, char *src)
2 {
3 while (*dest++ = *src++)
4 ;
5 }
Annotation
3 The condition of this loop assigns the contents of src to the contents of dest and then
increments both pointers. This condition becomes 0 when the final null character of src is
copied to dest.
In turns out that an array variable (such as nums) is itself the address of the first element of the
array it represents. Hence the elements of nums can also be referred to using pointer arithmetic on
nums, that is, nums[i] is equivalent to *(nums + i). The difference between nums and ptr is that
nums is a constant, so it cannot be made to point to anything else, whereas ptr is a variable and can
be made to point to any other integer.
Listing 5.3 shows how the HighestTemp function (shown earlier in Listing 5.Error! Bookmark
not defined.) can be improved using pointer arithmetic.
Listing 5.3
19
1 int HighestTemp (const int *temp, const int rows, const int columns)
2 {
3 int highest = 0;
Annotation
1 Instead of passing an array to the function, we pass an int pointer and two additional
parameters which specify the dimensions of the array. In this way, the function is not restricted
to a specific array size.
6 The expression *(temp + i * columns + j) is equivalent to temp[i][j] in the previous
version of this function.
HighestTemp can be simplified even further by treating temp as a one-dimensional array of row
* column integers. This is shown in Listing 5.4.
Listing 5.4
1 int HighestTemp (const int *temp, const int rows, const int columns)
2 {
3 int highest = 0;
defines a function pointer named Compare which can hold the address of any function that takes two
constant character pointers as arguments and returns an integer. The string comparison library
function strcmp, for example, is such. Therefore:
Compare = &strcmp; // Compare points to strcmp function
20
When a function address is assigned to a function pointer, the two types must match. The above
definition is valid because strcmp has a matching function prototype:
int strcmp(const char*, const char*);
Given the above definition of Compare, strcmp can be either called directly, or indirectly via
Compare. The following three calls are equivalent:
Listing 5.5
1 int BinSearch (char *item, char *table[], int n,
2 int (*Compare)(const char*, const char*))
3 {
4 int bot = 0;
5 int top = n - 1;
6 int mid, cmp;
Annotation
1 Binary search is a well-known algorithm for searching through a sorted list of items. The search
list is denoted by table which is an array of strings of dimension n. The search item is denoted
by item.
2 Compare is the function pointer to be used for comparing item against the array elements.
7 Each time round this loop, the search span is reduced by half. This is repeated until the two
ends of the search span (denoted by bot and top) collide, or until a match is found.
9 The item is compared against the middle item of the array.
10 If item matches the middle item, the latter’s index is returned.
11 If item is less than the middle item, then the search is restricted to the lower half of the array.
21
14 If item is greater than the middle item, then the search is restricted to the upper half of the
array.
16 Returns -1 to indicate that there was no matching item.
The following example shows how BinSearch may be called with strcmp passed as the
comparison function:
char *cities[] = {"Boston", "London", "Sydney", "Tokyo"};
cout << BinSearch("Sydney", cities, 4, strcmp) << '\n';
3.1.4. References
A reference introduces an alias for an object. The notation for defining references is similar to that
of pointers, except that & is used instead of *. For example,
double num1 = 3.14;
double &num2 = num1; // num is a reference to num1
defines num2 as a reference to num1. After this definition num1 and num2 both refer to the same
object, as if they were the same variable. It should be emphasized that a reference does not create a
copy of an object, but merely a symbolic alias for it. Hence, after
num1 = 0.16;
You can also initialize a reference to a constant. In this case a copy of the constant is made
(after any necessary type conversion) and the reference is set to refer to the copy.
int &n = 1; // n refers to a copy of 1
The reason that n becomes a reference to a copy of 1 rather than 1 itself is safety. Consider what
could happen if this were not the case.
int &x = 1;
++x;
int y = x + 1;
The 1 in the first and the 1 in the third line are likely to be the same object (most compilers do
constant optimization and allocate both 1’s in the same memory location). So although we expect y
to be 3, it could turn out to be 4. However, by forcing x to be a copy of 1, the compiler guarantees
that the object denoted by x will be different from both 1’s.
The most common use of references is for function parameters. Reference parameters facilitates
the pass-by-reference style of arguments, as opposed to the pass-by-value style which we have
used so far. To observe the differences, consider the three swap functions in Listing 5.6.
Listing 5.6
22
1 void Swap1 (int x, int y) // pass-by-value (objects)
2 {
3 int temp = x;
4 x = y;
5 y = temp;
6 }
23
Self-test Exercise
1. Single-Dimensional Array: You are developing a student grading system for a class of 30
students. Write a C++ program to input the grades of each student for a particular subject and calculate
the average grade.
2. Two-Dimensional Array: You are managing a small library with multiple shelves and books on
each shelf. Write a C++ program to represent the library inventory using a two-dimensional array. Allow
users to add, remove, and search for books by title or author.
3. Three-Dimensional Array: You are working on a weather monitoring system that collects data
from multiple sensors placed in different locations. Write a C++ program to store temperature readings
from these sensors in a three-dimensional array. Implement functions to display the average temperature
for each sensor and the maximum temperature recorded overall.
4. Single-Dimensional Array: You are developing an ATM system for a bank. Write a C++
program to simulate the process of withdrawing money from an account. Use a single-dimensional array
to store account balances for multiple users and implement functions to deposit and withdraw funds.
5. Two-Dimensional Array: You are designing a seating arrangement system for a theater. Write a
C++ program to represent the seating layout using a two-dimensional array. Allow users to book seats,
view available seats, and cancel bookings.
6. Three-Dimensional Array: You are working on a 3D graphics application that simulates a city
skyline. Write a C++ program to store building heights for different city blocks using a three-
dimensional array. Implement functions to calculate the average building height and determine the
tallest building in each block.
7. Single-Dimensional Array: You are developing a stock management system for a grocery store.
Write a C++ program to track the inventory of different products using a single-dimensional array.
Implement functions to add new products, update quantities, and generate reports.
8. Two-Dimensional Array: You are creating a chess game application. Write a C++ program to
represent the chessboard using a two-dimensional array. Implement functions to move pieces, check for
checkmate, and display the board after each move.
9. Three-Dimensional Array: You are working on a medical imaging system that captures MRI
scans of patients' brains. Write a C++ program to store pixel intensity values for MRI images using a
three-dimensional array. Implement functions to apply image processing filters and display the
processed images.
10. Single-Dimensional Array: You are developing a music playlist application. Write a C++
program to store the names of songs in a playlist using a single-dimensional array. Implement functions
to add new songs, shuffle the playlist, and play songs in a loop.
11. Pointer to Array: You are developing a program to store the scores of students in an exam.
Write a C++ program that uses a pointer to dynamically allocate an array to store the scores of 10
students. Initialize the array with random scores and display them.
12. Pointer Arithmetic: You are working on a data processing application that deals with arrays of
integers. Write a C++ program that uses pointer arithmetic to find the sum of elements in an integer
array. Display the sum as output.
13. Pointer to Function: You are designing a calculator application that performs arithmetic
operations. Write a C++ program that defines functions for addition, subtraction, multiplication, and
division. Use function pointers to switch between different arithmetic operations based on user input.
14. Pointer to Pointer: You are working on a text processing application that manipulates strings.
Write a C++ program that uses a pointer to pointer to dynamically allocate memory for a 2D array of
characters to store a list of words. Allow users to input words and display them.
24
15. Dynamic Memory Allocation: You are developing a memory management system for a gaming
application. Write a C++ program that dynamically allocates memory for an array of integers based on
user input for the array size. Populate the array with random numbers and display them.
16. Pointer to Constant: You are designing a program to perform mathematical calculations using
constants. Write a C++ program that defines constant variables for the values of pi and gravity. Use
pointers to constants to perform calculations such as area and force.
17. Pointer to Function as Parameter: You are working on a sorting algorithm for arrays of integers.
Write a C++ program that defines a function to sort an array using the bubble sort algorithm. Use a
pointer to function as a parameter to generalize the sorting process for different types of arrays.
18. Pointer to Array of Pointers: You are implementing a command-line interface for a text-based
adventure game. Write a C++ program that uses an array of pointers to strings to represent different
game commands. Allow users to input commands and display appropriate responses.
19. String Length: You are developing a text processing application that requires calculating the
length of a string. Write a C++ program that prompts the user to enter a string and then calculates and
displays the length of the string.
20. String Concatenation: You are working on a messaging application that requires concatenating
two strings. Write a C++ program that prompts the user to enter two strings and then concatenates them.
Display the concatenated string as output.
21. String Comparison: You are designing a program that checks if two strings are equal. Write a
C++ program that prompts the user to enter two strings and then compares them. Display a message
indicating whether the strings are equal or not.
22. Substring Search: You are developing a search engine that searches for a keyword within a text
document. Write a C++ program that prompts the user to enter a string and a keyword, then searches for
the keyword within the string. Display the position of the keyword if found.
23. String Reversal: You are implementing a feature in your application that requires reversing a
string. Write a C++ program that prompts the user to enter a string and then reverses it. Display the
reversed string as output.
24. String Tokenization: You are working on a text parsing application that requires breaking a
string into tokens. Write a C++ program that prompts the user to enter a sentence and then tokenizes it
based on whitespace. Display each token separately.
25. String Trimming: You are developing a text processing tool that removes leading and trailing
whitespace from a string. Write a C++ program that prompts the user to enter a string and then trims the
whitespace. Display the trimmed string as output.
26. String Conversion: You are designing a program that converts a string to uppercase or
lowercase. Write a C++ program that prompts the user to enter a string and then converts it to uppercase
or lowercase based on user input. Display the converted string as output.
27. String Replacement: You are implementing a feature in your application that requires replacing
occurrences of a substring with another string. Write a C++ program that prompts the user to enter a
string, a substring to replace, and the replacement string. Perform the replacement and display the
modified string.
28. Palindrome Check: You are developing a utility to check if a given string is a palindrome.
Write a C++ program that prompts the user to enter a string and then checks if it is a palindrome.
Display a message indicating whether the string is a palindrome or not.
25