Chapter One: Fundamentals of Programming IIBHU
Chapter One: Fundamentals of Programming IIBHU
Chapter One: Fundamentals of Programming IIBHU
CHAPTER ONE
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:
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:
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];
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 [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 */
};
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
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:
procedure (myarray);
Here you have a complete example:
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.
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.
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.
Worksheet No 1: