Two Dimensional Arrays

Two Dimensional Arrays

A 2-dimensional array is an array of arrays. In other words, it is an array where each member of the array is also an array. 

Declaring and Initializing a 2-Dimensional Array
Two-dimensional array is made of rows and columns. Each column represents one category of data that everyone of the rows shares with the other rows. To declare it, use double pair of a opening and closing square brackets.
Data_Type NameOfArray[ROWS][COLUMNS];
int TwoDArray[5][5];
This declarations creates 5 rows and each row contains 5 elements.
You can initialize an array the same way you would proceed the a one-dimensional array: simply provide a list of values in the curly brackets.
A multidimensional array is represented as an algebraic matrix as MxN. This means that the array is made of M rows and N columns. Total number of elements of a multidimensional array can be calculated by multiply the number of rows by the number of columns. Therefore a 2x3 array contains 2*3=6 elements.
Based on this, when initializing a 2-dimensional array, make sure you provide a number of values that is less than or equal to the total number of elements.
Here is an example:
double age[2][3] = {12,14,16,17,17,19};
To locate a member of the array, this time, each must be identified by its double index. The first member is indexed at [0][0]. The second is at [0][1]. For a 2x3 array as this one, the 5th member is at [1][1]. You can use this same approach to display the values of the members of the array. Here is an example:
#include <iostream.h>
int main()
{
// A 2-Dimensional array
   int TwoDArray[2][3] = {1,2,3,4,5,6};
// Display the array
    cout << "Elements of the array";
    cout << "\nTwoDArray [0][0]" << ": " << TwoDArray[0][0];
    cout << "\nTwoDArray [0][1]" << ": " << TwoDArray[0][1];
    cout << "\nTwoDArray [0][2]" << ": " << TwoDArray[0][2];
    cout << "\nTwoDArray [1][0]" << ": " << TwoDArray[1][0];
    cout << "\nTwoDArray [1][1]" << ": " << TwoDArray[1][1];
    cout << "\nTwoDArray [1][2]" << ": " << TwoDArray[1][2];
    cout << endl;
    return 0;
}
Output:
Elements of the array
TwoDArray [0][0]: 1
TwoDArray [0][1]: 2
TwoDArray [0][2]: 3
TwoDArray [1][0]: 4
TwoDArray [1][1]: 5
TwoDArray [1][2]: 6
C++ also allows you to include each row in its own pair of curly brackets. You must separate each row from the next with a comma. Here is an example:
int items[2][3] = {
                    { 1,2,3},{4,5,6}  
                   };
Processing a 2-Dimensional Array
To process a 2D array, we should know how many columns the array contains. We can use two for loops to process the array. Here is an example:
#include <iostream.h>
int main()
{
    // A 2-Dimensional array
    int items[2][3] = {
                { 1,2,3},
                { 4,5,6}
                      };
    // Display all elements
    cout << "Elements of the array";
    for(int i = 0; i < 2; ++i)
       for(int j = 0; j < 3; ++j)
        cout << "\nItems[" << i << "][" << j << "]: " << items[i][j];
    cout << endl;
  return 0;
}
Sum of Diagonal elements of an Two Dimensional Array
#include <iostream.h>
#define N 3
#define M 3
int main()
{
    int a1[N][M],s;
    int i,j;
    cout<<"Enter Elements of  Array";
    for(i=0;i<N;i++)
       for(j=0;j<M;j++)
         cin>>a1[i][j];
     // Now we will find sum of diagonal elements
    for(i=0;i<N;i++)
       for(j=0;j<M;j++)
         {
          if(i==j)
          s=s+ a1[i][j];
         }
    cout<<endl<<"Sum of diagonal elements of a1 and a2 is  "<<s;
return 0;
}
Finding Maximum element in MXN Array
// Max Element in a two Dimensional Array
#include <iostream.h>
#define N 3
#define M 3
int main()
{
    int a1[N][M];
    int max=0;
    int i,j;
    cout<<"Enter Elements of  Array";
    for(i=0;i<N;i++)
       for(j=0;j<M;j++)
         cin>>a1[i][j];
     // Now we will find Max element
    for(i=0;i<N;i++)
       for(j=0;j<M;j++)
         {
          if(max<a1[i][j])
          max=a1[i][j];
         }
cout<<endl<<"Maximum element is  "<<max;
return 0;
}Finding Minimum element in MXN Array
// Min Element in a two Dimensional Array
#include <iostream.h>
#define N 3
#define M 3
int main()
{
    int a1[N][M];
    int min=9999;
    int i,j;
    cout<<"Enter Elements of  Array";
    for(i=0;i<N;i++)
       for(j=0;j<M;j++)
         cin>>a1[i][j];
     // Now we will find Min element
    for(i=0;i<N;i++)
       for(j=0;j<M;j++)
        { if(min>a1[i][j])
          min=a1[i][j];
         }
    cout<<endl<<"Minimum element is  "<<min;
    cin>>min;
return 0;
}
2D Array and String
Because strings are in fact sequences of characters, we can represent them also as plain arrays of char elements.
For example, the following array:
char Ayan[20];
is an array that can store up to 20 elements of type char. In this array, we can store sequences of characters up to 20 characters long. But we can also store shorter sequences. For example, Ayan could store at some point in a program either the sequence "Hello" or the sequence "Happy Diwali", since both are shorter than 20 characters.
Therefore, since the array of characters can store shorter sequences than its total length, a special character is used to signal the end of the valid sequence: the null character, whose literal constant can be written as '\0' (backslash, zero).
Our array of 20 elements of type char, called Ayan, can be represented storing the characters sequences "Hello" and "Happy Diwali" as:
Notice how after the valid content a null character ('\0') has been included in order to indicate the end of the sequence.
Initialization of null-terminated character sequences
If we want to initialize an array of characters with some predetermined sequence of characters we can do it just like any other array:
char Ayan[] = { 'H', 'e', 'l', 'l', 'o', '\0' }; 
In this case we would have declared an array of 6 elements of type char initialized with the characters that form the word "Hello" plus a null character '\0' at the end.
Arrays of char elements have an additional method to initialize their values: using string literals.String literals enclosed between double quotes always have a null character ('\0') automatically appended at the end by the compiler. Therefore we can initialize the array of char elements called Ayan with a null-terminated sequence of characters by either one of these two methods:
char Ayan[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char Ayan[] = "Hello"; 
In both cases the array of characters Ayan is declared with a size of 6 elements of type char: the 5 characters that compose the word "Hello" plus a final null character ('\0') which specifies the end of the sequence and that, in the second case, when using double quotes (") it is appended automatically.
Using null-terminated sequences of characters
Null-terminated sequences of characters are the natural way of treating strings in C++.For example, cin and cout support null-terminated sequences as valid containers for sequences of characters, so they can be used directly to extract strings of characters from cin or to insert them into cout. For example:
// null-terminated sequences of characters
#include <iostream.h>
int main ()
{
  char yourname[] = "Please, enter your first name: ";
  char message [] = "Hello, ";
  char name [80];
  cout << yourname;
  cin >> name;
  cout << message << name << "!";
  return 0;
}
Please, enter your first name: Sanjeev
Hello, Sanjeev!
As you can see, we have declared three arrays of char elements. The first two were initialized with string literal constants, while the third one was left uninitialized. In the first two arrays the size was implicitly defined by the length of the literal constant they were initialized to. While for name we have explicitly specified that it has a size of 80 chars.

No comments:

Post a Comment