Arrays in C
Arrays in C
ARRAY CONCEPTS
Characteristics of an Array
An array is a sequence of data items that are the same type, that
are indexable, and that are stored contiguously.
Number0 Number[0]
Number1 Number[1]
. .
. .
. .
Number19 Number[19]
An array of numbers
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.
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.
#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];
}
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];
x[3] = 0 y[3] = 0
y[4] = 0
college[0] = ‘C’;
college[1] = ‘C’;
college[2] = ‘M’;
college[3] = ‘I’;
college[4] = ‘T’;
college[5] = ‘\0’;
score[0]
Initialization
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.
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];
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.
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:
#include <stdio.h>
main()
{
int num[3] = {5, 3, 7};
int h, i, temp;
Sample Run:
Output:
3
5
7