# My Training Period: xx hours

This is a continuation from previous Module.  The source code for this module is: . The lab worksheets practice are: C/C++ array part 1, C/C++ array part 2, C/C++ 2D array part 1 and C/C++ 2D array part 2.

• # Able to understand and use array and string.

#### 1.3     Two-Dimensional Array Manipulation

• The following example prints the 3 x 3 array’s subscript and their element.

// printing 3x3 array's subscript and their element

#include  <iostream>

using namespace std;

#define  m  3

#define  n  3

int main()

{

int  i, j;

int  x[m][n]={{10,25,33}, {21,32,43},{20,42,51}};

cout<<"\n3x3 arrays' subscripts and\n";

cout<<"their respective elements\n";

cout<<"--------------------------\n";

// the outer for loop, reading the row by row...

for(i=0; i<m; i++)

// the inner loop, for every row, read every column by column...

for(j=0; j<n; j++)

cout<<"["<<i<<"]"<<"["<<j<<"]"<<"="<<x[i][j]<<"\n";

return 0;

}

#### Output: • The following program example illustrates the use of two-dimensional arrays.  This program calculates the average of all the elements in the integer array named x.  The program uses two nested for loops.

• The outer loop with index i provides the row subscript.  The nested for loops therefore accesses each element of the array and the inner loop with index j provides the column subscript.

// using two-dimensional array to compute the

// average of all the elements in array named x

#include  <iostream>

using namespace std;

#define   m  4

#define   n  5

int main()

{

int i, j, total = 0;

// a 4x5 or  array variable...

int q[m][n]={{4,5,6,2,12},{10,25,33,22,11},

{21,32,43,54,65},{3,2,1,5,6}};

float average;

// the outer for loop, read row by row...

for(i=0; i<m; i++)

// the inner for loop, for every row, read column by column

for(j=0; j<n; j++)

// the get the summation of the array elements.

{

// the display the array...

cout<<"q["<<i<<"]["<<j<<"] = "<<q[i][j]<<endl;

total=total + q[i][j];

}

// calculate the average, notice the simple typecast casted from int to float...

average = (float)total/(float) (m*n);

cout<<"\nThis program will calculate the average of the";

cout<<"\n4 x 5 array, which means the sum of the";

cout<<"\narray's element, divide the number of the";

cout<<"\narray's element....";

// display the average

cout<<"Average = "<<total<<"/"<<m*n<<endl;

cout<<"\nThe Average = "<<average<<endl;

return 0;

}

#### Output: • Study the program's source code and the output.

• The next example computes the square root of the sum of the squares of all the positive elements in array named x.  It uses the header file math.h since it contains the mathematical functions pow() (for taking the power of a number) and sqrt() (for taking the square root of a number).

// a program to compute the square root of the sum

// of the squares of all the elements in array x

#include <iostream>

using namespace std;

#include <cmath>

#define   m   4

#define   n   5

int main()

{

int i, j;

int x[m][n]={{4,5,6,2,12},{10,25,33,22,11}, {21,32,43,54,65},{3,2,1,5,6}};

float sum2, result;

// the outer for loop, read row by row...

for(i=0; i<m; i++)

{ // the inner for loop, for every row, read column by column

for(j=0; j<n; j++)

{ // set some condition here to avoid divides by 0...

if(x[i][j]>0)

// do the square of the array elements and then sum up...

sum2 = sum2 + pow(x[i][j], 2);

}

// assign the result to variable result, do the square root on the previous result....

result = sqrt(sum2);

}

// some story and printing the result...

cout<<"\nFirst, summing up all the arrays' element";

cout<<"\nThe given array has 4 x 5 in size,\n";

cout<<"\nThe sum is = "<<sum2;

cout<<"\nNext, square root the sum\n";

return 0

}

#### Output: • Study the program and the output.

• The following program example illustrates the use of three nested for loops.  The program multiplies matrix x and y and stores the resulting matrix product xy in matrix z.  Both x and y must be compatible for multiplication that means, the number of columns of x must be equal to the number of rows of y.

// a multiplication of the matrix x and matrix

// y and stores the result in matrix z

#include <iostream>

using namespace std;

#define  m  3

#define  c  2

#define  n  4

int main()

{

int i, j, k;

// first matrix...

int x[m][c] = {{1,2},{3,4},{5,6}};

// second matrix...

int y[c][n] = {{7,8,9,10},{11,12,13,14}};

// for storing the matrix product result...

int z[m][n];

for(i=0; i<m; i++)

for(j=0; j<n; j++)

{

z[i][j] = 0;

for(k=0; k<c; k++)

// same as z[i][j] = z[i][j] + x[i][k] * y[k][j];

z[i][j] += x[i][k] * y[k][j];

}

cout<<"\nMultiply matrix x and matrix y,";

cout<<"\nThen store the result in matrix z.";

cout<<"\nMatrix x is 3x2, and matrix y is 2x4,";

cout<<"\nso, the result, z should be matrix 3x4\n";

cout<<"\nThe matrix product is:  \n";

for (i=0; i<m; i++)

{

cout<<"\n";

for(j=0; j<n; j++)

// display the result...

cout<<"   "<<z[i][j];

}

cout<<endl;

return 0;

}

#### Output: • Study the program and the output.

#### 1.4     Multidimensional Arrays

• When an array has more than one dimension, we call it a multidimensional array.

• We have already looked at multidimensional arrays with two dimensions.  The declaration and manipulation of other multidimensional arrays in C/C++ are quite similar to that of the two dimensional array.

• The declaration takes the following form:

data_type    array_name[size1][size2]…[sizeN];

• For example:

int    y;

• Declares a 3-dimensional array with a depth of 4, 5 rows and 3 columns.

• The are no limitation on the dimension of the arrays, but the dimension more than two dimensional arrays are rarely used because of the complexity and code readability.

------------------------------o0o--------------------------------

---www.tenouk.com---

# More Working Program Examples

#### Example  #1

// compute the sum of the elements of an array

#include <stdio.h>

#define   SIZE  12

int main()

{

// declare and initialize the array named a with size SIZE

int a[SIZE] = {1,3,5,4,7,2,99,16,45,67,89,45};

// declare two normal variables

int i, total = 0;

// do the loop for the array...

for(i = 0; i <= (SIZE-1); i++)

{

// display the array and its element...

printf("\n a[%d]= %d", i, a[i]);

// total up the array

// total = total + a[i]

total += a[i];

}

printf("\nThe sum of the array elements is %d\n", total);

return  0;

}

#### Output: #### Example  #2

// printing a simple histogram

#include <stdio.h>

#define  SIZE   10

int main()

{

// declare and initialize an array named n with size SIZE...

int n[SIZE] = {19, 3, 15, 7, 11, 9, 13, 5, 17, 1};

int i, j;

printf("%s%13s%17s\n","Element/index", "Value", "Histogram");

// do the iteration...

// the outer for loop, read row by row...

for(i=0; i <= (SIZE-1); i++)

{

printf("%9d%15d       ", i, n[i]);

// the inner for loop, for every row, read column by column and print the bar...

for(j = 1; j<= n[i]; j++)

// print the asterisk bar...repeat...

printf("*");

// go to new line for new row...repeats...

printf("\n");

}

return   0;

}

#### Output: #### Example  #3

// sorting an array values into ascending order

#include <stdio.h>

#define  SIZE   10

int main()

{

int a[SIZE] = {34,6,41,58,0,12,89,-2,45,25};

int i, pass, hold;

printf("Data items in original order\n\n");

// displaying the original array...

for(i=0; i<=SIZE - 1; i++)

printf("%d  ", a[i]);

// ------do the sorting...ascending-------------

// for every array elements do this...

for(pass = 1; pass <= (SIZE-1); pass++)

// for every 2 array elements comparison do

// the comparison and swap...

for(i = 0; i <= (SIZE-2); i++)

// set the condition...

if(a[i] > a[i + 1])

{

// put the a[i] in temporary variable hold...

hold = a[i];

// put the a[i + 1] in a[i]

a[i] = a[i + 1];

// put the hold in a[i + 1], one swapping is

// completed...and repeat for other elements...

a[i + 1] = hold;

}

printf("\n\nData items in ascending order\n\n");

// display the new ordered list...

for (i=0; i <= (SIZE-1); i++)

printf("%4d", a[i]);

printf("\n\n");

return 0;

}

#### Output: • By changing the following code in the above program, recompile and re run the program.  You will get the descending order.

if(a[i] > a[i + 1]) to if(a[i] < a[i + 1])

• The following is the output. #### Example  #4

// initializing multidimensional arrays and function

#include <stdio.h>

// function prototype

void  printArray(int []);

int main()

{

// declare 3 array with initial values...

int  array1 = {{1,2,3}, {4,5,6}},

array2 = {{1,2,3},{4,5}},

array3 = {{1,2}, {4}};

printf("Element values in array1 by row are: \n");

// first time function call

printArray(array1);

printf("\nElement values in array2 by row are: \n");

// second time function call

printArray(array2);

printf("\nElement values in array3 by row are:\n");

// third time function call

printArray(array3);

printf("\nNOTICE THE DEFAULT VALUE 0...\n");

return 0;

}

// function definition, passing an array to function

void  printArray(int a[ ])

{

int i, j;

// the outer for loop, read row by row...

for(i = 0; i <= 1; i++)

{

// the inner for loop, for every row, read column by column...

for(j=0; j<= 2; j++)

{

printf("[%d][%d] = %d ", i, j, a[i][j]);

}

printf("\n");

}

}

#### Output: #### Example  #5

// a program will sort a list of strings entered by the user

#include <iostream>

using namespace std;

#include <cstring>

int main()

{

// declare two arrays named tname with 1-Dimension

// and name with 2-Dimension

char  tname, name;

// normal variables...

int   i, j, n;

cout<<"Enter the number of names:  ";

cin>>n;

// outer loop for counter...

for(i=0; i<n; i++)

{

cout<<"\nEnter the name(one word) "<<(i+1)<<": ";

cin>>name[i];

}

// inner for loop, read row by row set outer for loop...

for(i=0; i<n-1; i++)

// innermost for loop, read column by column of the characters...

for(j = i+1; j<n; j++)

// set the condition...

// strcmp - compare the string standard library function

// do the sorting...

if(strcmp(name[i], name[j])>0)

{

// strcpy - copy the strings...

// compare and swap...

strcpy(tname, name[i]);

strcpy(name[i], name[j]);

strcpy(name[j], tname);

}

cout<<"\nSorted names:\n";

for (i =0; i<n; i++)

cout<<"\n"<<name[i];

cout<<endl;

return 0;

}

#### Sample output: // sorting array values into ascending order

#include <cstdio>

#define  SIZE   10

int main()

{

int a[SIZE] = {-4,6,3,-20,0,1,77,-2,42,-10};

int i, pass, hold;

printf("Data items in original order\n\n");

// displaying the original array...

for(i=0; i<=SIZE - 1; i++)

printf("%d  ", a[i]);

// ------do the sorting...ascending-------------

// for every array elements do this...

for(pass = 1; pass <= (SIZE-1); pass++)

// for every 2 array elements comparison do

// the comparison and swap...

for(i = 0; i <= (SIZE-2); i++)

// set the condition...

if(a[i] > a[i + 1])

{

// put the a[i] in temporary variable hold...

hold = a[i];

// put the a[i + 1] in a[i]

a[i] = a[i + 1];

// put the hold in a[i + 1], one swapping is

// completed...and repeats for other elements...

a[i + 1] = hold;

}

printf("\n\nData items in ascending order\n\n");

// display the new ordered list...

for(i=0; i <= (SIZE-1); i++)

printf("%4d", a[i]);

printf("\n\n");

return 0;

}

#### Output: In C++, you can use member functions, operators, and classes etc. of the template based header file of the Standard Template Library (STL).  It is designed for performing high-speed mathematical operations, and optimized for computational performance. The class is a one-dimensional smart array that checks subscript references at run time to confirm that they are in bound. Also, in C++ many array constructs and manipulations accomplished using routines in Standard Template Library (STL). Take care also when you use arrays as buffers for storing strings (NULL terminated).  Many standard functions for string operations such as strcpy() do not do the bound checking.  This will result a buffer overflow. For example, consider the following program:

#include <stdio.h>

// for exit() function

#include <stdlib.h>

#include <string.h>

int main(int argc, char *argv[ ])

{

// reserve 5 byte of buffer....

// should allocate 8 bytes = 2 double words,

// to overflow, need more than 8 bytes...

// so, if more than 8 characters input by user,

// there will be access violation, segmentation fault etc

char mybuffer;

// a prompt how to execute the program...

if(argc < 2)

{

printf("strcpy() NOT executed....\n");

printf("Syntax: %s <characters>\n", argv);

exit(0);

}

// copy the user input to mybuffer...

strcpy(mybuffer, argv);

printf("mybuffer content= %s\n", mybuffer);

printf("strcpy() executed...\n");

return 0;

}

• The output, when the input is: 12345678 (8 bytes), the program run smoothly. • When the input is: 123456789 (9 bytes), the following application error message box will be displayed when compiled with Microsoft Visual C++ 6.0.  In Linux the “Segmentation fault” message will be displayed and the program terminates. • or something like the following message for newer compiler(s). • The vulnerability exist because the mybuffer could be overflowed if the user input (argv) bigger than 8 bytes. Why 8 bytes?  For 32 bit (4 bytes) system, we must fill up a double word (32 bits) memory (however this still depend on the C/C++ standard versions and/or platform used).

• Character (char) size is 1 byte, so if we request buffer with 5 bytes, the system will allocate 2 double words (8 bytes).  That is why when you input more than 8 bytes, the mybuffer will be overflowed!

• The system tries to write beyond the allocated storage (memory) which may be occupied by other important data.

• You may use safer type functions or insert some codes that do the bound checking manually.

• In real world, the buffer overflow vulnerabilities have been widely exploited by viruses, worms and malicious codes.

• However, newer compilers such as Visual C++ 2005, there are new secure versions of the vulnerable functions such as string manipulation have been introduced. For example printf_s(), scanf_s(), strcpy_s(), strcmp_s() etc. solving some of the mentioned problems. You will receive something like the following warning with a meaningful suggestion if the older code compiled using newer compilers:

1>c:\buffalo\buffalo\buffalo.cpp(20) : warning C4996: 'strcpy' was declared deprecated

1> c:\program files\microsoft visual studio 8\vc\include\string.h(73) : see declaration of 'strcpy'

1> Message: 'This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See online help for details.'

• As a final note for this Module, the following are previous program examples compiled using gcc.

/************array3.c**************/

/* a program to find the smallest number in an */

/* array named balance simple search function */

#include <stdio.h>

#define n  7

int main()

{

int i;

int small, balance[n];

/**loop for displaying array content....*/

for(i=0; i<=n; i++)

{

printf("Key in float value, let me ... for you: ");

scanf("%d", &balance[i]);

}

/* printing the element... */

for(i=0; i<=n; i++)

printf("%d ", balance[i]);

small = balance;

/*Another loop do the array element comparing...*/

for(i=1; i<=n; i++)        /*check until i=n*/

{

if(small > balance[i])

small = balance[i];

}

printf("\nComparing...");

/* display the result... */

printf("The smallest value in the given array is = %d \n", small);

return 0;

}

[bodo@bakawali ~]\$ gcc array3.c -o array3

[bodo@bakawali ~]\$ ./array3

Key in float value, let me ... for you: 12

Key in float value, let me ... for you: -21

Key in float value, let me ... for you: 4

Key in float value, let me ... for you: -3

Key in float value, let me ... for you: 0

Key in float value, let me ... for you: 7

Key in float value, let me ... for you: -41

Key in float value, let me ... for you: 3

12 -21 4 -3 0 7 -41 3

Comparing...The smallest value in the given array is = -41

/************array1.c*****************/

/* a simple sorting program that sort a list of n */

/* integer numbers, entered by the user (ascending) */

#include  <stdio.h>

#define   maxsize   100

int main()

{

int temp, i, j, n, list[maxsize];

printf("\n--You are prompted to enter your list size.--");

printf("\n--Then, for your list size, you are prompted to enter--");

printf("\n--Finally your list will be sorted ascending--\n");

/* get the list size... */

scanf(" %d", &n);

/* prompting the data from user store in the list... */

for(i=0; i<n; i++)

{

printf("Enter list's element #%d -->", i);

scanf("%d", &list[i]);

}

// do the sorting...

for(i=0; i<n-1; i++)

for(j=i+1; j<n; j++)

if(list[i] > list[j])

{

/* These three lines swap the elements */

/* list[i] and list[j]. */

temp = list[i];

list[i] = list[j];

list[j] = temp;

}

printf("\nSorted list, ascending:  ");

for(i=0; i<n; i++)

printf("  %d", list[i]);

printf("\n");

return   0;

}

[bodo@bakawali ~]\$ gcc array1.c -o array1

[bodo@bakawali ~]\$ ./array1

--You are prompted to enter your list size.--

--Then, for your list size, you are prompted to enter--

--Finally your list will be sorted ascending--

Enter list's element #0 -->23

Enter list's element #1 -->14

Enter list's element #2 -->-21

Enter list's element #3 -->-30

Enter list's element #4 -->34

Enter list's element #5 -->25

Enter list's element #6 -->12

Enter list's element #7 -->99

Enter list's element #8 -->100

Enter list's element #9 -->73

Sorted list, ascending:    -30  -21  12  14  23  25  34  73  99  100

/* *********************array2.c******************* */

/* printing 3x3 array's subscript and their element */

#include <stdio.h>

#define m  3

#define n  3

int main()

{

int i, j;

int x[m][n];

printf("\n3x3 arrays' subscripts and\n");

printf("their respective elements\n");

printf("--------------------------\n");

for(i=0; i<m; i++)

for(j=0; j<n; j++)

{

printf("Enter int values for ur array lol!: ");

scanf("%d", &x[i][j]);

}

/* outer for loop, reading the row by row... */

for(i=0; i<m; i++)

/* inner loop, for every row, read every column by column... */

for(j=0; j<n; j++)

printf("x[%d][%d] = %d\n", i, j, x[i][j]);

return 0;

}

[bodo@bakawali ~]\$ gcc array2.c -o array2

[bodo@bakawali ~]\$ ./array2

3x3 arrays' subscripts and

their respective elements

--------------------------

Enter int values for ur array lol!: 12

Enter int values for ur array lol!: 31

Enter int values for ur array lol!: 45

Enter int values for ur array lol!: -20

Enter int values for ur array lol!: 24

Enter int values for ur array lol!: -10

Enter int values for ur array lol!: 9

Enter int values for ur array lol!: -71

Enter int values for ur array lol!: 42

x = 12

x = 31

x = 45

x = -20

x = 24

x = -10

x = 9

x = -71

x = 42

#### Further C and C++ array related reading and digging:

1. Check the best selling C / C++ books at Amazon.com.
2. The source code for this module is: .
3. The lab worksheets practice are: C/C++ array part 1, C/C++ array part 2, C/C++ 2D array part 1 and C/C++ 2D array part 2.