Amazon

Arrays (1D & 2D)

Arrays (1D & 2D)



  1. Dimensional Arrays.
          
Let's start by looking at a single variable used to store a person's age.


1: #include <iostream.h>

2:
3: int main()
4: {
5: short age;
6: age=23;
7: cout<<"The age is =” <<age<<endl;
8: return 0;
9: }
Not much to it. The variable age is created at line (5) as a short. A value is assigned to age. Finally, age is printed to the screen.


Now let's keep track of 4 ages instead of just one. We could create 4 separate variables, but 4 separate variables have limited appeal. (If using 4 separate variables is appealing to you, then consider keeping track of 93843 ages instead of just 4). Rather than using 4 separate variables, we'll use an array.
Here's how to create an array and one way to initialize an array:

1: #include <iostream.h>
2:
3: int main()
4: {
5: short age[4];
6: age[0]=23;
7: age[1]=34;
8: age[2]=65;
9: age[3]=74;
10: return 0;
11: }

On line (5), an array of 4 short's is created. Values are assigned to each variable in the array on line (6) through line (9).



Accessing any single short variable, or element, in the array is straightforward. Simply provide a number in square braces next to the name of the array. The number identifies which of the 4 elements in the array you want to access.
The program above shows that the first element of an array is accessed with the number 0 rather than 1. Later in the tutorial, We'll discuss why 0 is used to indicate the first element in the array.

Printing Arrays

Our program is a bit unrevealing in that we never print the array to screen. Here is the same program with an attempt to print the array to the screen:

1: #include <iostream.h>
2:
3: int main()
4: {
5: short age[4];
6: age[0]=23;
7: age[1]=34;
8: age[2]=65;
9: age[3]=74;
10:
11: cout<<"\n" <<age;
12: return 0;
13: }
Line (11) is meant to print the 4 ages to the screen. But instead of printing out the four short variables, what appears to be nonsense prints out instead.
What the "nonsense" output actually is and why the 4 array values were not printed will be addressed later in the tutorial. For now, the important point to come away with is that simply providing the name of the array in an output statement will not print out the elements of the array.
How about printing out each of the values separately? Try this:
1: #include <iostream.h>
2:
3: int main()
4: {
5: short age[4];
6: age[0]=23;
7: age[1]=34;
8: age[2]=65;
9: age[3]=74;
10: cout<<"Age at index[0]= "<<age[0]<<endl;
11: cout<<"Age at index[1]= "<<age[1]<<endl;
12: cout<<"Age at index[2]= "<<age[2]<<endl;
13: cout<<"Age at index[3]= "<<age[3]<<endl;
14: return 0;
15: }
Lines (10) through line (13) produce the output we are expecting.
There is no single statement in the language that says "print an entire array to the screen". Each element in the array must be printed to the screen individually.

Copying Arrays.

Suppose that after filling our 4 element array with values, we need to copy that array to another array of 4 short's? Try this:
1: #include <iostream.h>
2:
3: int main()
4: {
5: short age[4];
6: short same_age[4];
7: age[0]=23;
8: age[1]=34;
9: age[2]=65;
10: age[3]=74;
11:
12: same_age=age;
13:
14: cout<<"The age at index[0]"<<same_age[0];
15: cout<<"The age at index[1]"<<same_age[1];
16: cout<<"The age at index[2]"<<same_age[2];
17: cout<<"The age at index[3]"<<same_age[3];
18: return 0;
19: }
Line (12) tries to copy the age array into the same_age array. What happened when you tried to compile the program above?
The point here is that simply assigning one array to another will not copy the elements of the array. The hard question to answer is why the code doesn't compile. Later in the tutorial this example will be re-examined to explain why line (12) doesn't work. This code should not compile on either C or C++ compilers. However, some older C++ compilers may ignore the ISO C++ standard and allow line 12 to compile. If it does compile on your C++ compiler, make a mental note that it is incorrect behavior.
Let's try copying arrays using a technique similar to the technique used to print arrays (that is, one element at a time):
1: #include <iostream.h>
2:
3: int main()
4: {
5: short age[4];
6: short same_age[4];
7:
8: age[0]=23;
9: age[1]=34;
10: age[2]=65;
11: age[3]=74;
12:
13: same_age[0]=age[0];
14: same_age[1]=age[1];
15: same_age[2]=age[2];
16: same_age[3]=age[3];
17:
18: cout<<"The age at index[0]= "<<same_age[0]<<endl;
19: cout<<"The age at index[1]= "<<same_age[1]<<endl;
20: cout<<"The age at index[2]= "<<same_age[2]<<endl;
21: cout<<"The age at index[3]= "<<same_age[3]<<endl;
22: return 0;
23: }
This technique for copying arrays works fine. Two arrays are created: age and same_age. Each element of the age array is assigned a value. Then, in order to copy of the four elements in age into the same_age array, we must do it element by element.





Copy second element
Like printing arrays, there is no single statement in the language that says "copy an entire array into another array". The array elements must be copied individually.
The technique used to copy one array into another is exactly the same as the technique used to copy 4 separate variables into 4 other variables. So what is the advantage to using arrays over separate variables?
One significant advantage of an array over separate variables is the name. In our examples, using four separate variables requires 4 unique names. The 4 short variables in our array have the same name, age. The 4 short's in the array are identical except for an index number used to access them. This distinction allows us to shorten our code in a way that would be impossible with 4 variables, each with unique names:
1: #include <iostream.h>
2:
3: int main()
4: {
5: short age[4];
6: short same_age[4];
7: int i, j;
8: age[0]=23;
9: age[1]=34;
10: age[2]=65;
11: age[3]=74;
12:
13: for(i=0; i<4; i++)
14: same_age[i]=age[i];
15:
16: for(j=0; j<4; j++)
17: cout<<"The age is = "<<same_age[j]<<endl;
18: return 0;
19: }
Since the only difference between each of the short's in the arrays is their index, a loop and a counter can be used to more easily copy all of the elements. The same technique is used to shorten the code that prints the array to the screen.
Even though arrays give us some convenience when managing many variables of the same type, there is little difference between an array and variables declared individually. There is no single statement to copy an array, there is no single statement to print an array.
If we want to perform any action on an array, we must repeatedly perform that action on each element in the array.

2-Dimensional (2D) Arrays

So far we have explored arrays with only one dimension. It is also possible for arrays to have two or more dimensions. The two-dimensional array is also called a matrix.
Here is a sample program that stores roll number and marks obtained by a student side by side in a matrix.
#include<iostream.h>
void main( )
{
int stud[4][2] ;
int i,j ;
for ( i = 0 ; i <= 3 ; i++ )
{
cout<<"\n Enter roll no. and marks "<<endl ;
cin>>stud[i][0]>>stud[i][1];
}
cout<<"The Roll No. and Marks are: "<<endl<<endl;
cout<<"RollNo.\t Marks\n";
for ( i = 0 ; i <= 3 ; i++ )
cout<<stud[i][0]<<" \t "<<stud[i][1]<<endl ;
}
There are two parts to the program—in the first part through a for loop we read in the values of roll no. and marks, whereas, in second part through another for loop we print out these values.
Look at the cin( ) statement used in the first for loop:
cin>>stud[i][0]>>stud[i][1];
In stud[i][0] and stud[i][1] the first subscript of the variable stud, is row number which changes for every student. The second subscript tells which of the two columns are we talking about—the zeroth column which contains the roll no. or the first column which contains the marks. Remember the counting of rows and columns begin with zero. 
Thus, 1234 is stored in stud[0][0], 56 is stored in stud[0][1] and so on. The above arrangement highlights the fact that a two- dimensional array is nothing but a collection of a number of one- dimensional arrays placed one below the other.
In our sample program the array elements have been stored rowwise and accessed rowwise. However, you can access the array elements columnwise as well. Traditionally, the array elements are being stored and accessed rowwise; therefore we would also stick to the same strategy.

Initializing a 2-Dimensional Array

How do we initialize a two-dimensional array? As simple as this:
int stud[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
} ;
Or we can write like this also..
int stud[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;
The above format work also but it is more difficult to read as compared to the first one. It is important to remember that while initializing a 2-D array it is necessary to mention the second (column) dimension, whereas the first dimension (row) is optional.
Thus the declarations,
int arr[2][3] = { 12, 34, 23, 45, 56, 45 } ;
int arr[ ][3] = { 12, 34, 23, 45, 56, 45 } ;
are perfectly acceptable, whereas,
int arr[2][ ] = { 12, 34, 23, 45, 56, 45 } ;
int arr[ ][ ] = { 12, 34, 23, 45, 56, 45 } ;
would never work.
Memory Map of a 2-Dimensional Array
Let see the arrangement of the above student arrays in memory which contains roll number and marks
This example will simply define an array of 2x3 and take input from user and prints scanned array.
#include<iostream.h>
void main()
{
int arr[2][3],i,j;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
{
cout<<"Enter Value for " <<i+1 << " row " <<j+1 <<" column\n";
cin>>arr[i][j];
}
cout<<"\n!!!Scanning Array Complete!!!\n\n\n";
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
cout<<arr[i][j] <<"\t";
cout<<"\n\n";
}
}
Another Example:
#include <iostream>
using namespace std;
int main()
{
// A 2-Dimensional array
double distance[2][4];
cout<<"Enter values\n";
for(int i = 0; i < 2; ++i) // this loop is for Rows
for(int j = 0; j < 4; ++j) // this loop is for Columns
cin>>distance[i][j]; //getting values from the user
cout << "Members of the array"; // the statement will be print as it is
for(int i = 0; i < 2; ++i) // For Rows
for(int j = 0; j < 4; ++j) // For Columns
cout << "\nDistance [" << i << "][" << j << "]: " << distance[i][j]; //Printing Rows and Columns
cout << endl;
return 0;

Arrays and Functions:

An array can be passed to a function as argument. An array can also be returned by a function. To declare and define that a function takes an array as argument, declare the function as you would do for any regular function and, in its parentheses, specify that the argument is an array. Here is an example: 
#include <iostream>
using namespace std;
void DisplayTheArray(double member[]) //function
{
for(int i = 0; i < 5; ++i)
cout << "\nDistance " << i + 1 << ": " << member[i];
cout << endl;
}
int main()
{
const int numberOfItems = 5;
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};
cout << "Members of the array";
DisplayTheArray(distance); //calling the function
return 0;








No comments:

Post a Comment