7 Arrays
7 Arrays
Definition
An array is a fixed-size sequenced collection of
elements of the same data type ie, a grouping
of like-type data that share a common name.
It can be used to represent a list of numbers or
names.
• Since an array can represent a list of items,
the individual values of the items are
referred to as elements. Example Salary[10]
represent the tenth element (10th employee
salary in a list of organization employees
salaries).
We can use the arrays to represent
not only a simple list of values (one-
dimension) but also tables of data in
two and three dimensions.
One-Dimensional Arrays
A list of items can be given one
variable name using only one
subscript and such a variable is
called a single-subscripted variable
or a one-dimensional array.
Declaration of One-Dimensional Arrays
23 56 12 58 70 94 Elements
0 1 2 3 4 5 Subscript or index
Cell
• To represent 35, 40, 20, 57, 19 by an array variable
number, the array variable number is declared as
int number[5]; the computer will reserve five
storage spaces as;
Number[0]
Number[1]
Number[2]
Number[3]
Number[5]
Initialization of One-Dimensional Arrays
Format:
• type array-name[size] = { list of value };
• The values in the list are separated by commas Example int num[3]
= {0,0,0};
or to initialize array number[5] with the following values 35, 40, 20,
57, 19 :
Number[0] = 35;
Number[1] = 40;
Number[2] = 20;
Number[3] = 57;
• These elements may be used in programs
just like any other C variable. Example
scanf(“%d”, &number[0]);
printf(“%d”, number[0]);
tot=tot+number[1];
Working with arrays
• The for statement enhances processing of array elements in
sequence from the first element to the last element.
for (i=0;i<5;i++)
scanf(“%d”,&number[i]);
for (i=0;i<5;i++)
printf (“%d”,number[i]);
Examples
{ for(i=9;i>=0;i--)
printf(“enter name:”); }
for(i=0;i<10;i++)
scanf(“%c”,&name[i]);
Program to input 8 numbers to an array and calculate
their total value