Arrays

Let’s say you have a program where you need to store 20 int values. You can declare 20 int variables, but there is a better way. The people who invented C knew this, so they gave us arrays.

Example Program

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int count;
    int nums[20];
    
    srand(time(0));
    
    printf("Filling array...");
    for(count = 0; count < 20; count++)
    {
        nums[count] = rand() % 10;
    }
    puts("done!");
    
    puts("Array values:");
    for(count = 0; count < 20; count++)
    {
        printf("%d\n", nums[count]);
    }
     
    return 0;
}

And the output:

Filling array…done!
Array values:
5
6
0
7
7
8
5
6
1
8
9
5
4
5
8
7
4
9
3
1

The Basics of Arrays

An array allows us to store a fixed-size sequential collection of elements of the same type using just one variable. An array will be declared using the following generalized format:

<type> <identifier>[<size>];

In our specific program, since we want an array of ints, we have done the following:

int nums[20];

You can access the members of the array, called elements, by specifying a number between the brackets after the identifier, called an index. The index used must be between 0 and 1 less that the size of the array. So if our array has 20 elements, the first element will be 0 and the last element will be 19.

for(count = 0; count < 20; count++)
{
    nums[count] = rand() % 10;
}

In our loop, we are referencing each specific element using the count variable. The referenced element can then be used exactly as a single variable. In our code we assign a random number to each element.

for(count = 0; count < 20; count++)
{
    printf("%d\n", nums[count]);
}

We then loop through the same array again, printing out each element we assigned in the previous loop.

<< prev | next >>

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x