Saturday, March 16, 2013

Array 1D


There are times while writing C code, you may want to store multiple items of same type as contiguous bytes in memory so that searching and sorting of items becomes easy. For example:
  1. Storing a string that contains series of characters. Like storing a name in memory.
  2. Storing multiple strings. Like storing multiple names.
C programming language provides the concept of arrays to help you with these scenarios.

1. What is an Array?

An array is a collection of same type of elements which are sheltered under a common name.
An array can be visualized as a row in a table, whose each successive block can be thought of as memory bytes containing one element. Look at the figure below :
An Array of four elements:
+===================================================+
| elem1     |  elem2      | elem3      | elem4      |
+===================================================+
The number of 8 bit bytes that each element occupies depends on the type of array. If type of array is ‘char’ then it means the array stores character elements. Since each character occupies one byte so elements of a character array occupy one byte each.


2. How to Define an Array?

An array is defined as following :
<type-of-array> <name-of-array> [<number of elements in array>];
  • type-of-array: It is the type of elements that an array stores. If array stores character elements then type of array is ‘char’. If array stores integer elements then type of array is ‘int’. Besides these native types, if type of elements in array is structure objects then type of array becomes the structure.
  • name-of-array: This is the name that is given to array. It can be any string but it is usually suggested that some can of standard should be followed while naming arrays. At least the name should be in context with what is being stored in the array.
  • [number of elements]: This value in subscripts [] indicates the number of elements the array stores.
For example, an array of five characters can be defined as :
char arr[5];

3. How to Initialize an Array?

An array can be initialized in many ways as shown in the code-snippets below.
Initializing each element separately. For example :
int arr[10];
int i = 0;
for(i=0;i<sizeof(arr);i++)
{
  arr[i] = i; // Initializing each element seperately
}
Initializing array at the time of declaration. For example :
int arr[] = {'1','2','3','4','5'};
In the above example an array of five integers is declared. Note that since we are initializing at the time of declaration so there is no need to mention any value in the subscripts []. The size will automatically be calculated from the number of values. In this case, the size will be 5.
Initializing array with a string (Method 1):
Strings in C language are nothing but a series of characters followed by a null byte. So to store a string, we need an array of characters followed by a null byte. This makes the initialization of strings a bit different. Let us take a look :
Since strings are nothing but a series of characters so the array containing a string will be containing characters
char arr[] = {'c','o','d','e','\0'};
In the above declaration/initialization, we have initialized array with a series of character followed by a ‘\0′ (null) byte. The null byte is required as a terminating byte when string is read as a whole.
Initializing array with a string (Method 2):
char arr[] = "code";
Here we neither require to explicitly wrap single quotes around each character nor write a null character. The double quotes do the trick for us.

4. Accessing Values in an Array

Now we know how to declare and initialize an array. Lets understand, how to access array elements. An array element is accessed as :
int arr[10];
int i = 0;
for(i=0;i<sizeof(arr);i++)
{
  arr[i] = i; // Initializing each element separately
}
int j = arr[5]; // Accessing the 5th element of integer array arr and assigning its value to integer 'j'.
As we can see above, the 5th element of array is accessed as ‘arr[5]‘.
Note that for an array declared as int arr[5]. The five values are represented as: arr[0] arr[1] arr[2] arr[3] arr[4] and not arr[1] arr[2] arr[3] arr[4] arr[5]
The first element of array always has a subscript of ’0′


Example 1
int main(int argc, char *argv[])
{
 
    /* initializing an array */
    int array[12];
    int i;
    for(i = 0; i<12; ++i)
    {
          array[i] = 0;
    }  
   /*
      A second way of initializing an array is the following:
     int array[12] = {0,0,0,0,0,0,0,0,0,0,0,0};
  */
 
    printf( "%s%13s\n", "Element", "Value" );
    for(i = 0; i<12; ++i)
    {
          printf( "%7d%13d\n", i, array[ i ] );
    }  
 getchar();   
}
Example 2
Compute the sum of the elements of an array
int main(int argc, char *argv[])
{
 
    int a[ SIZE ] = { 1, 3, 5, 4, 7, 2, 99,16, 45, 67, 89, 45 };
    int i = 0;
    int total = 0;
    printf( "%s%13s\n", "Element", "Value" );
    for(i = 0; i<SIZE; ++i)
    {
          total+=a[i];
    }  
 
    printf( "Total of array element values is %d\n", total );
}
Example 3
Forty students were asked to rate the quality of the food in the student cafeteria on a scale
of 1 to 10 (1 means awful and 10 means excellent). Place the 40 responses in an integer
array and summarize the results of the poll.
/* Student poll program */
#include <stdio.h>
#define RESPONSE_SIZE 40
#define FREQUENCY_SIZE 11
 
int main()
{
 
 int answer, rating, frequency[ FREQUENCY_SIZE ] = { 0 };
 int responses[ RESPONSE_SIZE ] =
                { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10,
                  1, 6, 3, 8, 6, 10, 3, 8, 2, 7,
                  6, 5, 7, 6, 8, 6, 7, 5, 6, 6,
                  5, 6, 7, 5, 6, 4, 8, 6, 8, 10 };
 
 for ( answer = 0; answer <= RESPONSE_SIZE - 1; answer++ )
     ++frequency[ responses [ answer ] ];
 
 printf( "%s%17s\n", "Rating", "Frequency" );
 
 for ( rating = 1; rating <= FREQUENCY_SIZE - 1; rating++ )
  printf( "%6d%17d\n", rating, frequency[ rating ] );
 
 return 0;
}
Example 4
/*
This program reads numbers from an array and graphs the information
in the form of a bar chart or histogram—each number is printed, 
then a bar consisting of that many asterisks is printed beside the number.
*/
#include <stdio.h>
#define SIZE 10
int main()
{
 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };

 int i, j;
 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" );
 for(i = 0; i< SIZE; ++i)
 {
         printf( "%7d%13d ", i, n[ i ]) ;

         for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */
             printf( "%c", '*' );

         printf( "\n" );

 }                

return 0;
}

Character Arrays

string is a static array of individual characters in C.
A character array can be initialized using a string literal.
Example 5
The declaration
char string1[] = "first";
//string2 is the same
char string2[] = { 'f', 'i', 'r', 's', 't', '\0' };

Initializes the elements of array string1 to the individual characters in the string literal "first". The size of array string1 is five characters plus a special string termination character called the null character '\0'

No comments:

Post a Comment