Array List and its Operations

Array List and its Operations

Array

  • Same type of elements at contiguous location
  • Same name and type

To refer to an element, specify

  • Array name and position number

Name of array (Note that all elements of this array have the same name, c)

Format: arrayname[ position number ]

  • First element at position 0
  • n element array c:

             c[ 0 ], c[ 1 ]c[ n – 1 ]

Array elements are like normal variables

             c[ 0 ] =  3;

             cout << c[ 0 ];

Performing operations in subscript. If x = 3,

        c[ 5 – 2 ]

        or c[ 3 ]

       Or c[ x ]

Size of an Array

  • Total size of an array in bytes?
  • Total bytes = number of bytes in type x number of elements
  • e.g. int sample[10];

Declaring Arrays 

Declaring arrays – specify:

  • Name
  • Type of array
  • Number of elements

               int c[ 10 ]; 

              float hi[ 3284 ];

Declaring multiple arrays of same type

  • Similar format as other variables

              int b[ 100 ], x[ 27 ];

What Operations Can You Perform on an Array?
  • Traversal
  • Insertion
  • Deletion
  • Searching
  • Sorting
Types of Arrays.

types of arrays

One-Dimensional Arrays

Arrays_in_ds-array-type-1d-img1

You can imagine a 1d array as a row, where elements are stored one after another.

Multi-Dimensional Arrays

Two-Dimensional Arrays

Arrays_in_ds-array-type-2d-img1

Getting Values

int MyArray[5];

cin>>MyArray[0];

cin>>MyArray[1] ;

cin>>MyArray[2] ;

cin>>MyArray[3] ;

cin>>MyArray[4] ;

  • Or

for(int i = 0; i < 5; i++)

cin>>MyArray[i];

Examples Using Arrays

Initializers

         int n[ 5 ] = { 1, 2, 3, 4, 5 };

  • If not enough initializers, rightmost elements become 0
  • If too many initializers, a syntax error is generated
  •        int n[ 5 ] = { 0 };     Sets all the elements to 0

If size omitted, the initializers determine it

              int n[] = { 1, 2, 3, 4, 5 };

  • 5 initializers, therefore n is a 5 element array

Arrays 

int a[10], b[10];

// …

a = b; // error – illegal

for(int i = 0; i < 10; i++)

a[i] = b[i];  //legal

Write a program to input an array of size 10 from the user and

  • Find and print the minimum value in array
  • Find and print the maximum value in array

Finding Minimum and Maximum

int main()

{

int i, min_value, max_value, list[10];

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

cin>>list[i];

// find minimum value

min_value = list[0];

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

if(min_value>list[i]) min_value = list[i];

cout << “\nminimum value: ” << min_value << ‘\n’;

// find maximum value

max_value = list[0];

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

if(max_value<list[i]) max_value = list[i];

cout << “maximum value: ” <<  max_value << ‘\n’;

return 0;

}

 

Search within CuiTutorial

Scroll to Top