Introduction of Array
Introduction of Array
Ahmedabad
Computer Department
1
Unit 6
Introduction of Array (one dimensional)
2
Topics and Sub-topics
• Array Terminology
• A characteristics of an array
• Array Declaration
• Array initialization
• Accessing an array
• Storing value in an array (Bubble Sort)
3
Array Terminology
• An array is used to store a collection of variables of the same type.
• Instead of declaring individual variables, such as number0, number1, ...,
and number99, you declare one array variable such as numbers and use
numbers[0], numbers[1], and ..., numbers[99] to represent individual
variables.
• A specific element in an array is accessed by an index.
• All arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last element.
4
A characteristics of an array
1. An array holds elements that have the same data type.
2. Array elements are stored in subsequent memory locations.
3. Size of the array must be declared at the time of declaring an
array.
4. Array name represents the address of the starting element.
5. Once we declare the size of an array it can not be changed at
run time.
6. Index of an array always starts with 0.
5
Array Declaration
• To declare an array in C, a programmer specifies the type of the
elements and the number of elements required by an array as follows
• type arrayName [ arraySize ];
• This is called a single-dimensional array.
• The arraySize must be an integer constant greater than zero
and type can be any valid C data type.
• For example, to declare a 10-element array called balance of type
double
• double balance[2][2];
• Here balance is a variable array which is sufficient to hold up to 10
double numbers.
6
Array initialization
• Initialize an array in C either one by one or using a single statement as
follows
• double balance[5][5]= {1000.0, 2.0, 3.4, 7.0, 50.0};
• The number of values between braces { } cannot be larger than the number
of elements that we declare for the array between square brackets [ ].
• If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write
• double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
• balance[4] = 50.0;
• The above statement assigns the 5th element in the array with a value of
50.0.
• All arrays have 0 as the index of their first element which is also called the
base index and the last index of an array will be total size of the array
minus 1.
7
Accessing an array
• An element is accessed by indexing the array
name.
• This is done by placing the index of the element
within square brackets after the name of the array.
• For example
• double salary = balance[3][2];
• The above statement will take the 10th element
from the array and assign the value to salary
variable.
8
Thank You