• No results found

Learning Objectives

After completing this chapter, you will be able to:

 Understand the concept of array and its memory organisation

 Know how arrays are declared and initialized in C

 Use multi dimensional arrays

 Know about various character and string functions

Need for an Array

Many applications require the processing of multiple data items that have common characteristics (e.g., set of numbers, set of names). Array is a derived data type which is used to store similar data items in contiguous memory locations under a single name. It holds a fixed number of equally sized data elements, of the same data type. The individual elements are accessed by specifying the subscript.

Memory Organization of an Array

The elements in an array are always stored in consecutive memory locations. If an array of 5 integers elements is created, totally 10 contiguous bytes will be allocated in memory.

Note: size of an integer is assumed to be 2 bytes

Individual memory location is referred by index. [index 0 refers first location , index 1 refers second location, etc.]. Address of an array element is calculated as below:

Address of ith location = base address + (size of the individual data element * index i ) Address of 0th element = 1000 + (2 * 0) = 1000

Address of 1st element = 1000 + (2 * 1) = 1002 …

In C, the name of the array refers to the base address of the array.

1000 1002 1004 1006 1008

Starting address is assumed as 1000 and totally 10 bytes are created.

Declaration and Initialization

Array Declaration

Arrays are declared with appropriate data type and size. Arrays can be of single dimension or of multi dimensions. Array declaration reserves space in memory.

General Form:

datatype arrayname[size] ;

Arrays are defined by appending an integer encapsulated in square brackets at the end of a variable name. Each additional set of brackets defines an additional dimension to the array (multi dimensional arrays). When addressing an element in an array, indexing begins at 0 and ends at 1 less than the defined size of an array.

Example 6.1 int x[5];

Defines an integer array x of 5 integers, starting at x[0], and ending at x[4]. char str[16]="qwerty";

Defines a character array, which is represents a string of maximum of 16 characters. float sales_amt[10];

Defines a floating point array sales_amt of 10 floating point numbers, starting at sales_amt[0] and ending at sales_amt[9].

int matrix[2][2];

Defines a 2*2 matrix (totally 4 elements) of integers.

Accessing Array Elements

The array elements are accessed by specifying the subscript / index. General Form:

arrayname[index or subscript]

Example 6.2

x[0]  to access the 1st element in array x[4]  to access the 5th element in array

str[2]  to access the 3rd character in the string (character array) sales_amt [8]  to access the 9th sales amount in the array

Array Initialization

Array elements can be initialized during declaration or can be initialized in the program. When arrays are initialized during declaration, partial initialization is allowed. In partial initialization, the uninitialized array elements are initialized to Zero or Null depending on the data type of the array. Zero is initialized for numeric array and Null for character array.

If initialized, array can be declared without specifying the exact size. In such cases, size of the array equals the number of elements initialized.

General Form:

datatype arrayname[size] = {value(s)}; OR

datatype arrayname[ ] = {value(s)};

Example 6.3

int a[5]={1,2,3,4,5};

/*a[0] = 1, a[1] = 2 , a[2] = 3 , a[3] = 4 and a[4] = 5*/

int a[5]={0};

/*all the array elements are initialized to zero*/

int a[5]={1,2,3,4}; /*a[4] = 0*/

int a[ ] = {1,2,3,4};

/*a[0]=1, a[1]=2, a[2]=3, a[3]=4 (if size not specified, size depends upon the number of values initialized. ) */

float b[2]={10.2,45.34};

/* b[0] = 10.20 , b[1] = 45.34 */

Basic Operation on Arrays

Basic operations allowed on arrays are storing, retrieving, and processing of array elements. Insertion and deletion can be done by moving the array elements to the appropriate places. (ex. 3rd element can be deleted by moving 4th element to 3rd location, 5th element to 4th location and so on) Array name is a constant pointer (pointer is a variable which holds address of another variable) to the base address of the array. Thus, the base address can not be changed. The following expressions are illegal:

 a++ (base address of array ‘a’ is modified by adding one)  a+=2 (base address of array ‘a’ is modified by adding two)

Getting the value for Arrays

Input statement is used to get the values for an array.

Example 6.5 int a[3];

(1) scanf(“%d”, &a[0]); /*gets value for 1st location*/

scanf(“%d”, &a[1]);  gets value for 2nd

location*/

scanf(“%d”, &a[2]);  gets value for 3rd location*/

(2) scanf(“%d%d%d”, a, a+1, a+2);

/* gets value for first 3 locations (array name has the base address - pointer)*/

(3) for(i=0;i<3;i++)

scanf(“%d”,&a[i]);

/* usually loop statement is used to get the array elements*/

Printing out the array elements

Example 6.6 int a[3];

(1) printf(“%d”, a[0]); /*prints value of 1st location*/

printf(“%d”,a[1]); /*prints value of 2nd location*/

printf(“%d”, a[2]); /*prints value of 3rd location*/

(2) printf(“%d%d%d”,a[0],a[1],a[2]); /* prints value of first 3 locations*/ (3) for(i=0;i<3;i++)

printf(“%d”,a[i]);

/*loop statement is used to print the array elements */

Multi-dimensional Array

The elements of an array can themselves be arrays. Multidimensional arrays will also occupy the contiguous memory locations. Two dimensional arrays can be viewed as set of one dimensional array (rows & columns) and 3 dimensional arrays can be viewed as set of two dimensional arrays. Two-dimensional array – Declaration

Two-dimensional arrays are defined in the same way as one dimensional array, except that a separate pair of square brackets is required for second dimension.

General Form:

Example 6. 7

int a[2][2];  creates 8 bytes of contiguous memory locations. (2*2 = 4 elements).

Elements are stored in row major order. Elements of 1st row are stored first and then the elements of next row. It is necessary to specify the size of the column in declaration.

Assume that array starts at location 1000,

a[0][0] will be in location 1000 - row 0 & column 0 a[0][1] will be in location 1002 - row 0 & column 1 a[1][0] will be in location 1004 - row 1 & column 0 a[1][1] will be in location 1006 - row 1 & column 1

Two-dimensional array Initialization

Two-dimensional arrays can also be initialized in the declaration statement. In partial initialization, the uninitialized array elements are initialized to Zero.

Example 6.8

int num[2][3] = {1,2,3,4,5,6};

int num[2][3] = {1,2,3,4,5}; /*num[1][2] = 0*/ int num[2][3] = {{1,2,3},{1,2,3}};

/*row elements are initialized separately*/ int num[2][3] = {{1,2},{4}};

/*num[0][2] = 0 num[1][1]=num[1][2]=0*/

Example 6.9: 4-dimensional array

sales [year ] [month ] [area ] [salesperson]

Advantages

 Simple and easy to use  Stored in Contiguous locations

 Fast retrieval because of its indexed nature

 No need to worry about the allocation and de-allocation of arrays

Limitations

 Conventional arrays are static in nature. Memory is allocated in the beginning of the execution. If m elements are needed, out of n locations defined, n-m locations are unnecessarily wasted

Strings

Strings are sequence of characters. In C, there is no built-in data type for strings. String can be represented as a one-dimensional array of characters. A character string is stored in an array of character type, one ASCII character per location. String should always have a NULL character (‘\0’) at the end, to represent the end of string.

String constants can be assigned to character array variables. String constants are always enclosed within double quotes and character constants are enclosed within single quotes.

Example 6.10

(1) char c[4]={‘s’,’u’,’m’,’\0’);

(2) char str[16]="qwerty"; /*Creates a string. The value at str[5] is the character ‘y’. The value at str[6] is the null character. The values from str[7] to str[15] are undefined.*/ (3) char name[5]; int main( ) { name[0] = ‘G’; name[1] = ‘O’; name[2] = ‘O’; name[3] = ‘D’; name[4] = ‘\0’; return 0; }

(4) char name[5] = “INDIA” /* Strings are terminated by the null

character, it is preferred to allocate one extra space to store null terminator */

Array of Strings

Two dimensional character arrays are used to represent array of strings.

Declaration General Form:

char arrayname [no. of strings] [max no. of chars in strings];

Example 6.11

char studname[50][15];

Initialization General Form:

char arrayname [ r ] [ c ]={“values”};

Example 6.12

char name[3][5] = {“bata” ,”cat” ,”at”}

char name[3][5] = {{‘b’,’a’,’t’,’a’,’\0’}, {‘c’,’a’,’t’,’\0’},

{‘a’,’t’,’\0’}}

String can be read either character-by-character or as an entire string (using %s format specifier). Array name itself specifies the base address and %s is a format specifier which will read a string until a white space character is encountered.

[Note: no need to use & operator while reading string using %s]

Example 6.13 (1) char name[20]; int i=0; while((name[i] = getchar ()) != ‘\n’ ) i++; (2) scanf( “%s“ , name); (3) printf(“%s” , name);

Illegal operations on Strings

C does not allow one array to be assigned to another, thus statements of the following form are illegal”

 name = “GOOD”; Or name1 = name;  assignment not allowed

 name1 = name + “to c “  concatenation is not allowed

String Functions

 C does not provide any operator, which manipulates the entire string at once. Strings are manipulated either via pointers or via special routines available from the standard string library string.h.

The following is the list of string functions available in string.h:

String Functions Functionality

strcpy(string1, string2) Copy string2 into string1

strcat(string1, string2) Concatenate string2 onto the end of string1

strcmp(string1,string2) Lexically compares the two input strings (ASCII comparison) returns 0 if string1 is equal to string2

< 0 if string1 is less than string2 > 0 if string1 is greater than string2

strlen (string) Gives the length of a string

strrev (string) Reverse the string and result is stored in same string.

strncat(string1, string2, n) Append n characters from string2 to string1 strncmp(string1, string2, n) Compare first n characters of two strings. strncpy(string1,string2, n) Copy first n characters of string2 to string1

strupr (string) Converts string to uppercase

strlwr (string) Converts a string to lowercase

atoi (string) Converts the string to integer number atof (string) Converts the string to floating point number atol (string) Converts the string to long integer number strchr (string, c) Find first occurrence of character c in string. strrchr (string, c) Find last occurrence of character c in string. strstr(s1,s2) Locates the first occurrence of s2 in s1.

strpbrk(s1, s2) Returns a pointer to the first occurrence in s1 of any character from s2

strspn(s1, s2) Returns the number of characters at the beginning of s1 that match s2.

strcspn(s1, s2) Returns the number of characters at the beginning of s1 that do not

Character Functions

C provides the following collection of character functions, which can manipulate a single character. The header file, ctype.h, is used for the character functions.

Functions Functionality

int isalnum (c) True if c is alphanumeric. int isalpha (c) True if c is a letter. int isascii( c) True if c is ASCII .

int iscntrl (c) True if c is a control character (\n,\f,\r,\a) int isdigit (c) True if c is a decimal digit

int isgraph (c) True if c is a graphical character (all characters, except space) int islower (c) True if c is a lowercase letter

int isprint (c) True if c is a printable character (all characters including white space) int ispunct (c) True if c is a punctuation character (, . ,‘, ‘, “,:,)

int isspace( c) True if c is a space character (\n,\f,\r,\t,\v,’ ‘) int isupper (c) True if c is an uppercase letter

int isxdigit (c) True if c is a hexadecimal digit

toupper (x) Converts lowercase letter to uppercase

tolower (x) Converts uppercase to lowercase

toascii (x) Converts the char to ASCII value

Summary

 An array can be defined as a collection of homogenous elements stored in consecutive memory locations.

 Array name is a constant pointer to the base address of the array.

 Conventional array always has a predefined size and the elements of an array are referenced by means of an index / subscript.

 An array can be of more than one dimension. There is no restriction on the number of dimensions.

 String is represented as an array of characters.

Test your Understanding

1. Is it possible to declare an array x containing 50 integer elements followed immediately by 50 floating point numbers?

2. Why array index should always start with 0?

3. How entire array, x[100] with value 0, is initialized in declaration statement?

4. When a one dimensional array is being declared, under what condition may the size be omitted, with array name followed by an empty pair of square brackets?

5. What is the output of the following code? main()

{

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

printf(""\n %d %d %d"",a[2],a[3],a[4]); }

6. List few library functions for string operations. Answers:

1. No, array can contain only similar data items.

2. Array elements are accessed by relative addressing method (base address + index), in order to access the first element, which is in base address, index must be 0.

3. int x[100] = {0} ( partial initialization)

4. If an entire array is being initialized within the declaration. 5. 0 0 0

Related documents