Basic introduction of c and c++ array data structure





In this tutorial we will learn basic concept of c and c++ array data structure.  so our first question is “what is array?”.

array is a data structure which stores items of same type in contiguous memory location.

How to declare an array in C and C++?

data_type name[size];

The above declaration  is known as a single-dimension array. The size must be an integer constant greater than zero. The data_type can be any valid C and C++ data type.

For example, to declare a 5 items array called weight of type float, we use array declaration as

float weight[5];

How to initialize an array in C and C++?

/* c program */

#include <stdio.h>

float weight[5] = { 20.2, 20.5,10.1,3.4,5.5}; // initialization of array weight

int main()
{
    return 0;
}
/* c ++ program */

#include <iostream>

float weight[5] = { 20.2, 20.5,10.1,3.4,5.5};

int main()
{
    return 0;
}

How to access an array in C and C++?

As we know ,the array stores elements in contiguous memory location. In this way we can access array element directly from its index.  For example float weight[5] = {20.2,  20.5, 10.1, 3.4, 5.5};

array in c and c++

The index of array starts from 0 , so if the size of array is 5, the valid index would be 0,1,2,3 and 4. 0 points to first element and 4 points to last element of the example array.

Let us print the array float weight[5] = {20.2,  20.5, 10.1, 3.4, 5.5}; using c program.

#include <stdio.h>

float weight [ 5] = { 20.2, 20.5, 10.1, 3.4, 5.5 };

int main()
{
    int index = 0;

    // loop through array weight
    for (index; index < 5; index++)
    {
        // print element
        float element = weight [ index];
        printf("%1f ", element);
    }
    // new line
    printf("\n");
    return 0;
}

The output would be

20.200001 20.500000 10.100000 3.400000 5.500000

Note: we have array elements float weight[5] = {20.2,  20.5, 10.1, 3.4, 5.5};  but look at the output , output is different than the actual input. To know the difference we have to know “how float value is stored in memory?” ,But we cam limit the decimal place using format “%.1f ” in printf statement. use printf(“%.1f “, element);  instead of printf(“%f “, element);  the output would be

20.2 20.5 10.1 3.4 5.5

So to declare an array of five integers , we use int name[5]

To declare an array of five double data type , we use float name[5]

To declare an array of five character data type we use char name[5]

We would now discuss two dimensional array in next chapter.



Related Contents to follow



No Comments Yet

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.