Chapter One: Fundamentals of Programming IIBHU

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Fundamentals of Programming IIBHU

CHAPTER ONE

ARRAYS AND STRINGS

Arrays

C++ provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type. Instead of declaring
individual variables, such as number0, number1, ..., and number99, you declare one array
variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index. All arrays consist of
contiguous memory locations. The lowest address corresponds to the first element and the
highest address to the last element. In other words, an array is a group or a table of values
referred to by the same name. The individual values in array are called elements. Array elements
are also variables. The Array is a 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. The
array is a block of memory representing a collection of many simple data variables stored in a
separate array element, and the computer stores all the elements of an array consecutively in
memory. 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.
Declaring Arrays
To declare an array in C++, the programmer specifies the type of the elements and the number of
elements required by an array as follows:
type arrayName [ arraySize ];
This is called a one-dimension array. One dimensional array is an array in which the components
are arranged in a list form. The arraySize must be an integer constant greater than zero and type
can be any valid C++ data type. For example, to declare a 10-element array called balance of
type double, use this statement:

Chapter one: Arrays and strings Page 1


Fundamentals of Programming IIBHU

double balance[10];
Initializing Arrays
You can initialize C++ array elements either one by one or using a single statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements that we
declare for the array between square brackets [ ]. Following is an example to assign a single
element of the array:
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write:
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th
index will be 5th, i.e., last element because all arrays have 0 as the index of their first element
which is also called base index. Following is the pictorial representation of the same array we
discussed above:

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. Accessing array component syntax is
as follows;
ArrayName[index];the index specifies the position of components. For example:
balance[9]; or double salary = balance[9];
The above statement will take 10th element from the array and assign the value to salary
variable. Following is an example, which will use all the above-mentioned three concepts viz.
declaration, assignment and accessing arrays:
#include <iostream>
using namespace std;
#include <iomanip>

Chapter one: Arrays and strings Page 2


Fundamentals of Programming IIBHU

using std::setw;
int main ()
{
int n[ 10 ]; // n is an array of 10 integers
// initialize elements of array n to 0
for ( int i = 0; i < 10; i++ )
{
n[ i ] = i + 100; // set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;
// output each array element's value
for ( int j = 0; j < 10; j++ )
{
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}
return 0;
}
This program makes use of setw() function to format the output. When the above code is
compiled and executed, it produces the following result:
Element Value

Multi-dimensional Arrays
C++ allows multidimensional arrays. Multidimensional arrays can be described as arrays of
arrays. Here is the general form of a multidimensional array declaration:
type name[size1][size2]...[sizeN];

Chapter one: Arrays and strings Page 3


Fundamentals of Programming IIBHU

For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:
int threedim[5][10][4];

Multidimensional arrays are nothing else than an abstraction, since we can simply obtain
the same results with a simple array by putting a factor between its indices:

int matrix [3][5]; is equivalent to

int matrix [15]; (3 * 5 = 15) With the only difference that the compiler remembers for
us the depth of each imaginary dimension.

Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional
integer array of size x,y, you would write something as follows:
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.
A two-dimensional array can be think as a table, which will have x number of rows and y
number of columns. A 2-dimensional array a, which contains three rows and four columns can
be shown as below:

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is
the name of the array, and i and j are the subscripts that uniquely identify each element in a.
Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */

Chapter one: Arrays and strings Page 4


Fundamentals of Programming IIBHU

};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional Array Elements
An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array. For example:
int val = a[2][3];
The above statement will take 4th element from the 3rd row of the array. You can verify it in the
above digram.
#include <iostream>
using namespace std;
int main ()
{
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
// output each array element's value
for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 2; j++ )
{
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2

Chapter one: Arrays and strings Page 5


Fundamentals of Programming IIBHU

a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is likely
that most of the arrays you create will be of one or two dimensions.

Arrays as parameters

At some point, we may need to pass an array to a function as a parameter. In C++, it is not
possible to pass the entire block of memory represented by an array to a function directly as an
argument. But what can be passed instead is its address. In practice, this has almost the same
effect, and it is a much faster and more efficient operation. To accept an array as parameter for a
function, the parameters can be declared as the array type, but with empty brackets, omitting the
actual size of the array. For example:

void procedure (int arg[])


This function accepts a parameter of type "array of int" called arg. In order to pass to this
function an array declared as:

int myarray [40];


It would be enough to write a call like this:

procedure (myarray);
Here you have a complete example:

Chapter one: Arrays and strings Page 6


Fundamentals of Programming IIBHU

// arrays as parameters Out put


#include <iostream> 5 10 15
using namespace std; 2 4 6 8 10
void printarray (int arg[], int length) {
for (int n=0; n<length; ++n)
cout << arg[n] << ' ';
cout << '\n';
}
int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
}
In the code above, the first parameter (int arg[]) accepts any array whose elements are of type int,
whatever its length. For that reason, we have included a second parameter that tells the function
the length of each array that we pass to it as its first parameter. This allows for loop that prints
out the array to know the range to iterate in the array passed, without going out of range.

STRINGS

A string is a sequence of characters stored in a certain address in memory. In all programs and
concepts we have seen so far, we have used only numerical variables, used to express numbers
exclusively. But in addition to numerical variables there also exist strings of characters that allow
us to represent successive characters, like words, sentences, names, texts, etc. Until now we have
only used them as constants, but we have never considered variables able to contain them. In
C++ there is no specific elementary variable type to store string of characters. In order to fulfill
this feature we can use arrays of type char, which are successions of char elements. Remember
that this data type (char) is the one used to store a single character, for that reason arrays of them
are generally used to make strings of single characters.

Chapter one: Arrays and strings Page 7


Fundamentals of Programming IIBHU

For example, the following array (or string of characters) can store a string up to 20
characters long. You may imagine it thus: char name [20];

name

This maximum size of 20 characters is not required to be always fully used. For example, name
could store at some moment in a program either the string of characters "Hello" or the string
"studying C++”. Therefore, since the array of characters can store shorter strings than its total
length, there has been reached a convention to end the valid content of a string with a null
character, whose constant can be written as '\0’.
We could represent name (an array of 20 elements of type char) storing the strings of characters
"Hello" and "Studying C++" in the following way:

Notice how after the valid content it is included a null character ('\0') in order to indicate the end
of string. The empty cells (elements) represent indeterminate values.

C++ provides following two types of string representations:


 The C-style character string.

 The string class type introduced with Standard C++.

The C-Style Character String


The C-style character string originated within the C language and continues to be supported
within C++. This string is actually a one-dimensional array of characters which is terminated by
a null character '\0'. Thus a null-terminated string contains the characters that comprise the string
followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To
hold the null character at the end of the array, the size of the character array containing the string
is one more than the number of characters in the word "Hello."

Chapter one: Arrays and strings Page 8


Fundamentals of Programming IIBHU

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


If you follow the rule of array initialization, then you can write the above statement as follows:
char greeting[] = "Hello";
Following is the memory presentation of above defined string in C/C++:

Actually, you do not place the null character at the end of a string constant. The C++ compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to print
above-mentioned string:
#include <iostream>
using namespace std;
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Greeting message: Hello
C++ supports a wide range of functions that manipulate null-terminated strings:
S.N. Function & Purpose
1 strcpy(s1, s2); Copies string s2 into string s1.
2 strcat(s1, s2); Concatenates string s2 onto the end of string s1.
3 strlen(s1); Returns the length of string s1.
4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater
than 0 if s1>s2.

Following example makes use of few of the above-mentioned functions:


#include <iostream>
#include <cstring>

Chapter one: Arrays and strings Page 9


Fundamentals of Programming IIBHU

using namespace std;


int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;
// copy str1 into str3
strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;
// concatenates str1 and str2
strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;
// total lenghth of str1 after concatenation
len = strlen(str1);
cout << "strlen(str1) : " << len << endl;
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
The String Class in C++
The standard C++ library provides a string class type that supports all the operations mentioned
above, additionally much more functionality. Let us check the following example:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str1 = "Hello";

Chapter one: Arrays and strings Page 10


Fundamentals of Programming IIBHU

string str2 = "World";


string str3;
int len ;
// copy str1 into str3
str3 = str1;
cout << "str3 : " << str3 << endl;
// concatenates str1 and str2
str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;
// total length of str3 after concatenation
len = str3.size();
cout << "str3.size() : " << len << endl;
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10

Chapter one: Arrays and strings Page 11


Fundamentals of Programming IIBHU

Worksheet No 1:

1. Define strlen function (i.e write the function body of strlen)


2. Define the strcmp function and the strncmp function
3. Define strcpy function and the strncpy function
4. Define strcat function and the strncat function
5. Write a program to store the ages of six of your friends in a single array. Store each of the six
ages using the assignment operator. print the ages on the screen
6. Write a C++ program that accepts 10 integers from the user and finally displays the smallest
value and the largest value.
7. Write a program that accepts ten different integers from the user and display these numbers
after sorting them in increasing order.
8. Write a program to store six of your friend’s ages in a single array. Assign the ages in a random
order. print the ages, from low to high, on-screen
9. Modify the program on Q8 to print the ages in descending order.
10. Write a C++ program that calculates the letter grades of 20 students. The program should
accept the mid result and the final result from the students. Use the appropriate validity
control mechanism to prevent wrong inputs.
11. Write a C++ program that has two functions toBinary and toDecimal. The program should
display a menu prompting the user to enter his choice. If the user selects toBinary, then the
function should accept a number in base ten and displays the equivalent binary representation.
The reverse should be done if the user selects toDecimal.
12. Develop a C++ program that accepts a word from the user and then checks whether the word is
palindrome or not. (NB a word is palindrome if it is readable from left to right as well as right
to left).
13. Write a C++ program that accepts a word from the user and then displays the word after
reversing it.
14. Develop a C++ program that accepts the name of a person and then counts how many vowels
the person’s name have.
15. Modify the question in Q14 in such a way that it should replace vowel characters with * in the
person name.
16. Write a program in C++ which read a three digit number and generate all the possible
permutation of numbers using the above digits. For example n = 123 then the permutations are

123, 213, 312, 132, 231, 321
17. Write a program which read a set of lines until you enter #.
18. Write a program which read two matrixes and then print a matrix which is addition of these
two matrixes.
19. Write a program which reads two matrix and multiply them if possible
20. Write a program which reads a 3 x 2 matrix and then calculates the sum of each row and store
that in a one dimension array.

Chapter one: Arrays and strings Page 12

You might also like