0% found this document useful (0 votes)
239 views8 pages

Arrays in C

The document discusses arrays in computer programming. It explains that arrays allow storing multiple values of the same type in contiguous memory locations that can be individually accessed via indices. The document provides details on declaring and defining arrays, initializing array elements, accessing elements, and storing values in arrays. It also discusses using loops to process array elements and gives examples of one-dimensional arrays of different data types including integers, characters, and strings.

Uploaded by

Nicky Ackerman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
239 views8 pages

Arrays in C

The document discusses arrays in computer programming. It explains that arrays allow storing multiple values of the same type in contiguous memory locations that can be individually accessed via indices. The document provides details on declaring and defining arrays, initializing array elements, accessing elements, and storing values in arrays. It also discusses using loops to process array elements and gives examples of one-dimensional arrays of different data types including integers, characters, and strings.

Uploaded by

Nicky Ackerman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

COMP 20023 - Computer Programming 1 ARRAY

ARRAY CONCEPTS

Imagine we have problem that requires 20 integers to be processed.


We need to read them, process them, and print them. We must also
keep these 20 integers in memory for the duration of the program.
We can declare and define 20 variables, each with a different name.

But having 20 different names creates another problem. How can we


read 20 integers from the keyboard and store them? To read 20
integers from the keyboard, we need twenty references, each to one
variable. Furthermore, once we have them in memory, how can we
print them? To print them, we need another twenty references.

Although this may be acceptable for 20 integers, it is definitely


not acceptable for 200 or 2000 or 20000 integers. To process larger
amounts of data we need a powerful data structure, such as array.

Characteristics of an Array

An array is a fixed-sized, sequenced collection of elements of the


same data type.

An array is a sequence of data items that are the same type, that
are indexable, and that are stored contiguously.

Arrays are data type that is used to represent a large number of


homogenous values.

Since an array is sequenced collection, we can refer to the


elements in the array as the first element, the second element,
and so forth until we get to the last element. If we were to put
our twenty numbers into an array, we could designate the first
element as: Number0

In similar fashion, we could refer to the second number as Number1,


and the third number as Number2. Continuing the series, the last
number would be Number19.

Process twenty variables

Number0 Number1 … Numbern-1

What we have seen is that the elements of the array are


individually addressed through their subscripts. This concept is
graphically shown in the next figure to be presented. The array as
a whole has a name, numbers, but each member can be accessed
individually using subscript.
COMP 20023 - Computer Programming 1 ARRAY

The advantages of the array would be limited if we didn’t also


have programming constructs that would allow us to process the
data more conveniently. Fortunately, there is a powerful set of
programming constructs – loops – that make array processing easy.

Number0 Number[0]

Number1 Number[1]
. .
. .
. .

Number19 Number[19]

Subscript Form Index Form

An array of numbers

We can use loops to read and write the elements in an array. We


can use loops to add, subtract, multiply and divide the elements.
We can also use loops for more complex processing such as
calculating averages.

But one question still remains. How can we write and instruction
so that at one time it refers to the first element of an array,
and the next time it refers to another element? It is really quite
simple: we simply borrow from the subscript concept we have been
using.

Rather than using subscripts, however, we will place the subscript


value in square brackets. Using this notation, we would refer to
Number0 as: Number[0]

Following the convention, Number1 becomes Number[1] and Number19


becomes Number[19]. This is known as indexing. Using reference, we
now refer to our array using the variable i: Number[i]

USING ARRAYS IN C

We will first show to declare and define arrays. Then we will look
at several typical applications using arrays including reading
COMP 20023 - Computer Programming 1 ARRAY
values into arrays, accessing and exchanging elements in arrays,
and printing arrays.

Declaration and Definition

An array must be declared and defined before it can be used.


Declaration and definition tell the compiler the name of the array,
the type of each element, and the size or number of elements in
the array. The size of the array is a constant and must have a
value at compilation time.

#include <stdio.h>
int scores[20], i, sum = 0;

main()

{
printf(“Please enter 20 scores: \n”);
for(i = 0; i < 20; i++)
{
scanf(“%d”, &scores[i]);
sum = sum + scores[i];
}

Declaring and Defining Arrays

An array is defined in much the same manner as ordinary variables,


except that each array name must be accompanied by a size
specification (the number of elements). For one dimensional array,
the size is specified by a positive integer expression enclosed in
square brackets. The expression is usually written as a positive
integer constant.

The General Form – One-Dimensional Array

data-type array[expression];

where data-type is the array data type (int, float, char, double),
array is the array name and expression is the positive-valued
integer expression that indicates the number of array elements.
COMP 20023 - Computer Programming 1 ARRAY
Example of one-dimensional array definition or array declaration:

int ccmit[5];
char bscs[30];
float bsit[20];
double ITCS[12];

the first line indicates that ccmit is a 5-element integer array,


the second line describes that bscs is a 30-element character
array. In line 3, bsit is defined as 20-element floating point
array and the last line, ITCS is a 12-element double array.

Consider the following array definition:

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


float y[5] = {1.0, 1.25, 1.5};

The result on an element by element basis are:

x[0] = 1 y[0] = 1.0

x[1] = 2 y[1] = 1.25

x[2] = 3 y[2] = 1.5

x[3] = 0 y[3] = 0

y[4] = 0

In each case, all of the array elements are automatically set to


zero except those that have been explicitly initialized within the
array definition.

One dimensional array string data type – a character in a string


can be accessed either as an element in an array by making use of
a pointing to character. The flexibility it provides makes C
especially useful in writing string processing programs. The
standard library provides many useful string handling functions.

Strings are handled somewhat differently. In particular, when a


string constant is assigned to an external or a static character
array as part of the array definition, the array size specification
is usually omitted. The proper array size will be assigned
automatically. This will include a provision for the null character
which is ‘\0’ and automatically added at the end of every string.
COMP 20023 - Computer Programming 1 ARRAY
Example:

Consider the character array definition. It includes an initial


assignment of the string constant “CCMIT”.

char college[6] = “CCMIT”;

It defines the following five element character array:

college[0] = ‘C’;
college[1] = ‘C’;
college[2] = ‘M’;
college[3] = ‘I’;
college[4] = ‘T’;
college[5] = ‘\0’;

The array definition could have been written as:

char college[] = “CCMIT”;

Accessing Elements in Array

C uses an index to access individual elements in an array. The


index must be an integral value or an expression that evaluates to
an integral value. The simplest form for accessing an element is
a numeric constant. For example, given an array scores[20], we
could access the first element as follows:

score[0]

Typically, however, the index is a variable or an expression. To


process all the elements in scores, a loop similar to the following
code is used:

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


scores[i]…;

You might be wondering how C know where an individual element is


located in memory. In scores, for example, there are ten elements.
How does it find just one? The answer is simple. The array’s name
is a symbolic reference for the address to the first byte of the
array. Whenever we use the array’s name, therefore, we are actually
referring to the first byte of the array. The index represents an
offset from the beginning of the array to the element being
referred to. With these two pieces of data, C can calculate the
COMP 20023 - Computer Programming 1 ARRAY
address of any element in the array using the following simple
formula:

Element address = array address + (sizeof(element) * index

For example, assume that scores is stored in memory at location


10,000. Since scores is an integer, the size of one element is the
size of an integer. Assuming an integer size of two, the address
of the element at index 3 is:

element address = 10,000 + 2 * 3 = 10,006

Storing Values in Array

Declaration and definition only reserve space for the elements in


the array. No values will be stored. If we want to store values in
the array, we must either initialize the elements, read values
from the keyboard, or assign values to each individual element.

Initialization

Initialization of all elements in an array can be done at the time


of declaration and definition, just as with variables. For each
element in the array we provide a value. The only deference is
that the values must be enclosed in braces and, if there are more
than one, separated by commas. It is a compile error to specify
more values than there are elements in the array. The initial
values must appear on the order in which they will be assigned to
the individual array elements, enclosed in braces and separated by
commas.

The general form is:

data-type arrayname[expression] = {value1, value2, value3…);

Where value1 refer to the value of the first array element, value2
refers to the value of the second element and so on. The appearance
of the expression which indicates the number of array elements is
optional when initial values are present.

Examples of array initialization:

int first_array[5] = {5, 3, 2, 7, 9};


int second_array[] = {11, 21, 75, 24, 5};
int third_array[15] = {3,7, 4, 6, 1};
COMP 20023 - Computer Programming 1 ARRAY
The first example is a simple array declaration of five integers.
It is typically the way array initialization is coded. When the
array is completely initialized, it is not necessary to specify
the size of the array. This case is seen in the second example. It
is a good idea, however, to define the size explicitly because it
allows the compiler to do some checking and it is also good
documentation.

If the number of values provided is less that the number of


elements in the array, the unassigned elements are filled with
zeros. This case is seen in the third example. We can use this
rule to easily initialize an array to all zeros by supplying just
the first zero value of the first element.

Inputting Values

Another way to fill the array is to read the values from the
keyboard or a file. This can be done using a loop when the array
I going to be completely filled, the most appropriate loop is the
for because the number of elements are fixed and known.

Example:

int scores[10];

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


scanf(“%d”, &scores[i];

Several concepts need to be studied in this simple statement.


First, we start the index, i, at zero. Since there are ten elements
in the array, we must load the values from index locations zero(0)
through nine(9).The limit test therefore, is set at i<10, which
conveniently is the number of elements in the array. Then, even
though we are dealing with array elements, the address operator
(&) is still necessary in the scanf call.

Finally, when there is a possibility that all the elements are not
going to be filled, then one of the event-controlled loops (while
or do-while) should be used. Which one you use would depend on the
application.

Individual elements can be assigned values using the assignment


operator. Any value that reduces to the proper type can be assigned
to an individual array element.
COMP 20023 - Computer Programming 1 ARRAY
Example:

scores[4] = 23;

On the other hand, you cannot assign one array to another array,
even if they match full in type and size. You have to copy arrays
at the individual element level. For example, to copy an array of
25 integers to a second array of 25 integers, you could use a loop
as shown below:

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


second[i] = first[i];

If the values of an array follow a pattern, we can use a loop to


assign values. For example, the following loop assigns a value
that is twice the index number to array scores.

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


scores[i] = i * 2;

Sample Program: This is a program that sorts the values of


the array num.

#include <stdio.h>

main()

{
int num[3] = {5, 3, 7};
int h, i, temp;

for(h = 0; h < 3; ++h)


for(i = 0; i < h; ++i)
{
if(num[i] > num[i + 1])
{
temp = num[i];
num[i] = num[i + 1];
num[i + 1] = temp;
}
}
for(i = 0; i < 3; i++)
printf(“%d\n”, num[i]);
}

Sample Run:
Output:
3
5
7

You might also like