top

Search

C Tutorial

.

UpGrad

C Tutorial

Array in C

Introduction

Array in C refers to a method that combines multiple entities of identical type into a huge group. The data types of these elements or entities can be int, float, double, char, or user-defined data types as well. Rather than declaring separate variables for every value, arrays store multiple values in a single variable.

Why Do We Need Arrays?

If you want to work on a huge number of variables, you can use an array in C to store them. For example, if you want to store the marks of all the students of class 2 of a school, then you can use an array in C++ or C. After defining the array of the required size, you can print array in C to display the values of each element.

Here are a few more reasons justifying the need to use arrays:

  • Arrays help you to easily sort elements by writing a few lines of code.

  • You can access an array’s elements in any order.

  • All elements in an array can be traversed with the help of a single loop.

Declaration and Initialisation of Array in C

You can declare an array irrespective of its data type. The below ways help you to declare and initialise an array in C.

Declaring array by defining the size:

The array’s size mentions the maximum number of elements it can store. You can either declare an array by defining its size during declaration or allow a user-defined size.

Here’s an example demonstrating how to define the size of an array.

int newarray1[15];

The above C command declares an array named “newarray1” of int data type and size 15.

Note that if you declare an array without allocating a value, it will store a garbage value.

Declaring array by initialising elements:

This method states that the compiler allocates an array of size equivalent to the number of elements. The array initialisation happens during the declaration time.

Here’s an example showing how to initialise the elements of an array:

int newarray1[] = {5, 10, 20, 30, 40}

The above command creates an array of 5 elements. Although the array size is not specified, the compiler assigns a size of 5 integer elements to the array.

Declaring array by defining the size and initialising elements:

In this method. If the number of initialised elements is less than the array’s size, the compiler automatically initialises the remaining elements to 0. Here’s an example:

int newarray1[5] = {5, 10, 20, 30, 40};

you can also declare it as,

newarray1 = {5, 10, 20, 30, 40}

Here's another example:

int newarray1[5] = {5, 10, 20};

you can also declare it as,

int newarray2 = {5, 10, 20, 0, 0}

In the above examples, the size of the newarray1 array is 5. On the other hand, the size of the newarray2 array is 5, but only three elements are initialised. The compiler initialises the rest two elements to 0.


Initialising array using a loop:

When you initialise an array using a loop, the loop iterates from 0 to (size - 1) to access all elements of the array. Here’s an example that uses for loop to initialise an array’s elements.

#include <stdio.h>

int main() {
    int newarray1[4];
    int i;

    for (i = 0; i < 4; i++) {
        newarray1[i] = 2 * i;
    }

    printf("newarray1 = {");
    for (i = 0; i < 4; i++) {
        printf("%d", newarray1[i]);
        if (i != 3) {
            printf(", ");
        }
    }
    printf("}\n");

    return 0;
}

In the above example, an array of size 4 is declared first. The for loop then initialises it.


Access Array Elements

Any array’s elements range from”0” to “array_size – 1”. The indexing shows the array’s position. If you want to access an array element, you should refer to its index value. Specifically, [0] represents the first element. [1] represents the second element, etc. Here’s the syntax

array_name[index]

Let’s look at an example to understand how to access array elements: 

#include <stdio.h>
int main()
{
int newarray1[4] = {5, 10, 20, 30};
printf("%d", 5*newarray1[0]); //accesses and prints the value of 1st element
return 0;
}
Output:
25


Input and Output Array Elements

You can store array values by accepting input from the user and storing them in that array.

scanf("%d", &newarray1[0]); // inputs an integer element and stores it in 1st position of the array

The printf() method helps you to display the array elements. You can specify the index to indicate the position of the elements you want to print.

printf("%d", newarray1[0]); // prints the element stored at 0th index or 1st position 

 

Advantages & Disadvantages of Array in C

Advantages of Array in C

  • The array in C makes the code cleaner and more optimised. This is because you can save multiple elements in a single array at once. Hence, you don’t need to initialise or write them multiple times.

  • You can insert or delete elements in linear complexity in an array.

  • Being stored in an adjacent memory block, decreases the amount of memory required to access an element.

  • All C/C++ compilers support them. So, they are a universal choice when dealing with complex programming tasks.

  • You can perform operations on individual elements; no need to iterate through the whole data structure.


Disadvantages of Array in C:

  • Arrays in C are statically allocated. Once you initialise their size, it can’t be increased or decreased.

  • The size of an array can’t be changed once it's determined during declaration.

  • All elements in an array must be initialised, although they are not used. So it leads to memory wastage.


2-Dimensional Array in C

The 2D array in C is the most common type of multidimensional array. In this form of multidimensional array in C, every element can be signified as a separate 1-D array. The total number of elements is the multiplication of the number of rows and columns. For example, if the array is newarray1[3][4] then the total number of elements is 12.

The processing of a 2D array in C needs a nested loop. The outer loop represents the number of rows, and the inner loop represents the columns of elements in each row.

Here’s a syntax to declare a 2D array in C.

datatype name_of_array[no_of_rows][no_of_columns];

 
Initializing 2D array in C:

While working with 1D arrays, if you initialise an array during its declaration, you can skip declaring its size. However, in the case of 2D arrays, you can only skip the first dimension; you must specify the second dimension during initialisation.

Ways to initialise a 2D array in C:

The conventional way involves defining the 1D arrays (with the number of elements equal to that of columns).

Arrays Vs Pointers

Arrays can work like pointers in several scenarios. For example, when an array is passed to a function, it is considered as a pointer. The pointer arithmetic applies to arrays. But both of them differ in several ways. Let’s look at their key differences.

Array

Pointer

An array holds one or more values of an identical data type.

A pointer holds the address/memory location of a variable.

It is defined as data type array_name[size];

It is defined as data type *ptr_name;

Sequential or contiguous memory is assigned to the elements of an array.

Any random available memory can be allocated to a pointer.

Since arrays are static, you can’t alter their size.

Since pointers are dynamic, their memory size can be either freed or altered.

A single array can save a huge number of elements.

A pointer points to only one variable’s memory location.

The type of elements stored determines the data type of the array.

The type of the variable whose memory location a pointer points to determines its data type.

When you pass an array to the sizeof() operator, the total size of all the stored elements is returned.

Passing a pointer to the sizeof() operator prints the size of the pointer. The same is identical for any type of pointer.

Memory allocation to an array happens during the compilation process.  

Memory allocation to a pointer happens during the program’s run time.

Conclusion

Declaring, accessing, and sorting any required elements is simplified with the use of an array in C. Despite storing many elements at once, they save memory and improve the program’s efficiency.

In addition to practising through tutorials that help you reinforce your programming abilities, pursuing higher education can be an extraordinary addition to your skill set.

upGrad’s Master of Science in Computer Science, provided by Liverpool John Moores University, can accelerate your career to stay updated with the recent trends in the tech industry. Due to thorough guidance from leading faculties and industry experts, this course benefits learners with extensive support, projects, live sessions, assignments, videos, use cases, and more. After completing this course, you can discover outstanding job opportunities in software engineering.

FAQs

Q. What are the types of arrays in C?

There are two types of array in C, i.e., one-dimensional array in C and multidimensional array in C.

Q. What is a string array in C?

The strings are arrays of characters, so the string array in C evolves into a two-dimensional array of characters.

Q. How can I declare an Array in C language?

The common syntax to declare an array in C programming is- datatype arrayName[arraySize];. For example, int numbers[7]; declares an integer array named numbers with a size of 7 elements.

Leave a Reply

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