# 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 ];

• Traversal
• Insertion
• Deletion
• Searching
• Sorting

types of arrays

##### One-Dimensional Arrays

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

##### Multi-Dimensional Arrays

Two-Dimensional Arrays

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;

}

Scroll to Top