Computer Science

One Dimensional Arrays in C

One dimensional arrays in C are a way to store a collection of data of the same type in a contiguous block of memory. They are declared using square brackets and can be accessed using an index. Arrays can be used to simplify code and make it more efficient.

Written by Perlego with AI-assistance

1 Key excerpts on "One Dimensional Arrays in C"

  • C Programming
    eBook - ePub

    C Programming

    Learn to Code

    A 1D array is a collection of items having common data types stored in a contiguous memory location, identified by a single name with its index number. More generally, suppose we have stored five different integers in a continuous memory location with a common name. We can access each integer with the help of the name of the array and index number – then the whole scenario is called an integer array.
    A one-dimensional array is a collection of items having common data types stored in a contiguous memory location, identified by a single name with its index number.

    10.4.1 Declaration of 1D Arrays

    As we know, before using any variable, we must declare it. Similarly, we must declare the array before we use it in our program code. Let us recall how a variable is declared because there is a little difference between the declaration of a variable and the declaration of an array (see Figure 10.3 ).
    Figure 10.3 Variable declaration with example.
    In this example, x represents the name of the variable, and int represents the type of data that x can store and the size (in bytes) of x (see Figure 10.4 ).
    Figure 10.4 Describing int x.
    In the same manner, we can declare an array. Figure 10.5 shows the syntax.
    • The data type indicates the type of data we can store inside an array;
    • Array names can be valid identifiers;
    • Size (also known as the dimension) indicates the number of the same type of data we can store inside the array;
    • The size must be an integer and specified within two square brackets.
    • See Figure 10.6 for an illustration of the declaration process. This indicates the array named age will contain five integer values;
    • This declaration will immediately reserve 20 bytes of memory because each of these five integers will be four bytes long (we assume the integer takes four bytes for our illustration).
    Figure 10.5 Array declaration with example.
    Figure 10.6 Illustration of the example shown in Figure 10.5.

    Note

    The dimension of the array must be a constant. We cannot use a variable name for representing the dimension of the array. This is possible, but for the time being, we will not concentrate on this aspect, as it will be discussed later whenever there is a need.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.