Wednesday, March 4, 2020

CHAR ARRAYS & 2D ARRAYS


Tools needed:
1.    PC running Windows Operating System (OS)
2.    DevC++ (installed)

Turn on the PC and log into it using your student account information.

Note:
The information and concepts discussed in this lab manual are in sufficient detail but are still not exhaustive. It is assumed that all these concepts are already taught to you in your ITC theory class.

1.    Arrays
When we need to store a lot of values of the same type, instead of declaring a lot of variables, it is convenient to be able to use a single name but access different values by indexing. Such data structures are called arrays.

Initialization of char arrays:
char arrays can be initialized in two ways:

char name[10] = {'H','e','l','l','o'};
char name[10] = "Hello";

In both the cases, the remaining number of elements in the array are initialized to 0. Thus both get a NULL character at the end.

A memory-map to depict the values of elements is given below:

Element #
Index
Byte address
Byte contents
Access
1
0
0x00FF2200
'H'
age[0]
2
1
0x00FF2201
'e'
age[1]
3
2
0x00FF2202
'l'
age[2]
4
3
0x00FF2203
'l'
age[3]
5
4
0x00FF2204
'o'
age[4]
6
5
0x00FF2205
0
age[5]
7
6
0x00FF2206
0
age[6]
8
7
0x00FF2207
0
age[7]
9
8
0x00FF2208
0
age[8]
10
9
0x00FF2209
0
age[9]

However, there is a finer point to be noted. In initializing a char array the first way (as {'H','e','l','l','o'}) the first 5 indices receive the mentioned initialized value and if the array size is greater than 5, the remaining elements are initialized to 0. What if the array size is only 5?

Note that you cannot initialize a smaller array with more initialization values, the compiler will give an error. Initialization is the only time C++ helps in checking the bounds of the array!

For example, try this code:

char word[4] = "Hell";
cout << word;

You will receive a compilation error -- that says something like "initializer string for character array is too long"!

This is because in initializing a char array as a string (i.e. values enclosed in double quotes) a NULL character is also required to be appended at the end. So the array size should at least be 5!

Now, consider the code below:

char name1[5] = "Hell";
char name2[5] = "Word";
cout << name2;

We can reconstruct the memory map as:

Byte address
Byte contents
Access
0x00FF21FF
??

0x00FF2200
'W'
name2[0]
0x00FF2201
'o'
name2[1]
0x00FF2202
'r'
name2[2]
0x00FF2203
'd'
name2[3]
0x00FF2204
NULL
name2[4]
0x00FF2205
'H'
name1[0]
0x00FF2206
'e'
name1[1]
0x00FF2207
'l'
name1[2]
0x00FF2208
'l'
name1[3]
0x00FF2209
NULL
name1[4]
0x00FF220A
??


Finally, try this code:

char a1[16]={'A','r','r','a','y','1',':',' ','d','a','t','a',' ','.',' '};
char a2[16]={'A','r','r','a','y','2',':',' ','d','a','t','a','','.','.','.'};
cout << a1 << endl;
cout << a2 << endl;

Why do you see, what you see? Try to create a memory map for these two arrays (a1 and a2).

NULL char:
The use of NULL character as a delimiter simplifies the way character arrays are handled, read-in and printed-out. Consider the following code:

char word[100]; //a maximum of 99 char can be put in
cin >> word;
cout << word;

Note how only the array name is used with cin and cout. Note that this use of arrays is specific to char arrays. cin will read in char values into the array, with first character stored at the index 0, second at index 1, and so on and if the last value is entered at index 10, then at index 11 NULL character is appended.

cout will start displaying characters from the start of the array until a NULL is encountered. Note that if a NULL character is not present within the array (as in the case of a2 array above), the byte values treated as chars will continue to be displayed until a byte value of zero is encountered.

Address of a char array:
A char array's address cannot be checked this way. Recall that for arrays, the base address is the name of the array. That’s why for integer arrays, cout << num outputs the address of the array. However, for character arrays, cout starts printing the contents of array rather than its address. This is one of the differences between character and other arrays. The address of a char array cannot be displayed with knowledge learnt in this course.

In fact the address of a single char variable too cannot be displayed. Check the code below:

char ch = 'A';
cout <<&ch;

Again, &ch is treated as a character array, and starting from the contents of the variable ch the char values in contiguous memory locations will be displayed until a NULL char is encountered (reference a previous lab on types, values, addresses and storage).

Caution: Array bounds
In C++ the array bounds must be taken care of by the programmer. Changing values of elements at indices that are not within limits (0 to one less than the size-of-array) would overwrite (i.e. change) the adjacent memory bytes and may corrupt other variables! Even in the case of read, we should be careful not to exceed the array bounds, otherwise we’re liable to read other variables’ data, which could be a privacy breach.



Example 1:For a large input string (from user or from file), determine the number of characters in the string. In the following code snippet,for convenience the string has been provided as an initialization to a char array.




   char para[1000] = "It was the best of times, it was the worst \
of times, it was the age of wisdom, it was the age of foolishness, \
it was the epoch of belief, it was the epoch of incredulity, it was \
the season of Light, it was the season of Darkness, it was the \
spring of hope, it was the winter of despair, we had everything \
before us, we had nothing before us, we were all going direct to \
Heaven, we were all going direct the other way — in short, the \
period was so far like the present period, that some of its noisiest \
authorities insisted on its being received, for good or for evil, \
in the superlative degree of comparison only.";
  
   int count = 0, i;
   for(i=0; para[i]!='\0'; i++); //note the semicolon; no body present
  
   cout <<endl <<"The para has " << i << " characters!\n";

Note the use of \ at the end of a line to mark that the line continues on the next line without consideration to newline character.

getline() Function:
To read the text containing blank space, cin.getline() function can be used. This function takes two arguments. First argument is the name of the character array (address of first element of array) and second argument is the maximum size of the array.

Syntax:

cin.getline(char_array_name, size_of_array)


Example:
#include <iostream>
using namespace std;
  
int main()
{
    char str[20];
    cout << "Enter Your Name::";
    cin.getline(str, 20);

    cout << "\nYour Name is:: " << str;
    return 0;
}




2.    Two-Dimensional Arrays

Declaration of 2D Array:
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 thought of 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 in Figure 1:
Figure 1
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.
A.   Initializing Two-Dimensional Arrays
Multi-dimensioned 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 */
};
 

 

 

 

 


Initialization of 2D array

 

Two-dimensional arrays with initializer lists can omit (only) the rightmost length specification:
int a[][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 */
};

 

However, you can’t initialize an 2D array with following methods:
int a[][] = { 
 {0, 1, 2, 3} ,   /*  INVALID */
 {4, 5, 6, 7} ,   /*  INVALID */
 {8, 9, 10, 11}   /*  INVALID */
};

int a[3][] = { 
 {0, 1, 2, 3} ,   /*  INVALID */
 {4, 5, 6, 7} ,   /*  INVALID */
 {8, 9, 10, 11}   /*  INVALID */
};

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example:


B.   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 diagram. Remember index of array start from zero.



#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;}
 















Code 2. Accessing elements of 2-D array

 

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
When the above code is compiled and executed, it produces the following result:








Exercise:

Task # 1: Reverse the character Array
Write a program that can reverse the sentence entered by user. (Hint: use getline() function)

CODE:
#include <iostream>
using namespace std;
 
int main()
{
   int count;
   char string[500];
cout<<"Enter the Sentence :";
cin.getline(string, 500);
      for(int i=0;string[i]!='\0'; i++)
    { 
      count++;
      }
cout<<endl;
cout<<"The Reversed Sentence is :"<<endl;
   int j=count;
   while (j>=0)                    //for(int j=count;j>=0;j--)
   {
     cout<<string[j];
     j--;
   }
   cout<<count;
   return 0;
}

Task # 2:Based on Example 1 above
             I)        Change the code to count the number of vowels and report.
            II)        Count the number of words and report.
           III)        Count the number of sentences and report.
          IV)        Count the occurrences of the word "as" and report.
           V)        Convert all the first alphabets of all words to uppercase letters.
          VI)        Reverse the whole string and store it within para. Do not declare any other char array.
         VII)        Challenge task:Count how many times each alphabet of the English language has occurred and report.

CODE:

#include <iostream>
using namespace std;
 
int main()
{

int c,alpha[26]={0},x,size=0,rev,par,temp;

char para[1000] = "It was the best of times, it was the worst \
of times, it was the age of wisdom, it was the age of foolishness, \
it was the epoch of belief, it was the epoch of incredulity, it was \
the season of Light, it was the season of Darkness, it was the \
spring of hope, it was the winter of despair, we had everything \
before us, we had nothing before us, we were all going direct to \
Heaven, we were all going direct the other way - in short, the \
period was so far like the present period, that some of its noisiest \
authorities insisted on its being received, for good or for evil, \
in the superlative degree of comparison only.";
     
      int vowels=0,words=0,sentence=0,count=0;
      for(int i=0;i<=1000;i++)
      {
      if(para[i]=='a'||para[i]=='e'||para[i]=='i'||para[i]=='o'||para[i]=='u'||para[i]=='A'||para[i]=='E'||para[i]=='I'||para[i]=='O'||para[i]=='U')
          {
                  vowels++;
                              }                      
      if(para[i]==' ')
        {
       
                  words++;        
      }
      if(para[i]=='.')
        {
       
                  sentence++;   
      }
      if(para[i-1]==' '&&para[i+2]==' ')
        {
          if(para[i]=='a'&&para[i+1]=='s')
                  { 
                  count++;
                  }
}
if (para[i-1]==' ')
{
       if(para[i]>=97 && para[i]<=122)
      {
                  para[i]=para[i]-32;
      }
}
}
 words=words+1; // cover up for last full stop .
     
      cout<<"no of vowels="<<vowels<<endl;
      cout<<"no of words="<<words<<endl;
      cout<<"no of sentences="<<sentence<<endl;
      cout<<"no of as="<<count<<endl;
      for (int m=0;m<=800;m++)
      cout<<para[m];
cout<<endl;
while (para[x] != '\0')
 {
      size++;
      if (para[x] >= 'a' && para[x] <= 'z')
         {
         c = para[x] - 'a';
         ++alpha[c];
      }
      ++x;
   }
   cout<<"occurence of alphabets is:"<<endl;
   for (x = 0; x < 26; x++)
     {
      cout<< char(x + 'a')<<":"<< alpha[x]<< endl;
  }
    rev = 0;
    par = size - 1;
    while(rev< par)
    {
      
        temp = para[rev];
        para[rev] = para[par];
        para[par] = temp;
       
        rev++;
        par--;
    }
    cout<<"The reversed array is :"<<endl;
     cout<<para;
       // for(int z=0; z<size; z++)
    {
     //   cout<<para[z];
    }


                  return 0;
}










Task # 3: Basic calculator
This calculator builds on top of what you have already implemented in a previous lab. Further specs are that:
a)    there are four arithmetic operations (+-*/) to be performed
b)    there are four control operations (e, u, d, s) to be managed such that:
                                      i.        user enters 'e' to exit or any other key to continue with another expression.
                                     ii.        user enters 'u' for up and 'd' for down to scroll through previous expressions the user has entered.
                                    iii.        user enters 's' if s/he wishes to redo a previous calculation; in that case, the previously entered operation is executed.
Design code for these specs.

An example interaction with the program at run time could be:

Enter an expr as <operand1><+, -, * or /><operand2>: 1 + 18
1 + 1 = 2
Enter 'e' to exit or any other key to continue: k8
Enter an expras <operand1><+, -, * or /><operand2>: 2 + 28
2 + 2 = 4
Enter 'e' to exit or any other key to continue: h8
Enter an expr as <operand1><+, -, * or /><operand2>: u8
2 + 2s8
2 + 2 = 4
Enter 'e' to exit or any other key to continue: e8
Good bye.
CODE:
#include <iostream>
using namespace std;
 int main()
{
     
      int i,num1,num2,u,temp,temp1;
      char a,b,j,q;
 do{
    cout<<endl<<"Enter an expr as <operand1><+, -, * or /><operand2>: ";
            cin>>num1>>a>>num2;
            cout<<num1<<a<<num2<<"=";
     
     
            j=a;
           
switch(j)
    {
        case '+':
            cout << num1+num2;
            break;
        case '-':
            cout << num1-num2;
            break;
        case '*':
            cout << num1*num2;
            break;
        case '/':
            cout << num1/num2;
            break;
}


cout<<endl<<"Enter 'e' to exit or any other key to continue: ";
cin>>b;
if (b=='u')
{
      cout<<num1<<a<<num2<<"=";
      switch(j)
    {
        case '+':
            cout << num1+num2;
            break;
        case '-':
            cout << num1-num2;
            break;
        case '*':
            cout << num1*num2;
            break;
        case '/':
            cout << num1/num2;
            break;
     }
}
else if (b=='d')
{
      cout<<num1<<a<<num2;
     
}
else if (b=='s')
{
      switch(j)
    {
        case '+':
            cout << num1+num2;
            break;
        case '-':
            cout << num1-num2;
            break;
        case '*':
            cout << num1*num2;
            break;
        case '/':
            cout << num1/num2;
            break;
     }
}
}


while (b!='e');

cout<<"good bye"<<endl;
      return 0;
      }








      Task # 4: Traspose of Matrix
Write a program that can perform transpose of matrices entered by user. Transpose of a matrix means, changing row to column and column to row.




CODE:

#include <iostream>
using namespace std;
int main()
{
    int a[10][10], trans[10][10], r, c, i, j;
    cout << "Enter rows of matrix: ";
    cin >> r ;
    cout << "Enter columnc of matrix: ";
    cin >> c ;
    cout << endl << "Enter elements of matrix: " << endl;
    for(i = 0; i < r; ++i)
    for(j = 0; j < c; ++j)
    {
        cout << "Enter elements A" << i + 1 << j + 1 << ": ";
        cin >> a[i][j];
        trans[j][i]=a[i][j];
    }

    cout << endl << "Transpose of Matrix: " << endl;
    for(i = 0; i < c; ++i)
       {
                        for(j = 0; j < r; ++j)
        {
            cout << '\t' << trans[i][j];
            if(j == r - 1)
                cout << endl;
        }
    }
    return 0;
}


No comments:

Post a Comment

Functions & BASIC FILE I/O

A.    Files : For storage of data for later use, files are used. Files are stored on the Hard Disk Drive (HDD). There are two types of f...