|< C & C++ Arrays 1 | Main | C & C++ Pointers 1 >| Site Index | Download |


 

 

 

 

 

 

MODULE 7a

MORE ON C & C++ ARRAY 2

 

 

 

 

 

 

My Training Period: xx hours

 

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.

 

The C and C++ array programming abilities that should be acquired:

 

 

 

 

 

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:

 

C C++ two dimensional array output snapshots example

  • 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 [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;

}

 

Output:

 

C C++ two dimensional array comparing values output snapshots example

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

                        }

 

Output:

 

C C++ array product or sum of element output snapshots example

// 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:

 

C C++ two dimensional array matric output snapshots example

1.4     Multidimensional Arrays

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

int    y[4][5][3];

------------------------------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:

 

C/C++ array sum of element output snapshots example

 

 

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;

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

}

 

Output:

 

C/C++ array printing histogram output snapshots example

 

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:

 

C/C++ array sorting ascending descending output snapshots example

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

C/C++ array sorting ascending descending output snapshots example

 

Example  #4

 

// 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");

       }

}

 

Output:

 

C C++ multi dimensional array initialization output snapshots example

 

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

}

 

Sample output:

 

C C++ array sorting a string output snapshots example

// 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:

C C++ array sorting Visual C++ . Net output snapshots example

  • In C++, you can use member functions, operators, and classes etc. of the <valarrary> 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[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]);

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

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

       return 0;

}

C C++ array buffer overflow output snapshots example

C C++ array buffer overflow

The C array type buffer overflow warning/error message when compiled using Visual studio and run on Windows

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.'

/************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[0];

    /*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--the element of your list.--");

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

    

    /* get the list size... */

    printf("\nEnter your 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--

--the element of your list.--

--Finally your list will be sorted ascending--

 

Enter your list size: 10

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[0][0] = 12

x[0][1] = 31

x[0][2] = 45

x[1][0] = -20

x[1][1] = 24

x[1][2] = -10

x[2][0] = 9

x[2][1] = -71

x[2][2] = 42

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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: C/C++ array source codes.
  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.

 

 

 

 

 

 

 

 

|< C & C++ Arrays 1 | Main | C & C++ Pointers 1 >| Site Index | Download |


C and C++ Array:  Part 1 | Part 2 |