Introduction to Array in C Programming

An array is a collection of similar data elements. These data elements have the same data type. The elements of the array are stored in consecutive memory locations and are referenced by an index (also known as the subscript). If one subscript, then we call a one-dimensional array.

Memory representation in an array

The array elements are stored in contiguous memory locations. For the array, int stuMark[]={43,70,56}; the memory representation shown as follows:

By using an array, we just declare like this,

int studMark[1000];

This will reserve 1000 contiguous memory locations for storing the students’ marks. Graphically, this can be depicted as in the following figure. Compared to the basic data type (int, float, char, and double) it is an aggregate or derived data type. All the elements of an array occupy a set of contiguous memory locations. Why do we need to use array type?

Consider the following issue:
“We have a list of 1000 students’ marks of an integer type. If using the basic data type (int), we will declare something like the following…”

int studMark0, studMark1, studMark2, ..., studMark999

Can you imagine how long we have to write the declaration part by using normal variable declaration?

int main(void){
int studMark1, studMark2, studMark3, studMark4, ..., ...,
studMark998, stuMark999, studMark1000;
...
...
return 0;}

This absolutely has simplified our declaration of the variables. We can use index or subscript to identify each element or location in the memory. Hence, if we have an index of jIndex, studMark[jIndex] would refer to the jIndexth element in the array of studMark. For example, studMark[0] will refer to the first element of the array. Thus by changing the value of jIndex, we could refer to any element in the array. So, array has simplified our declaration and of course, manipulation of the data.

One Dimensional Arrays

One/Single Dimensional array
Dimension refers to the array’s size, which is how big the array is.

Declaration of One Dimensional array
Declaring an 1D dimnl. array means specifying three things:

  • data type – what kind of values it can store ex, int, char, float.
  • Name – to identify name of the array.
  • size – the maximum number of values that the array can hold.

Arrays are declared using the following syntax.

type name[size];

For example, to declare an array of 30 characters, that construct a people name, we could declare,

char cName[30];

Which can be depicted as follows,
In this statement, the array character can store up to 30 characters with the first character occupying location cName[0] and the last character occupying cName[29].

Note that the index runs from 0 to 29. In C, an index always starts from 0 and ends with array’s (size-1). So, take note the difference between the array size and subscript/index terms.

Examples of the one-dimensional array declarations,

int    xNum[20], yNum[50];
float  fPrice[10], fYield;
char   chLetter[70];

The first example declares two arrays named xNum and yNum of type int. Array xNum can store up to 20 integer numbers while yNum can store up to 50 numbers. The second line declares the array fPrice of type float. It can store up to 10 floating-point values, fYield is basic variable that shows array type can be declared together with basic type provided the type is similar. The third line declares the array chLetter of type char. It can store a string up to 69 characters.

Note: Why 69 instead of 70? Remember, a string has a null terminating character (\0) at the end, so we must reserve for it.

Initialization of an array

An array may be initialized at the time of declaration.

Giving initial values to an array.
Initialization of an array may take the following form,

type array_name[size] = {a_list_of_value};

For example:

int   idNum[7] = {1, 2, 3, 4, 5, 6, 7};
float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
char  chVowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};

The first line declares an integer array idNum and it immediately assigns the values 1, 2, 3, …, 7 to idNum[0], idNum[1], idNum[2],…, idNum[6] respectively. The second line assigns the values 5.6 to fFloatNum[0], 5.7 to fFloatNum[1], and so on. Similarly the third line assigns the characters ‘a’ to chVowel[0], ‘e’ to chVowel[1], and so on.

Note: again, for characters we must use the single apostrophe/quote (‘) to enclose them. Also, the last character in chVowel is NULL character (‘\0’).

Initialization of an array of type char for holding strings may take the following form,

char array_name[size] = "string_lateral_constant";

For example, the array chVowel in the previous example could have been written more compactly as follows,

char chVowel[6] = "aeiou";

When the value assigned to a character array is a string (which must be enclosed in double quotes), the compiler automatically supplies the NULL character but we still have to reserve one extra place for the NULL. For unsized array (variable sized), we can declare as follow,

char chName[ ] = "Mr. Dracula";

C compiler automatically creates an array which is big enough to hold all the initializer.

Store values in the array (3 possible ways)
1) Initialize the elements
2) Inputting Values for the elements
3) Assigning Values to the elements

1) Initialize the elements

int   idNum[7] = {1, 2, 3, 4, 5, 6, 7};
float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
char  chVowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};

2) Inputting Values for the elements

int i, marks[10];
for(i=0;i<10;i++)
scanf("%d", &marks[i]);

3) Assigning Values to the elements

int i, arr1[10], arr2[10];
for(i=0;i<10;i++)
arr2[i] = arr1[i];

Accessing elements

To access all the elements of the array, you must use a loop. That is, we can access all the elements of the array by varying the value of the subscript into the array. But note that the subscript must be an integral value or an expression that evaluates to an integral value.

int i, marks[10];
for(i=0;i<10;i++)
marks[i] = -1;

Calculating the address of array elements
Address of data element:

A[k] = BA(A) + w( k – lower_bound)

Here,
A is the array
k is the index of the element of which we have to calculate the address.
BA is the base address of the array A.
w is the word size of one element in memory, for example, size of int is 2.

Marks[4] = 1000 + 2(4 – 0) = 1000 + 2(4) = 1008

Calculating the length of the array

Length = upper_bound – lower_bound + 1

Where upper_bound is the index of the last element and lower_bound is the index of the first element in the array.

Here,
lower_bound = 0, upper_bound = 7. Therefore, length = 7 – 0 + 1 = 8.

Program example 1: Write A program to read and display n numbers using an array:

#include<stdio.h>
#include<conio.h>
int main()
{
int i=0, n, arr[20];
printf("\n Enter the number of elements : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d",&arr[i]);
}
printf("\n The array elements are ");
for(i=0;i<n;i++)
printf("arr[%d] = %d\t", i, arr[i]);
return 0;
}

Output:

Enter the number of elements : 2

arr[0] = 1

arr[1] = 2

The array elements are arr[0] = 1     arr[1] = 2

Arrays allow programmers to group related items of the same data type in one variable. However, when referring to an array, one has to specify not only the array or variable name but also the index number of interest.

Program example 2: Sum of array’s elements:

// finding sum of array's element
#include <stdio.h>
// replace every nSize occurrences with 10
#define nSize 10

int main(void){
 int iCount, nSum = 0, iNum[nSize] = {6,4,2,3,5,10,12};

 for (iCount=0; iCount<nSize; iCount++) {
 // display the array contents
 printf("%d ",iNum[iCount]);
 // do the summing up
 nSum = nSum + iNum[iCount];
 }

 // display the sum
 printf("\nSum of %d numbers is = %d\n", iCount, nSum);
 return 0;
}

OUTPUT:

6 4 2 3 5 10 12 0 0 0
Sum of 10 numbers is = 52
Note: the array’s element which is not initialized is set to 0 automatically

Operations

Operation on array includes:

  • Traversal
  • selectiion
  • Insertion
  • Deletion
  • Searching

1. Traversal

Traversal is an operation in which each element of a list, stored in an array, is visited.. The travel proceeds from the zeroth element to the last element of the list.

Exercise Program 1 : Traverse on the list and Print the number of positive and negative values present in the array -as 0)

Algorithm:
Step 1: get the elements
Step 2: visit all the elements from oth element to the last element.
Step 3. chk for element is 0, if so do count of each criteria.
Step 4: count of negative, zero and positive in which travel proceeds from oth to last.
Step 5. print the count for each criteria.

#include <stdio.h>
void main()
{
int list[10];
int n;
int i, neg=0, zero=0, pos=0;
printf("\n enter the size of the list\n");
scanf("%d",&n);
printf("Enter the elements one by one");
for(i=0;i<n;i++)
{
 printf("\n Enter number %d number",i);
scanf("%d", &list[i]);
}
for(i=0;i<n;i++)
{
if(list[i]<0)
neg=neg+1;
else
if(list[i]==0)
zero=zero+1;
else
pos=pos+1;
}
printf("No of Negative numbers in given list are %d", neg);
printf("No of Zeros in given list are %d", zero);
printf("No of Positive numbers in given list are %d", pos);
}

2. Selection

An array allows selection of an element for given index. Array is called as random access data structure.

Algorithm:
Step 1: enter size of the list
Step 2: enter the merit list one by one
Step 3: get into menu of two choice 1-querya and 2. quit
Step 4: get the pos value and find the value in that pos value
Step 5. print that value

#include<stdio.h>
#include<conio.h>
void main()
{
float merit[10];
int size,i,pos,choice;
float percentage;
printf("\n Enter the size of the list");
scanf("%d", &size);
printf("\n Enter the merit list one by one");
for(i=0; i < size; i++)
{
printf("\n Enter Data:");
scanf("%f", &merit[i]);
}
do
{
printf("\n menu");
printf("\n Querry…….1");
printf("\n Quit…………2");
printf("\n Enter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n Enter position");
scanf("%d", &pos);
percentage=merit[pos];
printf("\n percentage=%4.2f", percentage);
break;
case 2:
printf("\n Quitting");
 }
printf("\n press a key to continue…:");}
 while(choice!=2);}

3. Insertion

Insertion is the operation that inserts an element at a given location of the list. To insert an element at ith location of the list, then all elements from the right of i+ 1th location have to be shifted one step towards right.

Algorithm:
Step 1: Set upper_bound = upper_bound + 1
Step 2: Set A[upper_bound] = VAL
Step 3; EXIT
Step 1: [INITIALIZATION] SET I = N
Step 2: Repeat Steps 3 and 4 while I >= POS
Step 3: SET A[I + 1] = A[I]
Step 4: SET I = I – 1
[End of Loop]
Step 5: SET N = N + 1
Step 6: SET A[POS] = VAL
Step 7: EXIT

#include <stdio.h>
int main()
{ int array[100], position, i, n, value;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
printf("Enter the location where you wish to insert an element\n");
scanf("%d", &position);
printf("Enter the value to insert\n");
scanf("%d", &value);
for (i = n - 1; i >= position - 1; i--)
array[i+1] = array[i];array[position-1] = value;
printf("Resultant array is\n");
for (i = 0; i <= n; i++) printf("%d\n", array[i]);
return 0;
}

4. Deletion

Deletion is the operation that removes an element from a given location of the list.To delete an element from the ith location of the list, then all elements from the right of i+ 1th location have to be shifted one step towards left to preserve contiguous locations in the array.

Algorithm:
Step 1: Set upper_bound = upper_bound – 1
Step 2: EXIT
Step 1: [INITIALIZATION] SET I = POS
Step 2: Repeat Steps 3 and 4 while I <= N – 1
Step 3: SET A[I] = A[I + 1]
Step 4: SET I = I + 1
[End of Loop]
Step 5: SET N = N – 1
Step 6: EXIT

#include <stdio.h>
int main()
{
int array[100], position, i, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for ( i = 0 ; i< n ; i++ )
scanf("%d", &array[i]);
printf("Enter the location where you wish to delete element\n");
scanf("%d", &position);
if ( position >= n+1 )
printf("Deletion not possible.\n");
else
{
for ( i= position - 1 ; i < n - 1 ; i++ )
array[i] = array[i+1];
printf("Resultant array is\n");
for( i = 0 ; i < n - 1 ; i++ )
printf("%d\n", array[i]); 
}
return 0;
}

5. Searching

Search is an operation in which a given list is searched for a particular value. A list can be searched sequentially wherein the search for the data item starts from the beginning and continues till the end of the list. This method is called linear Search.. It is straightforward and works as follows: we compare each element with the element to search until we find it or the list ends.

linear Search

#include<stdio.h>
void main(){
int numlist[20];
int n,pos, val,i;
printf("\n enter the size of the list");
scanf("%d", &n);
printf("\n Enter the elements one by one");
for(i=0;i<n;i++){
scanf("%d", &numlist[i]);}
printf("\n Enter the value to be searched");
scanf("%d", &val);
for(i=0;i<n;i++){
if(val== numlist[i]) {
printf("%d is present at location %d.\n",val,i+1);
 break; }
if(i==n)
printf("%d isn't present in the array.\n",val);
}}

Binary Search

Binary search in C language to find an element in a sorted array. If the array isn’t sorted, you must sort it using a sorting technique such as bubble sort, insertion or selection sort. If the element to search is present in the list, then we print its location. The program assumes that the input numbers are in ascending order.

#include<stdio.h>
int main(){
 int c, first, last, midd, n, search, array[100];
 printf("Enter number of elements:\n");
 scanf("%d",&n);
 printf("Enter %d integers:\n", n);
 for (c = 0; c < n; c++)
 scanf("%d",&array[c]);
 printf("Enter the value to find:\n");
 scanf("%d", &search);
 first = 0;
 last = n - 1;

 while (first <= last) {
 midd = (first+last)/2;
 if (array[midd] == search)
 break;
 else if (search < array[midd])
 last = midd - 1;
 else
 first = midd + 1; }
 if (first > last)
 printf("Element not found");
 else
 printf("Element is at positoin %d",midd+1);}

One dimentional arrays for inter function communication are

  • Passing individual elements
  • Passing entire array

Summary

    Before using an array, its type and size must be declared.
  • The first element in the array is numbered 0, so the last element is 1 less than the size of the array.
  • The elements of the array are always stored in contiguous memory locations.
  • An array can be initialized at the same place where it is declared. Example: int num[6] = {2,4,12,5,45,5}. if the array is initialized at the time of declaration, mentioning the dimension of array is optional. Example: double dNum[] = {12.3, 34.2, -23.4, -11.3};
  • If the array elements are not given any specific values, they are supposed to contain garbage values.
  • In C there is no check to see if the subscript used for an array exceeds the size of the array. Data entered with a subscript exceeding the array size will simply be placed in memory outside the array. This will lead to unpredictable results, to say the least, and there will be no error messages to warn the programmer.
Related Post