Users Online

· Guests Online: 33

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Articles Hierarchy

Arrays in C

Arrays in C

Arrays in C are data structures that hold multiple elements. C uses a numeric index to access these elements.

Representation and Terms

Representation

Things are best explained through examples, so here is one example.

C array representation - elements and index

Terms

This is an array, called "numbers" and it holds 10 values. The first row represents the index - the values 0 - 9. The second row of the picture are the actual values (23, 56 ... -40). We call these values elements. To access the elements we need to use the name of the array and the index.

For example, here the element with position 0 has a value of 23, index 4 points to the value -5 and so on.
Most of the time, you will use a loop to handle the values in an array. Usually, you will use a for loop and use its counter variable as an index.

An array is a data structure that hold multiple values. These values are called elements and they are located next to each other in the memory of the computer. To access them we need an index - a value that locates a given element within the array. The index always starts from 0 (the first element) and reaches N-1 (the last element), where N is the size of the array.

Arrays in C

Creating arrays in C is similar to how we create regular variables. Here we need to specify the type, the name and the size. To specify the size we use square brackets. Here is an example of how we can create a character array called "symbols" with size 5:

char symbols[5];

Then we can assign a value to, let's say, the first element:

symbols[0] = 'H';

And finally output that value to the screen:

printf("%c", symbols[0]);

In this case we are holding char values, but we can define the array to be of any other type. However, once we create it, we cannot change neither its type, nor its size.

Save the alphabet

Like we said above, usually you will use a loop to go through the elements. In this next example we use character arithmetic to save the letters from the English alphabet in an array called "letters":

#include <stdio.h>

int main(int argc, char **argv)
{
    char letters[26];
    int i;
    for(i =0; i<26; ++i)
        letters[i] = 'a'+i;
    
    for(i =0; i<26; ++i)
        printf("%c ", letters[i]);
        
    return 0;
}

Size precautions

Be alert that arrays in C don't have boundary checks. This means that you can access (read/write) values that are outside of the array. For example: in the above program we could have continued to write after index = 25. This means that we would overwrite whatever values were located in the memory after the array. It is obvious that this could cause a loss of data, program crash or other unintended consequences.

In the same way we could continue to read after the last element. Once again this may cause our program to behave in unexpected ways.

Arrays in C don't have boundary checks!
Always make sure that your index stays in the range of 0 - N-1.

2D

Arrays in C with 2 or more dimensions

So far, we only looked at an array with one dimension. There we had one index and we visualized the elements as one row of vales.

A 2 dimensional array is usually represented like a table. It has two indices - one for the rows and another for the columns. It is accepted that the first is the row index. Just like before, the rules for the index are the same - they both start from 0 and reach the dimension size -1.

Here is one example - here we create an array, called 'prices', it has 4 rows and 5 columns.

float prices[4][5];

We can visualize it like this:

2 dimensional float array called 'prices' with 4 rows and 5 columns

To go through all elements in this case, we need to use nested loops. Because we know the exact number of rows and columns it is convenient to use for loops. Let's reset all prices to 0.0f:

#include <stdio.h>

int main(int argc, char **argv)
{
    float prices[4][5];
    int row,col;
    for(row = 0; row < 4; ++row)
    {
        for(col = 0; col < 5; ++col)
        {
            prices[row][col] = 0.0f;
        }
    }   
    return 0;
}

More dimensions

You can create an array with more than 2 dimensions. In fact, there is not limit to how many dimensions arrays in C can have. However, it is very rare to use more than 2. In fact, if you ever need to use 3-4 or even more, you should reconsider your data representation. Most of the time you can organize your data more efficiently and you don't need a 3 dimensions. For 7 years of programming, I have used 3D array just once.

Just to make one example - here is how we create a 3 dimensional array and find the sum of all positive elements.

#include <stdio.h>

int main(int argc, char **argv)
{
    int seconds[6][4][7];
    long totalSeconds = 0;
    int x,y,z;
    for(x = 0; x < 6; ++x)
    {
        for(y = 0; y < 4; ++y)
        {
            for(z = 0; z < 7; ++z)
            {
                if(seconds[x][y][z] > 0)
                {
                    totalSeconds += seconds[x][y][z];
                }
            }
        }
    }
    printf("Total number of secods: %ld\n", totalSeconds);
    return 0;
}

And remember that you can omit the brackets of the loops and ifs, when their body consists of only one row. Many people prefer this way, so you need to get used to reading both styles. The above code is equivalent to this:

#include <stdio.h>

int main(int argc, char **argv)
{
    int seconds[6][4][7];
    long totalSeconds = 0;
    int x,y,z;
    for(x = 0; x < 6; ++x)
        for(y = 0; y < 4; ++y)
            for(z = 0; z < 7; ++z)
                if(seconds[x][y][z] > 0)
                    totalSeconds += seconds[x][y][z];
    printf("Total number of secods: %ld\n", totalSeconds);
    return 0;
}

And just make the example more interesting, here is the same data, but this time we are performing some arithmetic with the result in order to present it in a more convenient way:

#include <stdio.h>

int main(int argc, char **argv)
{
    int seconds[6][4][7];
    long totalSeconds = 0;
    int x,y,z,years,days,hours,minutes;
    for(x = 0; x < 6; ++x)
    {
        for(y = 0; y < 4; ++y)
        {
            for(z = 0; z < 7; ++z)
            {
                if(seconds[x][y][z] > 0)
                {
                    totalSeconds += seconds[x][y][z];
                }
            }
        }
    }
    printf("Total number of secods: %ld\n", totalSeconds);
    years = totalSeconds / (365 * 60 * 60 * 24);
    totalSeconds -= (long)years * 365 * 60 * 60 * 24;
    days = totalSeconds / (60 * 60 * 24);
    totalSeconds -= days * 60 * 60 * 24;
    hours = totalSeconds / (60 * 60);
    totalSeconds -= hours * (60 * 60);
    minutes = totalSeconds / 60;
    totalSeconds -= minutes * 60;
    printf("Total time: %d years, %d days, %d hours, %d minutes, %ld seconds.", years, days, hours, minutes, totalSeconds);
    return 0;
}
 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.82 seconds
10,276,117 unique visits