Holla Tech - Learn

Arrays in C
 

An array is a data structure that stores a collection of related values that are all the same type.
Arrays are useful because they can represent related data with one descriptive name rather than using separate variables that each must be named uniquely.
For example, the array test_scores[25] can hold 25 test scores.
An array declaration includes the type of the values it stores, an identifier, and square brackets [ ] with a number that indicates the array size.
For example: 

int test_scores[25]; /* An array size 25 */ 

 

You can also initialize an array when it is declared, as in the following statement:

float prices[5] = {3.2, 6.55, 10.49, 1.25, 0.99}; 

 

Note that initial values are separated by commas and placed inside curly braces { }.
An array can be partially initialized, as in:

float prices[5] = {3.2, 6.55}; 

 

Missing values are set to 0.

NOTE!
A recursive solution requires a base case to prevent an infinite loop. Tap Try It Yourself to play around with the recursive code.

Accessing Array Elements
 

The contents of an array are called elements with each element accessible by an index number.
In C, index numbers start at 0.
An array with 5 elements will have index numbers 0, 1, 2, 3, and 4. Consider an array x:

int x[5] = {20, 45, 16, 18, 22}; 

 

It can be thought of as:
0 => [20] 1 => [45] 2 => [16] 3 => [18] 4 => [22]

To access an array element, refer to its index number.
For example:

int x[5] = {20, 45, 16, 18, 22};
printf(“The second element is %d\n”, x[1]); /* 45 */ 

 

The value of an array element can be changed through an assignment statement, which also requires using the array name and index:

int x[5] = {20, 45, 16, 18, 22};
x[1] = 260;
printf(“The second element is %d\n”, x[1]); /* 260 */ 

 

NOTE!
The index of an array is also referred to as the subscript.

Using Loops with Arrays
 

Many algorithms require accessing every element of an array to check for data, store information, and other tasks. This can be done in a process called traversing the array, which is often implemented with a for loop because the loop control variable naturally corresponds to array indexes.
Consider the following program:

float purchases[3] = {10.99, 14.25, 90.50};
float total = 0;
int k;

/* total the purchases */
for (k = 0; k < 3; k++) {
  total += purchases[k];
}
  
printf(“Purchases total is %6.2f\n”, total);
/* Output:  Purchases total is 115.74 */ 

 

The loop control variable iterates from 0 to one less than the number of elements to match index values.
Loops are also useful for assignment.
For example:

int a[10];
int k;

for (k = 0; k < 10; k++) {
  a[k] = k * 10;

 


BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE C MAIN COURSE PAGE. 

C MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT