Learning Objectives
After completing this session, you will be able to:
Explain the concept of Array and memory organization
Write program using Single-dimensional arrays
Write program using Multi-dimensional arrays
Understand Strings
Understand String and Character 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
Starting address is assumed as 1000 and totally 10 bytes are created.
1000 1002 1004 1006 1008
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.
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 7.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 7.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 7.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 7.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 7.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:
datatype arrayname [row ][column]
Example 7. 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 7.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 7.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
No automatic array bounds checking during compilation
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 7.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 7.11
char studname[50][15];
/* 50 student names each with 15 characters at the maximum */
Initialization
General Form:
char arrayname [ r ] [ c ]={“values”};
Example 7.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 7.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
if (name1 == name) Æ two strings cannot be compared with the ‘equal to’ operator
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 match s2.
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
Try It Out
1. Problem Statement:
Write a program to develop Fibonacci series using arrays Code:
#include <stdio.h>
main() {
int fib[24];
int i;
fib[0] = 0;
fib[1] = 1;
for(i = 2; i < 24; i++) fib[i] = fib[i-1] + fib[i-2];
for (i = 0; i < 24; i++)
printf("%3d %6d\n", i, fib[i]);
getchar();
}
Refer File Name: <sesh7_1.c> to obtain soft copy of the program code How It Works:
The Fibonacci series is 1,2,3,5,8,13…..
This program implemented fibonacci series by using for loop and array.The program computes the series up to 24 numbers.
Initially array of size 24 is declared, as we know the first two numbers initialize the first two elements in the array.
In the for loop start adding the values in the previous two indices of array and store it in the third element
Then increment the indices and keep continuing the same process until 24 numbers are added.
Again use the for loop to print the series one by one from the array.
2. Problem Statement:
Write a program to demonstrate two dimensional arrays Code:
#include <stdio.h>
main() {
int twod[4][5];
int i,j;
for(i=0; i<4; i++) for(j=0; j<5; j++) twod[i][j] = i*j;
for (i=0; i<4; i++) { for (j=0; j<5; j++) printf("%d ", twod[i][j]);
printf("\n");
}
getchar();
}
Refer File Name: <sesh7_2.c> to obtain soft copy of the program code How It Works:
This program explains the how to use the two dimensional array.
In two dimensional array, two indices will be used, one represent the row and the other one column. Here “i” represents row and the “j’ represents the column
Two for loops are used.
The outer loop decides the row and the inner loop represents the column
Initialise both i and j to 0.
For each value of i, find out all the values of column by multiplying the i with j with incremental of j.
Store the values in the array
Use another for loop to print the values in the two dimensional array in the form of matrix.
The program output looks like this:
o 00000 o 01234 o 02468 o 036912
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.
C supports a number of in-built string functions to manipulate strings.
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
6. strlen(), strcmp(), strcat(), strrev(), strcpy()