What is an array and why is it required?

What is an array and why is it required?

A collection of comparable sorts of data objects stored in contiguous memory regions is referred to as an array. Arrays are a derived data type in the C programming language that may hold primitive data types like int, char, double, float, and so on. It may also hold a collection of derived data types such as pointers, structures, and so on. The array is the most basic data structure, in which each data piece may be retrieved at random by its index number.

If you need to keep comparable elements, a C array is useful. For example, if we want to record a student's grades in six courses, we don't need to create separate variables for each subject's grades. Instead, we may create an array that can be used to hold the marks in each topic in contiguous memory regions.

We may simply retrieve the items by utilising the array. To access the array's elements, only a few lines of code are necessary.

Properties of Array

  • The properties in the array are as follows.
  • An array's elements all have the same data type and size, for example, int = 4 bytes.
  • The array's elements are kept in contiguous memory regions, with the initial element kept in the smallest memory place.
  • Because we can compute the address of each element of the array with the supplied base address and the size of the data element, we can access elements of the array at random.

Advantage of C Array

  • Data Access Code Optimization: Less code is required to access the data.
  • Ease of traversal: We may quickly get the items of an array by utilising the for loop.
  • Sorting is simple: We just need a few lines of code to sort the array's contents.
  • Random Access: The array allows us to access any element at any time.

Disadvantage of C Array

  • Fixed Size: Whatever size we provide at the time of array declaration, we cannot exceed it. As a result, unlike LinkedList, which we'll learn about later, it doesn't expand in size dynamically.

Declaration of C Array

In the C programming language, we may declare an array in the following fashion. array name[array size] data type;

Let's look at an example of how to declare an array.

An example of a C array

#include<stdio.h> int main() { int i=0; int marks[5];//declaration of array marks[0]=80;//initialization of array marks[1]=60; marks[2]=70; marks[3]=85; marks[4]=75; //traversal of array for(i=0;i<5;i++) { printf("%d \n",marks[i]); }//end of for loop return 0; }