/    /  Arrays

Arrays

 

A variable is used to store a single value at a time.

 

For example:

 

int a; char c; float f;

 

Above example contains different data types and each can store only a single value of the declared data type. These variables are called scalar variables. A scalar variable is a single variable that can store an atomic value.

An array is a fundamental data structure that allows large amounts of data to be stored and manipulated.

An array stores an orderly sequence of uniform values. An array is a collection of individual data elements that are ordered- can count the elements fixed in size.

In C, each array has two fundamental properties the data type and size. The individual array elements are identified by an integer index. The array indexing starts from 0. The index is written inside square brackets.

Some examples where arrays can be used are:

  1. List of registered temperatures every hour per day, month or year.
  2. List of employees of a given organization.
  3. List of products and the selling price in store.
  4. Test scores of a class of students

 

One-Dimensional Array

 

There are several forms of an array-like one dimensional and multidimensional.

 

Declaration of a One-dimensional Array:

 

The array has to be declared in a program before it is used. When defining an array the following need to be specified.

  • the type of data it can hold.
  • the number of values it can hold.
  • name of the array.

 

Syntax:

 

data_type array-name[size];

 

Example:

 

 int a[5];

 

array

here size specifies how many items in the array. Array indexes can vary between 0 and size-1. The lower boundary is 0 and the upper boundary is size 1.

The array cannot be declared without size in square brackets.

float f[ ],g[ ]; // illegal declaration

 

Example:

 

#include<stdio.h> 
#define n 20 
main()
{
float x[n]; // is valid
…….
}

 

Here n is the symbolic constant assigned value of 20.

 

Initializing an Array:

 

As variables are assigned values during declaration arrays can also be initialized in the same manner.

 

int a[5]={3,5,7,9,2};

 

array

 

Accessing the Array Elements:

 

The array elements are accessed by index. If the element 0 and element 3 are to be assigned values then

 

a[0]=5;              a[3]=8;