This is a continuation from previous Module. The source code for this module is: C/C++ array source codes. 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.
|
|
1.3 Two-Dimensional Array Manipulation
// 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:
|
// 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 [4][5] 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....";
cout<<"\nProcessing.... PLEASE WAIT\n";
// display the average
cout<<"Average = "<<total<<"/"<<m*n<<endl;
cout<<"\nThe Average = "<<average<<endl;
return 0;
}

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";
cout<<"\nThe answer is = "<<result<<"\n";
return 0
}

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

Study the program and the output.
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[4][5][3];
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---
// 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;
}

-----------------------------------------------------------------------------------------------------------------------
// 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;
// display the table header...
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;
}

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

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.

// initializing multidimensional arrays and function
#include <stdio.h>
// function prototype
void printArray(int [][3]);
int main()
{
// declare 3 array with initial values...
int array1[2][3] = {{1,2,3}, {4,5,6}},
array2[2][3] = {{1,2,3},{4,5}},
array3[2][3] = {{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[ ][3])
{
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");
}
}

// 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[20], name[20][20];
// 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;
}
-------------------------------------------------------------------------------------------------

// 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;
}
|
|
|
#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[5];
// a prompt how to execute the program...
if(argc < 2)
{
printf("strcpy() NOT executed....\n");
printf("Syntax: %s <characters>\n", argv[0]);
exit(0);
}
// copy the user input to mybuffer...
strcpy(mybuffer, argv[1]);