You are on page 1of 4

ES085 (Computer Programming 2)

Week 4 Topic: C Array



At the end of the lesson the students should be able to:
1. explain the definition of an array,
2. declare single-dimensional arrays of different data types in a program, and
3. explore different ways to initialize, store, and manipulate data into arrays.
Array
An array is a collection of the same type of elements under the same variable identifier referenced by
index number. Arrays are widely used within programming for different purposes such as sorting,
searching, etc. All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element as shown in the figure below.

Syntax of array declaration (single-dimensional)


data_type array_name[size];
where:
data_type – valid C data type
array_name – any user-defined identifier
size – number of elements in the array
Example: int num[5]; float weight[30];
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows:
float weight[5] = {45, 32.3, 42.1, 25.7, 53.67};
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. 
float weight[] = {45, 32.3, 42.1, 25.7, 53.67, 3.21}; //The size of the array is 6.

To refer to an element, specify an array name and position number.


Format:
arrayname [ position number ]
• First element at position 0 (must always be put in mind)
Examples:
Which1. n element array named c:
c[ 0 ], c[ 1 ]...c[ n – 1 ]
2.
C statements:
num[0] = -45;
num[1] = 2;
num[2] = 4;
num[3] = 72;
num[4] = 1;


Arrays and Loops
One of the nice things about arrays is that you can use a loop to manipulate each element. When an array
is declared, the value of each element is not set to 0 automatically.


Sample Program 1: Store 5 integers entered by the user to an array using a loop statement.


 Sample Output:
Sample Program 2: Write a C program that will accept integers and display the sum and average.

Sample Output:


 Practice 1: Key in the following code. Compare the output to the output of Sample Program 2.
What are your observations?

You might also like