|< C & C++ Program Controls 2 | Main | C & C++ Arrays 2 >| Site Index | Download |


 

 

 

 

 

MODULE 7

THE C & C++ ARRAY PROGRAMMING 1

 

 

 

 

 

 

 

 

My Training Period: xx hours

 

Array is another important topic in C and C++. 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++ programming skills:

 

  • Able to understand, use and create an array.

  • Able to understand and use array and function.

  • Able to understand and use array, function and a pointer.

  • Able to understand and use array and string.

 

2.1       Introduction And Definition

  • Up till this Module we were introduced with simple data types that suit to simple applications.  For aggregated data, with same type of element we can use Array.

  • An array in C / C++ is a collection of related data elements of the same type that are referenced by a common name.  Generally, it is just another data type, aggregate data type.

  • All the elements of an array occupy a set of contiguous memory locations and by using an index or subscript we can identify each element.

  • For example, instead of declaring mark1, mark2, ..., markN to store and manipulate a set of marks obtained by the students in certain courses, we could declare a single array variable named mark and use an index, such as j, to refer to each element in mark.  This absolutely has simplified our declaration of the variables.

  • Hence, mark[ j ] would refer to the jth element in the array mark.  Thus by changing the value of j, we could refer to any element in the array, so it simplifies our declaration.

  • For example, if we have 100 list of marks of integer type, we will declare it as follows:

int  mark1, mark2, mark3, ..., mark100;

  • If we have 100 marks to be stored, you can imagine how long we have to write the declaration part by using normal variable declaration?

  • By using an array, we just declare like this:

int  mark[100];

  • This will reserve 100 contiguous/sequential memory locations for storing the integer data type.

  • Graphically can be depicted as follows:

C C++ array illustration

7.2    One Dimensional Array: Declaration

array_element_data_type    array_name[array_size];

char   character[20];

C/C++ array illustration of memory

int        x[20], y[50];

float     price[10], yield;

char     letter[70];

 

 

 

 

 

 

 

 

 

 

 

 

 

 

7.3    Array Initialization

type   array_name[size] = {value_list};

int    id[7] = {1, 2, 3, 4, 5, 6, 7};

float  x[5] = {5.6, 5.7, 5.8, 5.9, 6.1};

char   vowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};

char    array_name[size] = "string_lateral_constant";

char    vowel[6] = "aeiou";

1.1       Array And Function: Passing One Dimensional Arrays To Function

  1. A pointer.

  2. A sized array (dimension is explicitly stated), e.g. s[20] or

  3. An unsized array (dimension is not stated), e.g. p[ ].

// pointers, will be explained in another Module

int    myfunction(float *x)

// sized array

char    yourfunction(float x[5])

// unsized array

void    ourfunction(float x[ ])

// function prototype

void func(float *);

                       

int main()

{

      float x[5];

      // an array name (without the bracket) is

      // the pointer to the first array element

      func(x);

      return 0;

}

 

// function definition

void func(float *pter)

{ return; }

 

1.2       Array Manipulation:  How to use an array and what array can do?

 

1.2.1           Accessing Array’s Element

// a program to find the total of all the elements in array y

#include  <iostream>

using namespace std;

// replace every n occurrences with 7

#define  n  7

 

int main()

{

     int i, total = 0, y[n] = {6,9,2,4,5,23,12};

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

     {

            // display the array contents...

            cout<<y[i]<<" ";

            // do the summing up...

            total = total + y[i];

     }

     // display the result...

     cout<<"\nSum of 7 numbers in an array is = "<<total<<endl;

     return 0;

}

 

Output:

 

C/C++ total element in array example

 

int    get_total(int*, int)

// a program to find the total values of an

// array y by passing an array to a function using pointer

#include <iostream>

using namespace std;

#define  n  7

 

// function prototype

int get_total(int*, int);

 

int main()

{

     int  total,  y[n]={6,9,2,4,5,23,12};

     cout<<"\nCalling function get_total(y, n),";

     cout<<"\nBy bringing along the value of y, an array";

     cout<<"\nfirst address and n = 7, an array size.";

     cout<<"\nAn array name, is the pointer to the";

     cout<<"\n1st element of an array\n\n";

     // a function call, pass along the pointer to the first

     // array element and the array size, and the

     // return result assign to variable total

     total = get_total(y, n);

     cout<<"\nSum of the 7 array elements is "<<total<<endl;

     return 0;

}

               

// function definition

int get_total(int *ptr, int x)

{

     int  i, total = 0;

     // do the looping for array elements...

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

     {

            // displays the array content, pointed by pointer...

            cout<<*(ptr+i)<<" ";

            // do the summing up of the array elements...

            total += *(ptr+i);  // total=total + *(ptr+i);

     }

     // return the result to the calling program...

     return total;

}

 

Output:

 

C C++ passing array to function example

 

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

// **********gccarray.C or gccarray.cpp************

// ************FeDoRa 3, g++ x.x.x**********

// a program to find the total values of an

// array y by passing an array to a function using pointer

#include <iostream>

#define  n  7

using namespace std;

 

// a function prototype

int  get_total(int*, int);

 

int main()

{

        int  total,  y[n]={6,9,2,4,5,23,12};

        cout<<"\nCalling function get_total(y, n),";

        cout<<"\nBy bringing along the value of y, an array";

        cout<<"\nfirst address and n = 7, an array size.";

        cout<<"\nAn array name, is the pointer to the";

        cout<<"\n1st element of an array\n\n";

        // function call, pass along the pointer to the first

        // array element and the array size, and the

        // return result assign to variable total

        total = get_total(y, n);

        cout<<"\nSum of the 7 array elements is "<<total<<endl;

        return 0;

}

 

// a function definition

int get_total(int *ptr, int x)

{

        int  i, total = 0;

        // do the looping for array elements...

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

        {

                // displays the array content, pointed by pointer...

                cout<<*(ptr+i)<<" ";

                // do the summing up of the array elements...

                total += *(ptr+i);  //total=total + *(ptr+i);

        }

        // return the result to the calling program...

        return total;

}

 

[bodo@bakawali ~]$ g++ gccarray.C -o gccarray

[bodo@bakawali ~]$ ./gccarray

 

Calling function get_total(y, n),

By bringing along the value of y, an array

first address and n = 7, an array size.

An array name, is the pointer to the

1st element of an array

 

6 9 2 4 5 23 12

Sum of the 7 array elements is 61

[bodo@bakawali ~]$

 

7.5.2    Searching For A Value

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

// named balance, a very simple search function

#include <iostream>

using namespace std;

#define  n  10

 

int main()

{

     int i;

     float  small, balance[n]={100.00,40.00,-30.00,400.00,60.00,-25.00,-24.00,0.00,3.24,0.50};

     small = balance[0];

     // loop for displaying array content....

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

         cout<<balance[i]<<" ";

     // another loop do the array element comparing...

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

     {

            if(small > balance[i])

                small = balance[i];

    }

     cout<<"\nSearching..."<<endl;

     // display the result...

     cout<<"The smallest value in the given array is = "<<small<<endl;

     return  0;

}

 

Output:

 

C C++ array find smallest number example

 

1.1.1           Exchanging Values of Variables

// assign num1 to third_var

third_var = num1;

// then assigns num2 to num1

num1 = num2;

// finally assigns third_var to num2

num2 = third_var;

C/C++ array exchanging value swapping example

1.1.2           Sorting Variables

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

// integer numbers, entered by the user, ascendingly

#include  <iostream>

using namespace std;

#define   maxsize   100

 

int main()

{

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

     cout<<"\n--You are prompted to enter your list size.--";

     cout<<"\n--Then, for your list size, you are prompted to enter--";

     cout<<"\n--the element of your list.--";

     cout<<"\n--Finally your list will be sorted ascending!!!--\n";

     // get the list size...

     cout<<"\nEnter your list size: ";

     cin>>n;

     // prompting the data from user and store it in the list...

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

     {

            cout<<"Enter list's element #"<<i<<"-->";

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

                }

     cout<<"\nSorted list, ascending:  ";

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

            cout<<" "<<list[i];

    cout<<endl;

                   return 0;

}

 

Output:

 

C/C++ array sorting ascending descending example

 

 

1.2     Two Dimensional/2D Arrays

data_type    array_name[1st dimension size][2nd dimension size];

int        x[3][4];

float    matrix[20][25];

C C++ two dimensional array row column example

For n rows and m columns, the total size equal to mn

// a 2D array that can store 4 names, each is 10 characters long

char    name[4][10];

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

C C++ two dimensional array assign value example

x[0][0]=1       x[0][1]=2      x[0][2]=3     x[0][3]=4

x[1][0]=5       x[1][1]=6      x[1][2]=7     x[1][3]=8

x[2][0]=9       x[2][1]=10     x[2][2]=11    x[2][3]=12

int  x[3][4] = {{1,2,3,4},

         {5,6,7,8},

         {9,10,11,12}

         };

C C++ two dimensional array assign value example

C/C++ two dimensional array assign initial value example

// all array elements will be 0

int   x[3][4]={0};

char   name[4][10] = {"Sally", "Joyce", "Lisa", "Alice"};

name[0] = "Sally"       name[1] = "Joyce"

name[2] = "Lisa"        name[3] = "Alice"

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

 

Further C/C++ related reading:

 

  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++ Program Controls 2 | Main | C & C++ Arrays 2 >| Site Index | Download |


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