MODULE 4:ARRAYS AND STRINGS CO4. Demonstrate the use of arrays, strings and structures in C language.
CONTENTS ● Introduction to Arrays ● Declaration and initialization of one dimensional and two- dimensional arrays. ● Definition and initialization of String ● String functions
INTRODUCTION TO ARRAYS An array is a group of elements (data items) that have common characteristics (eg numerical data, character data etc.,) and share a common name. The elements of an array are differentiated from one another by their positions within an array. Each array element(i.e., each individual data item) is referred to by specifying the array name followed by its subscript enclosed in square brackets. The subscript indicates the position of the particular element with respect to the rest of the elements. The subscript must be a non negative integer. For example, in the n element array , x, the array elements are x[1],x[2],x[3],x[4],..........x[n-1],x[n]; and 1,2,......n are the subscripts x[i] refers to the ith element in a list of n elements.
INTRODUCTION TO ARRAYS Types of arrays Single dimensional array Multidimensional array
SINGLE DIMENSIONAL ARRAY Declaration Of An Array An array is declared in the same manner as ordinary variables, except that each array name must be accompanied by a size specification. This is necessary because the complier will have to know how much memory to reserve for this array. A single dimensional array is declared as follows : type array_name[n]; where array_name is the name of an array of n elements of the type specified. The size of an array must be an integer constant. The integer array declaration int x[100]; creates an array that is 100 elements along with the first element being 0 and the last being 99.
SINGLE DIMENSIONAL ARRAY The subscript used to declare an array is sometimes called a dimension and the declaration for the array is often referred to as dimensioning. The dimension used to declare an array must always be a positive integer constant, or an expression that can be evaluated to a constant when the program is compiled. It is sometimes convinient to define an array size in terms of the symbolic constant. For example, i[20]=1234;
SINGLE DIMENSIONAL ARRAY An individual element in an array can be referred to by means of the subscript, the number in brackets following the array name. A subscript is the number that specifies the element’s position in an array. In the C language, subscript begins with zero. Thus, the valid subscript value can be from 0 to n-1, if n is the dimension of the array. The subscript value used to access an array element could result from a subscription variable, a unary expression, a binary expression etc. Thus, i[2] is not the second element of the array i but the third.
SINGLE DIMENSIONAL ARRAY int a[4];
INITIALIZING ARRAYS An array can be initialized when declared by specifying the values of some or all of its elements. Arrays can be intialized at the time of declaration when their intial values are known in advance. The values to intialize an array must be constants never variables or function calls. The array can be initialized as follows : int array[5]={4,6,5,7,2}; float x[6]={0,0.25,0,-0.50,0,0}; When an integer array is declared as, int array[5]={4,6,5,7,2}; the compiler will reserve ten contiguous bytes in memory to hold the five integer elements as shown in the diagram below :
INITIALIZING ARRAYS The array size need not be specified explicitly when intial values are included as a part of an array declaration. With a numerical array, the array size will automatically be set equal to the number of initial values included within the declaration. int digits[]={1,2,3,4,5,6}; float x[]={0,0.25,0,-0.5}; So digits will be a six-element integer array, and x will be a four- element floating-point array. The individual elements will be assigned the following values. The example given below illustrates this point. digits [0]=1;digits[1]=2;digits[2]=3; digits[3]=4;digits[4]=5 ;digits[5]=6;
INITIALIZING ARRAYS An array may also be intialized as follows : int xyz[10]={78,23,67,56,87,76}; In the above array initialization, although the array size is 10, values were defined only for the first six elements.
INITIALIZING ARRAYS Example int a[4]={4, 3, 2, 1}; /*Intializing and printing the value*/
INITIALIZING ARRAYS #include<stdio.h> int main() { int i,a[4]={4,3,2,1}; for(i=0;i<4;i++) { printf("a[%d]=%dn",i,a[i]); printf("Address of a[%d] is %un",i,&a[i]); } return 0; }
ARRAY OVERFLOW It is illegal to access a non-existent element of the array. C does not check for array overflow. It is the programmers responsibility to ensure that any subscription performed does not crosses the upper as well as the lower bounds of the array. int array[5]; array[5]=105; /* illegal as valid subscripting ends at array[4] */ In the above code, an attempt is made to move the binary value of 105 onto the 2 bytes that immediately follow the end of the array. So when executing the assignment array[5]=105, some other variables that the program uses are being overwritten.
PROCESSING AN ARRAY If a and b are two similar arrays of the same data type, same dimensions and same size then assignment operations and comparison operations etc, must be carried out on an element-by- element basis. This is done within a loop, where each pass through the loop is used to process an element of the array. The number of passes through the loop will there for equal to the number of array elements to be processed; and the value of the index (subscript) would be incremented from 0 to n-1.
MULTIDIMENSIONAL ARRAYS C as a language provides for arrays of arbitrary dimensions. A two dimensional array of size m rows by n columns is declared as follows : type array_name[m][n]; A two dimensional array, of type int, with 3 rows and 4 columns is declared as follows The array can be declared by passing values of number of rows and number of columns as subscript values. Example int a[3][4];
INITIALIZING ARRAYS The values can also be initialized by forming group of initial values enclosed within braces. The values within an inner pair of braces will be assigned to the element of a row or all the values can be given in single braces sequentially. Example int array[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}}; Or int array[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
PROCESSING AN ARRAY The array processing is done as in the one dimensional array. Since it is a two dimensional array we may need two variable to keep track and to process the data in the array.
CHARACTER ARRAYS (STRINGS) C Strings are nothing but array of characters ended with null character (‘0’). This null character indicates the end of the string. Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C. char string[20] = {‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘2’, ‘r’, ‘e’, ‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘0’}; (or) char string[20] = “fresh2refresh”; (or) char string [] = “fresh2refresh”; Difference between above declarations are, when we declare char as “string[20]”, 20 bytes of memory space is allocated for holding the string value. When we declare char as “string[]”, memory space will be allocated as per the requirement during execution of the program.
CHARACTER ARRAYS (STRINGS) Declaration Of An Array Array declaration is also done as same as normal array except for the specification of character data type. Example char a[5];
INITIALIZATION OF CHARACTER ARRAYS Character array can be initialized in two different ways. Firstly, they may initialize in the same way as the numeric array are initialized. char a[5] = {'H','a','r','i','0'}; (i.e.) by specifying character constants for each of the values. When initializing character by character, the null character ('0') should also be specified. Secondly, character array can also be initialized as follows, char a[5] ="Hari"; This type of initialization will include a provision for null character, which is automatically added at the end of the string.
PROCESSING A CHARACTER ARRAY Character arrays are different from the numerical array. The entire character string can be entered from the terminal and placed in a character array. Whereas numeric arrays can be input element by element only. Same is the case with output also. The entire string can be output using printf() function whereas an integer array can be output element by element only.
PROCESSING A CHARACTER ARRAY #include<stdio.h> #include<string.h> int main () { char a[6] ="Nikhat"; printf ("Name=%sn",a); }
PASSING STRINGS TO FUNCTION As strings are character arrays, so we can pass strings to function in a same way we pass an array to a function.
PASSING STRINGS TO FUNCTION // C program to illustrate how to // pass string to functions #include<stdio.h> void printStr(char str[]) { printf("String is : %s",str); } int main() { // declare and initialize string char str[] = “nikhat"; // print string by passing string // to a different function printStr(str); return 0; }
STRING FUNCTIONS Include string.h library to your program to use some of the inbuilt string manipulation functions present in the library.there are about 20-22 inbuilt string manipulating functions present in this library. The most common functions used from the library are: 1. strlen("name of string") 2. strcpy( dest, source) 3. strcmp( string1, string2 ) 4. strstr( str1, str2 ) Commonly Used String Functions strlen() - calculates the length of a string strcpy() - copies a string to another strcmp() - compares two strings strcat() - concatenates two strings
STRING FUNCTIONS
STRING FUNCTIONS
STRING FUNCTIONS The strlen() function takes a string as an argument and returns its length. The returned value is of type size_t (the unsigned integer type). It is defined in the <string.h> header file. #include <stdio.h> #include <string.h> int main() { char str1[20] = “nikhat"; printf("Length of string str1: %d", strlen(str1)); return 0; }
STRING FUNCTIONS strcmp() int strcmp(const char *str1, const char *str2) It compares the two strings and returns an integer value. If both the strings are same (equal) then this function would return 0 otherwise it may return a negative or positive value based on the comparison. If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value. If string1 > string2 then it would return positive value. If string1 == string2 then you would get 0(zero) when you use this function for compare strings.
STRING FUNCTIONS #include <stdio.h> #include <string.h> int main() { char s1[20] = “nikhat"; char s2[20] = “shaikh"; if (strcmp(s1, s2) ==0) { printf("string 1 and string 2 are equal"); }else { printf("string 1 and 2 are different"); } return 0; }
STRING FUNCTIONS Return value - if Return value if < 0 then it indicates str1 is less than str2 - if Return value if > 0 then it indicates str2 is less than str1 - if Return value if = 0 then it indicates str1 is equal to str2
STRING FUNCTIONS strcat() char *strcat(char *str1, char *str2) It concatenates two strings and returns the concatenated string. #include <stdio.h> #include <string.h> int main() { char s1[10] = "Hello"; char s2[10] = "World"; strcat(s1,s2); printf("Output string after concatenation: %s", s1); return 0; }
STRING FUNCTIONS strcpy() char *strcpy( char *str1, char *str2) It copies the string str2 into string str1, including the end character (terminator char ‘0’). #include <stdio.h> #include <string.h> int main() { char s1[30] = "string 1"; char s2[30] = "string 2 : I’m gonna copied into s1"; /* this function has copied s2 into s1*/ strcpy(s1,s2); printf("String s1 is: %s", s1); return 0; }
STRING FUNCTIONS strstr(str1, str2) This library function finds the first occurrence of the substring str2 in the string str1. The terminating '0' character is not compared. strstr( str1, str2); - str1: the main string to be scanned. - str2: the small string to be searched in str1 This function is very useful in checking whether str2 is a substring of str1 or not. Return value This function returns a pointer to the first occurrence in str1 of any of the entire sequence of characters specified in str2, or a NULL pointer if the sequence is not present in str1. .
STRING FUNCTIONS #include<stdio.h> #include<string.h> int main () { char str1[55] ="This is a test string for testing"; char str2[20]="test"; char *p; p = strstr (str1, str2); if(p) { printf("string foundn" ); //i.e str2 is a substring of str1. printf ("First occurrence of string "test" in "%s" is" " "%s"",str1, p); } else printf("string not foundn" ); // str2 is not a substring of str1. return 0; }

Module 4- Arrays and Strings

  • 1.
    MODULE 4:ARRAYS AND STRINGS CO4.Demonstrate the use of arrays, strings and structures in C language.
  • 2.
    CONTENTS ● Introduction toArrays ● Declaration and initialization of one dimensional and two- dimensional arrays. ● Definition and initialization of String ● String functions
  • 3.
    INTRODUCTION TO ARRAYS Anarray is a group of elements (data items) that have common characteristics (eg numerical data, character data etc.,) and share a common name. The elements of an array are differentiated from one another by their positions within an array. Each array element(i.e., each individual data item) is referred to by specifying the array name followed by its subscript enclosed in square brackets. The subscript indicates the position of the particular element with respect to the rest of the elements. The subscript must be a non negative integer. For example, in the n element array , x, the array elements are x[1],x[2],x[3],x[4],..........x[n-1],x[n]; and 1,2,......n are the subscripts x[i] refers to the ith element in a list of n elements.
  • 4.
    INTRODUCTION TO ARRAYS Typesof arrays Single dimensional array Multidimensional array
  • 5.
    SINGLE DIMENSIONAL ARRAY DeclarationOf An Array An array is declared in the same manner as ordinary variables, except that each array name must be accompanied by a size specification. This is necessary because the complier will have to know how much memory to reserve for this array. A single dimensional array is declared as follows : type array_name[n]; where array_name is the name of an array of n elements of the type specified. The size of an array must be an integer constant. The integer array declaration int x[100]; creates an array that is 100 elements along with the first element being 0 and the last being 99.
  • 6.
    SINGLE DIMENSIONAL ARRAY Thesubscript used to declare an array is sometimes called a dimension and the declaration for the array is often referred to as dimensioning. The dimension used to declare an array must always be a positive integer constant, or an expression that can be evaluated to a constant when the program is compiled. It is sometimes convinient to define an array size in terms of the symbolic constant. For example, i[20]=1234;
  • 7.
    SINGLE DIMENSIONAL ARRAY Anindividual element in an array can be referred to by means of the subscript, the number in brackets following the array name. A subscript is the number that specifies the element’s position in an array. In the C language, subscript begins with zero. Thus, the valid subscript value can be from 0 to n-1, if n is the dimension of the array. The subscript value used to access an array element could result from a subscription variable, a unary expression, a binary expression etc. Thus, i[2] is not the second element of the array i but the third.
  • 8.
  • 9.
    INITIALIZING ARRAYS An arraycan be initialized when declared by specifying the values of some or all of its elements. Arrays can be intialized at the time of declaration when their intial values are known in advance. The values to intialize an array must be constants never variables or function calls. The array can be initialized as follows : int array[5]={4,6,5,7,2}; float x[6]={0,0.25,0,-0.50,0,0}; When an integer array is declared as, int array[5]={4,6,5,7,2}; the compiler will reserve ten contiguous bytes in memory to hold the five integer elements as shown in the diagram below :
  • 10.
    INITIALIZING ARRAYS The arraysize need not be specified explicitly when intial values are included as a part of an array declaration. With a numerical array, the array size will automatically be set equal to the number of initial values included within the declaration. int digits[]={1,2,3,4,5,6}; float x[]={0,0.25,0,-0.5}; So digits will be a six-element integer array, and x will be a four- element floating-point array. The individual elements will be assigned the following values. The example given below illustrates this point. digits [0]=1;digits[1]=2;digits[2]=3; digits[3]=4;digits[4]=5 ;digits[5]=6;
  • 11.
    INITIALIZING ARRAYS An arraymay also be intialized as follows : int xyz[10]={78,23,67,56,87,76}; In the above array initialization, although the array size is 10, values were defined only for the first six elements.
  • 12.
    INITIALIZING ARRAYS Example int a[4]={4,3, 2, 1}; /*Intializing and printing the value*/
  • 13.
    INITIALIZING ARRAYS #include<stdio.h> int main() { inti,a[4]={4,3,2,1}; for(i=0;i<4;i++) { printf("a[%d]=%dn",i,a[i]); printf("Address of a[%d] is %un",i,&a[i]); } return 0; }
  • 14.
    ARRAY OVERFLOW It isillegal to access a non-existent element of the array. C does not check for array overflow. It is the programmers responsibility to ensure that any subscription performed does not crosses the upper as well as the lower bounds of the array. int array[5]; array[5]=105; /* illegal as valid subscripting ends at array[4] */ In the above code, an attempt is made to move the binary value of 105 onto the 2 bytes that immediately follow the end of the array. So when executing the assignment array[5]=105, some other variables that the program uses are being overwritten.
  • 15.
    PROCESSING AN ARRAY Ifa and b are two similar arrays of the same data type, same dimensions and same size then assignment operations and comparison operations etc, must be carried out on an element-by- element basis. This is done within a loop, where each pass through the loop is used to process an element of the array. The number of passes through the loop will there for equal to the number of array elements to be processed; and the value of the index (subscript) would be incremented from 0 to n-1.
  • 16.
    MULTIDIMENSIONAL ARRAYS C asa language provides for arrays of arbitrary dimensions. A two dimensional array of size m rows by n columns is declared as follows : type array_name[m][n]; A two dimensional array, of type int, with 3 rows and 4 columns is declared as follows The array can be declared by passing values of number of rows and number of columns as subscript values. Example int a[3][4];
  • 17.
    INITIALIZING ARRAYS The valuescan also be initialized by forming group of initial values enclosed within braces. The values within an inner pair of braces will be assigned to the element of a row or all the values can be given in single braces sequentially. Example int array[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}}; Or int array[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
  • 18.
    PROCESSING AN ARRAY Thearray processing is done as in the one dimensional array. Since it is a two dimensional array we may need two variable to keep track and to process the data in the array.
  • 19.
    CHARACTER ARRAYS (STRINGS) CStrings are nothing but array of characters ended with null character (‘0’). This null character indicates the end of the string. Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C. char string[20] = {‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘2’, ‘r’, ‘e’, ‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘0’}; (or) char string[20] = “fresh2refresh”; (or) char string [] = “fresh2refresh”; Difference between above declarations are, when we declare char as “string[20]”, 20 bytes of memory space is allocated for holding the string value. When we declare char as “string[]”, memory space will be allocated as per the requirement during execution of the program.
  • 20.
    CHARACTER ARRAYS (STRINGS) DeclarationOf An Array Array declaration is also done as same as normal array except for the specification of character data type. Example char a[5];
  • 21.
    INITIALIZATION OF CHARACTER ARRAYS Characterarray can be initialized in two different ways. Firstly, they may initialize in the same way as the numeric array are initialized. char a[5] = {'H','a','r','i','0'}; (i.e.) by specifying character constants for each of the values. When initializing character by character, the null character ('0') should also be specified. Secondly, character array can also be initialized as follows, char a[5] ="Hari"; This type of initialization will include a provision for null character, which is automatically added at the end of the string.
  • 22.
    PROCESSING A CHARACTER ARRAY Characterarrays are different from the numerical array. The entire character string can be entered from the terminal and placed in a character array. Whereas numeric arrays can be input element by element only. Same is the case with output also. The entire string can be output using printf() function whereas an integer array can be output element by element only.
  • 23.
    PROCESSING A CHARACTER ARRAY #include<stdio.h> #include<string.h> intmain () { char a[6] ="Nikhat"; printf ("Name=%sn",a); }
  • 24.
    PASSING STRINGS TOFUNCTION As strings are character arrays, so we can pass strings to function in a same way we pass an array to a function.
  • 25.
    PASSING STRINGS TOFUNCTION // C program to illustrate how to // pass string to functions #include<stdio.h> void printStr(char str[]) { printf("String is : %s",str); } int main() { // declare and initialize string char str[] = “nikhat"; // print string by passing string // to a different function printStr(str); return 0; }
  • 26.
    STRING FUNCTIONS Include string.hlibrary to your program to use some of the inbuilt string manipulation functions present in the library.there are about 20-22 inbuilt string manipulating functions present in this library. The most common functions used from the library are: 1. strlen("name of string") 2. strcpy( dest, source) 3. strcmp( string1, string2 ) 4. strstr( str1, str2 ) Commonly Used String Functions strlen() - calculates the length of a string strcpy() - copies a string to another strcmp() - compares two strings strcat() - concatenates two strings
  • 27.
  • 28.
  • 29.
    STRING FUNCTIONS The strlen()function takes a string as an argument and returns its length. The returned value is of type size_t (the unsigned integer type). It is defined in the <string.h> header file. #include <stdio.h> #include <string.h> int main() { char str1[20] = “nikhat"; printf("Length of string str1: %d", strlen(str1)); return 0; }
  • 30.
    STRING FUNCTIONS strcmp() int strcmp(constchar *str1, const char *str2) It compares the two strings and returns an integer value. If both the strings are same (equal) then this function would return 0 otherwise it may return a negative or positive value based on the comparison. If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value. If string1 > string2 then it would return positive value. If string1 == string2 then you would get 0(zero) when you use this function for compare strings.
  • 31.
    STRING FUNCTIONS #include <stdio.h> #include<string.h> int main() { char s1[20] = “nikhat"; char s2[20] = “shaikh"; if (strcmp(s1, s2) ==0) { printf("string 1 and string 2 are equal"); }else { printf("string 1 and 2 are different"); } return 0; }
  • 32.
    STRING FUNCTIONS Return value -if Return value if < 0 then it indicates str1 is less than str2 - if Return value if > 0 then it indicates str2 is less than str1 - if Return value if = 0 then it indicates str1 is equal to str2
  • 33.
    STRING FUNCTIONS strcat() char *strcat(char*str1, char *str2) It concatenates two strings and returns the concatenated string. #include <stdio.h> #include <string.h> int main() { char s1[10] = "Hello"; char s2[10] = "World"; strcat(s1,s2); printf("Output string after concatenation: %s", s1); return 0; }
  • 34.
    STRING FUNCTIONS strcpy() char *strcpy(char *str1, char *str2) It copies the string str2 into string str1, including the end character (terminator char ‘0’). #include <stdio.h> #include <string.h> int main() { char s1[30] = "string 1"; char s2[30] = "string 2 : I’m gonna copied into s1"; /* this function has copied s2 into s1*/ strcpy(s1,s2); printf("String s1 is: %s", s1); return 0; }
  • 35.
    STRING FUNCTIONS strstr(str1, str2) Thislibrary function finds the first occurrence of the substring str2 in the string str1. The terminating '0' character is not compared. strstr( str1, str2); - str1: the main string to be scanned. - str2: the small string to be searched in str1 This function is very useful in checking whether str2 is a substring of str1 or not. Return value This function returns a pointer to the first occurrence in str1 of any of the entire sequence of characters specified in str2, or a NULL pointer if the sequence is not present in str1. .
  • 36.
    STRING FUNCTIONS #include<stdio.h> #include<string.h> int main() { char str1[55] ="This is a test string for testing"; char str2[20]="test"; char *p; p = strstr (str1, str2); if(p) { printf("string foundn" ); //i.e str2 is a substring of str1. printf ("First occurrence of string "test" in "%s" is" " "%s"",str1, p); } else printf("string not foundn" ); // str2 is not a substring of str1. return 0; }