Arrays & Strings
Definition of Array An array is a fixed – size sequenced collection of elements of the same data type. It is simply a grouping of like – type data. In its simplest form, an array can be used to represent a list of numbers, or list of names. (OR) “A set of consecutive storage location referred by a single name to store homogeneous data type.” int A[10] Array is a Collection of Homogenous Data Items Example 1. List of employees in an organization. 2. List of products and their cost sold by a store. 3. Test Scores of a class of students. 12/6/2020 2
1. One Dimensional Array. 2. Two Dimensional Array. 3. Multi Dimensional Array Types of Array
One Dimensional Array 12/6/2020 4 X Y Z One Dimensional Array is defined any one of axis (X or Y or Z) in the graph
Arrays So far, we've been declaring simple variables int i; It is also possible to declare an array of Several elements. an array is a variable that can hold more than one value , The declaration int a[10]; declares an array, named a, consisting of ten elements, each of type int. We can represent the array a above with a picture like this: 12/6/2020 5 •Arrays are zero-based: the ten elements of a 10-element array are numbered from 0 to 9.
• An array uses a single identifier, together with an integer index, to create one variable that can hold many values • An array is created the same as a “normal” variable, but with the addition of square brackets indicating the size of the array • Each value in the array is called an element 12/6/2020 6 Arrays
One Dimensional Arrays Syntax data_type array_name[size]; Description Data_type valid data type in C language Array_name name given to the array Size are the size of the dimensions Example int a[3]; float b[4]; 12/6/2020 7
Initializing Arrays • An array is initialized using a code block containing comma-delimited values which match in position the elements in the array • If there are values in the initialization block, but not enough to fill the array, all the elements in the array without values are initialized to 0 in the case of float or int, and NULL in the case of char • If there are values in the initialization block, an explicit size for the array does not need to be specified, only an empty Array Element Operator is needed. C will count the values and size the array for you. 12/6/2020 8
Initializing Arrays int x [ 5 ] = { 1,2,3,4,5 }; size 10 bytes creates array with elements 0-4 values 1-5 int x [ 5 ] = { 4,3 }; size 10 bytes creates array with elements 0-4 values 4,3,0,0,0 int x [ ] = { 1,2,3 }; size 6 bytes creates array with elements 0-2 values 1,2,3 char c [ 4 ] = { ‘M’ , ‘o’ , ‘o’ }; size 4 bytes creates array with elements 0-3 values M o o NULL 12/6/2020 9
Arrays •The first element of the array is x[0], the second element is x[1].. e.g x[0] = 10; x[1] = 20; x[2] = 30 x[3] = 40 x[4] = 50 Total = 150; This loop sets all ten elements of the array a to 0. int a[i]; int i; for(i = 0; i < 10; i = i + 1) a[i] = 0; To copy the contents of one array to another, you must again do so one by one: int b[10]; for(i = 0; i < 10; i = i + 1) b[i] = a[i]; Printing Array Values for(i = 0; i < 10; i = i + 1) printf("%dn", a[i]); 12/6/2020 10
Array Basics • An array has a fixed number of elements based on its creation • The elements are ALWAYS numbered from 0 to 1 less than the array’s size • Referencing an element outside of the created bounds is possible but not recommended 12/6/2020 11
Visual Representation of an Array 12/6/2020 12 Identifier? ? 23 ? int x[4]; x[2]=23; 342901 342903 342905 342917 0 1 2 3 X Address Offset Value
The Array Element Operator [ ] • The Array Element Operator is used to reference a specific array element • The expression inside the Array Element must resolve to type int. This value is known as an index • The value of the index can be any number, but care should be taken that the index falls within the bounds of the array. The bounds of an array are defined as 0 to 1 less than the size of the array 12/6/2020 13
Array Example #include <stdio.h> int main(void) { int x[5]; x[0]=23; valid x[2.3]=5; invalid: index is not an int x[6]=45; valid but not recommended return 0; } 12/6/2020 14
A Simple Array Example #include <stdio.h> int main(void) { int i , x[ 5 ] , total = 0 ; for ( i = 0 ; i < 5 ; i++ ) { printf( “Enter mark %d” , i ); scanf ( “%d” , &x[ i ] ); } for ( i = 0 ; i < 5 ; i++ ) total = total + x[ i ]; printf ( “The average is %d” , total / 5 ); return 0; } 12/6/2020 15
ARRAYS • DON'T declare arrays with subscripts larger than you will need; it wastes memory. • DON'T forget that in C, arrays are referenced starting with subscript 0, not 1. 12/6/2020 16
Sample program #include<stdio.h> main() { int a[5],i; printf(‘enter the array elements”); for(i = 0;i<5;i++) scanf(“%d”, &a[i]); printf(“Array in the reverse order”); for(i = 5;i>0;i--) printf(“%d”,a[i]); } 12/6/2020 17
#inlcude<stdio.h> #define Max 5; main(); { int a[Max], i, min; int pos = 0; printf(“Enter the array elements”); for(i=0;i<5;i++) scanf(‘%d”,&a[i]); min = a[0]; for(i=1;i<Max;i++) if(a[i] < min) { min = a[i]; pos = i; } printf(“ Minimum Value = %d” , min); printf(“ Position of the Minimum Value = %d” , pos); } 12/6/2020 18
Two-Dimensional Arrays • Two-dimensional Array: a collection of a fixed number of components arranged in two dimensions • All components are of the same type • The syntax for declaring a two-dimensional array is: dataType arrayName[intexp1][intexp2]; where intexp1 and intexp2 are expressions yielding positive integer values 12/6/2020 19
Two-Dimensional Arrays (continued) • The two expressions intexp1 and intexp2 specify the number of rows and the number of columns, respectively, in the array • Two-dimensional arrays are sometimes called matrices or tables 12/6/2020 20
Two Dimensional Array 12/6/2020 21 Two Dimensional Array is defined any Two of axis of XY or YZ or ZX in the graph X Y Z
12/6/2020 22
Two Dimensional Arrays Syntax data_type array_name[size_1][size_2]; Description Data_type valid data type in C language Array_name name given to the array Size_1 is the row size of the array Size_2 is the column size of the array Example int a[3][3]; float b[4][4]; Int a[3][2]; 12/6/2020 23
Two Dimensional Array Initializing int table [2][3] = {0,0,0,1,1,1}; int table [2][3] = {{0,0,0},{1,1,1}}; int table [2][3] = { {0,0,0}, {1,1,1} }; int table [ ][3] = { {0,0,0} {1,1,1} }; 12/6/2020 24
Two Dimensional Array Initializing If the values are missing in an initializer, they are automatically set to zero. For instance, the statement int table [2][3] = {{1,1}, {2}}; will initialize the first two elements of the first row to one, the first element of the second row to two , and all other elements to zero. When all the elements are to be initialized to zero, the following short – cut method may be used. int m[3][5] = { {0},{0},{0} }; The first element of each row is explicitly initialized to zero while other elements are automatically initialized to zero, The following statement will also achieve the same result: int m[3][5] = {0,0}; 12/6/2020 25
Accessing Array Components • The syntax to access a component of a two-dimensional array is: arrayName[indexexp1][indexexp2] where indexexp1 and indexexp2 are expressions yielding nonnegative integer values • indexexp1 specifies the row position and indexexp2 specifies the column position 12/6/2020 26
0 1 2 0 1 2 3 4 25.75 12/6/2020 27
Multi – Dimensional Arrays 12/6/2020 28 X Y Z • Three or More Dimensional Array is called the Multi – Dimensional Arrays. • Three Dimensional array defined in any three of axis of XYZ OR YZX OR ZXY in the graph
Multi Dimensional Arrays • This arrays have more than one dimensions. Syntax data_type array_name[size1][size2]…….[sizen]; Description Data_type valid data type in C language Array_name name given to the array Size1,size2 are the sizes of the dimensions Example Int a[3][3][3]; Float b[4][4][4]; 12/6/2020 29
CHARACTER ARRAYS AND STRINGS 12/6/2020 30
Character and Strings • An char array is a group of characters that store related data • A String is a special char array that does not store related data, but a single piece of data made up of a number of characters OR A string is a sequence of character that is treated as a single data item. Any group of characters defined between double quotation marks is a string constant. • Example: Grades can be stored in a char array with the values A,B,C,D,F; when we want to print a specific grade we use only 1 element of the array • Example: But for grades like “Pass” and “Fail” we must print ALL the elements 12/6/2020 31
String Conti… • Most Computers languages have a string data type; C does NOT • There are 3 ways to store strings in memory • Fixed Length • Stored Length • Terminated • C adopts the Terminated String approach • A string in C is an array of chars terminated by the String Terminator or NULL character 0 12/6/2020 32
Common String Operation 1. Reading and Writing Strings 2. Combining strings together 3. Copying one string to another 4. Comparing strings for equality 5. Extracting a portion of a string 12/6/2020 33
Declaring and Initializing of String The General form of String is char string_name [size]; Example: char city [10]; char name[30]; When the complier assigns a character string to a character array, it automatically supplies a multicharacter (‘0’) at the end of the string. Therefore, the size should be equal to the maximum number of characters in the string plus one. C Permits a character array to be initialized in either of the following two forms: char city [9] = “ NEW YORK”; char city [9] = {‘N’.’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’0’); C also permits us to initialize a character array without specifying the number of elements. In such cases, the size of the array will be determined automatically, base on the number of elements initialiazed. For Example, the statement char string [ ] = {‘G’,’O’,’O’,’D’,’0’}; 12/6/2020 34
Declaring Conti…. We can also declare the size much larger than the string size in the initializer. That is, the statement. char str[9] = “GOOD”; 12/6/2020 35 G O O D 0 0 0 0 0 The following declaration is illegal. (I) char str[5]; str = “GOOD”; This will result in a compile time error. Also note that we cannot separate the initialization from declaration. (II) char s1[4] = “abc”; char s2[4]; s2 = s2; /* Error */ is not allowed. An array name cannot be used as the left operand of an assignment operator.
Creating a String in C 12/6/2020 36 h i ! array1820 1821 1822 h i ! /0 string2820 2821 2822 2823
READING STRINGS FROM TERMINAL The familiar input function scanf can be used with %s format specification to read in a string of characters. Example: char address [10]; scanf(“%s”,address); The problem with the scanf function is that it terminates its input on the first white space it finds. Therefore, if the following line of text is typed in at the terminal, NEW YORK then only the string “NEW” will be read into the array address, since the blank space after the word ‘NEW’ will terminate the string reading. The scanf calls in the case of character arrays, the ampersand (&) is not required before the variable name. The address array is created in the memory as shown below: 12/6/2020 37 N E W O ? ? ? ? ? ? Note that the unused locations are filled with garbage. If we want to read the entire line “NEW YORK”, then we may use two character arrays of approximate sizes. That is, char adr1[5], adr2[5]; scanf(“%s %s”,adr1,adr2); With the line of text NEW YORK
READING STRINGS FROM TERMINAL 12/6/2020 38 We can also specify the field width using the form %ws in the scanf statement for reading a specified number of characters from the input string. Example: scanf(“%ws”,name); Here two things may happen. 1. The width w is equal to or greater than the number of characters typed in. The entire string will be stored in the string variable. 2. The width w is less than the number of characters in the string. The excess characters will be truncated and left unread. Consider the following statements: char name [10]; scanf(“%5s”,name); The input string RAM and KRISHNA will be stored as: R A M 0 ? ? ? ? ? ? K R I S H 0 ? ? ? ?
Reading a Line of Text We have seen just now that scanf with %s or %ws can read only strings without white spaces. That is, they cannot be used for reading a text containing more than one word. However, C Supports a format specification known as the edit set conversion code % [..] that can be used to read a line containing a variety of characters, including white spaces. Recall that we have used this conversion code in the program segment char line [80]; scanf (“%[^n]”,line); printf(“%s”,line); will read a line of input from the keyboard and display the same on the screen. We would very rarely use this method. 12/6/2020 39 Using getchar and gets Functions To read a single character from the terminal, using the function getchar. We can use this function repeatedly to read successive single characters from the input and place them into a character array. Thus, an entire line of text can be read and stored in an array. The reading is terminated when the newline character (‘n’) is entered and the null character is then inserted at the end of the string. The getchar function call takes the form: char ch; ch = getchar ( ); Note that the getchar function has no parameters.
12/6/2020 40 #include <stdio.h> void main() { char line[81], character; int c; c = 0; printf("Enter text. Press <Return> at endn"); do { character = getchar( ); line[c] = character; c++; } while(character != 'n'); c = c - 1; line [c] = '0'; printf("n%sn", line); }
getchar and gets Conti…. Another and more convenient method of reading a string of text containing white spaces is to use the library function gets available in the <stdio.h> header file. This is a simple function with one string parameter and called as under. gets (str); str is string variable declared properly. It reads characters into str from the keyboard until a new line character is encountered and then appends a null character to the string. Unlike scanf, it does not skip white spaces. For example the code segment char line [80]; gets (line); printf(“%s”,, line); reads a line of text from the keyboard and displays it on the screen. The last two statements may be combined as follows: printf(“%s”,gets(line)); C does not provide operators that work on strings directly. For instance we cannot assign one string to another directly. For example, the assignment statements. string = “ABC” string1 = string2; are not valid. 12/6/2020 41
12/6/2020 42 #include<stdio.h> void main() { char string1[80],string2[80]; int i; printf("Enter a string n"); printf("?"); scanf("%s",string2); for(i=0;string2[i] != 'o'; i++) string1[i] = string2[i]; string1[i] = 'o'; printf("n"); printf("%sn", string1); printf("Number of characters = %dn",i); }
12/6/2020 43 WRITING A STRINGS TO SCREEN We have used extensively the printf function with %s format to print strings to the screen. The format %s can be used to display an array of characters that is terminated by the null character. For example, the statement printf(“%s”, name); can be used to display the entire contents of the array name. We can also specify the precision with which the array is displayed. For instance, the specification %10.4 Indicates that the first four characters are to be printed in a field width of 10 columns. However, if we include the minus sign in the specification (e.g., %-10.4s), the string will be printed left-justified. Using putchar and puts Functions Like getchar, C supports another character handling function putchar to output the values of character variables. It takes the following form: char ch = ‘A’; putchar (ch); The function putchar requires one parameter. This statement is equivalent to: printf(“%c”,ch); We have used putchar function to write characters to the screen. We can use this function repeatedly to output a string of characters stored in an array using a loop:
12/6/2020 44 Example: char name[6] = “PARIS”; for(i=0;i<5;i++) putchar (name[i]); putchar(‘n’); Another and more convenient way of printing string values is to use the function puts declared in the header file <stdio.h>. This is a one parameter function and invoked as under: puts (str); Where str is a string variable containing a string value. This prints the value of the string variable str and then moves the cursor to the beginning of the next line on the screen. For example, the program segment char line [80]; gets (line); puts (line); Reads a line of text from the keyboard and displays it on the screen. Note that the syntax is very simple compared to using the scanf and printf statements Using putchar and puts Functions Conti…
Function Action strcat ( ) Concatenates two strings strcmp ( ) Compares two strings strcpy ( ) Copies one strings over another strlen ( ) Finds the length of a string 12/6/2020 45 The C Library supports a large number of string – handling function that can be used to carry out many of the string manipulations. The most commonly used string – handling functions. STRING HANDLING FUNCTIONS

Arrays & Strings

  • 1.
  • 2.
    Definition of Array Anarray is a fixed – size sequenced collection of elements of the same data type. It is simply a grouping of like – type data. In its simplest form, an array can be used to represent a list of numbers, or list of names. (OR) “A set of consecutive storage location referred by a single name to store homogeneous data type.” int A[10] Array is a Collection of Homogenous Data Items Example 1. List of employees in an organization. 2. List of products and their cost sold by a store. 3. Test Scores of a class of students. 12/6/2020 2
  • 3.
    1. One DimensionalArray. 2. Two Dimensional Array. 3. Multi Dimensional Array Types of Array
  • 4.
    One Dimensional Array 12/6/20204 X Y Z One Dimensional Array is defined any one of axis (X or Y or Z) in the graph
  • 5.
    Arrays So far, we'vebeen declaring simple variables int i; It is also possible to declare an array of Several elements. an array is a variable that can hold more than one value , The declaration int a[10]; declares an array, named a, consisting of ten elements, each of type int. We can represent the array a above with a picture like this: 12/6/2020 5 •Arrays are zero-based: the ten elements of a 10-element array are numbered from 0 to 9.
  • 6.
    • An arrayuses a single identifier, together with an integer index, to create one variable that can hold many values • An array is created the same as a “normal” variable, but with the addition of square brackets indicating the size of the array • Each value in the array is called an element 12/6/2020 6 Arrays
  • 7.
    One Dimensional Arrays Syntaxdata_type array_name[size]; Description Data_type valid data type in C language Array_name name given to the array Size are the size of the dimensions Example int a[3]; float b[4]; 12/6/2020 7
  • 8.
    Initializing Arrays • Anarray is initialized using a code block containing comma-delimited values which match in position the elements in the array • If there are values in the initialization block, but not enough to fill the array, all the elements in the array without values are initialized to 0 in the case of float or int, and NULL in the case of char • If there are values in the initialization block, an explicit size for the array does not need to be specified, only an empty Array Element Operator is needed. C will count the values and size the array for you. 12/6/2020 8
  • 9.
    Initializing Arrays int x[ 5 ] = { 1,2,3,4,5 }; size 10 bytes creates array with elements 0-4 values 1-5 int x [ 5 ] = { 4,3 }; size 10 bytes creates array with elements 0-4 values 4,3,0,0,0 int x [ ] = { 1,2,3 }; size 6 bytes creates array with elements 0-2 values 1,2,3 char c [ 4 ] = { ‘M’ , ‘o’ , ‘o’ }; size 4 bytes creates array with elements 0-3 values M o o NULL 12/6/2020 9
  • 10.
    Arrays •The first elementof the array is x[0], the second element is x[1].. e.g x[0] = 10; x[1] = 20; x[2] = 30 x[3] = 40 x[4] = 50 Total = 150; This loop sets all ten elements of the array a to 0. int a[i]; int i; for(i = 0; i < 10; i = i + 1) a[i] = 0; To copy the contents of one array to another, you must again do so one by one: int b[10]; for(i = 0; i < 10; i = i + 1) b[i] = a[i]; Printing Array Values for(i = 0; i < 10; i = i + 1) printf("%dn", a[i]); 12/6/2020 10
  • 11.
    Array Basics • Anarray has a fixed number of elements based on its creation • The elements are ALWAYS numbered from 0 to 1 less than the array’s size • Referencing an element outside of the created bounds is possible but not recommended 12/6/2020 11
  • 12.
    Visual Representation ofan Array 12/6/2020 12 Identifier? ? 23 ? int x[4]; x[2]=23; 342901 342903 342905 342917 0 1 2 3 X Address Offset Value
  • 13.
    The Array ElementOperator [ ] • The Array Element Operator is used to reference a specific array element • The expression inside the Array Element must resolve to type int. This value is known as an index • The value of the index can be any number, but care should be taken that the index falls within the bounds of the array. The bounds of an array are defined as 0 to 1 less than the size of the array 12/6/2020 13
  • 14.
    Array Example #include <stdio.h> intmain(void) { int x[5]; x[0]=23; valid x[2.3]=5; invalid: index is not an int x[6]=45; valid but not recommended return 0; } 12/6/2020 14
  • 15.
    A Simple ArrayExample #include <stdio.h> int main(void) { int i , x[ 5 ] , total = 0 ; for ( i = 0 ; i < 5 ; i++ ) { printf( “Enter mark %d” , i ); scanf ( “%d” , &x[ i ] ); } for ( i = 0 ; i < 5 ; i++ ) total = total + x[ i ]; printf ( “The average is %d” , total / 5 ); return 0; } 12/6/2020 15
  • 16.
    ARRAYS • DON'T declarearrays with subscripts larger than you will need; it wastes memory. • DON'T forget that in C, arrays are referenced starting with subscript 0, not 1. 12/6/2020 16
  • 17.
    Sample program #include<stdio.h> main() { int a[5],i; printf(‘enterthe array elements”); for(i = 0;i<5;i++) scanf(“%d”, &a[i]); printf(“Array in the reverse order”); for(i = 5;i>0;i--) printf(“%d”,a[i]); } 12/6/2020 17
  • 18.
    #inlcude<stdio.h> #define Max 5; main(); { inta[Max], i, min; int pos = 0; printf(“Enter the array elements”); for(i=0;i<5;i++) scanf(‘%d”,&a[i]); min = a[0]; for(i=1;i<Max;i++) if(a[i] < min) { min = a[i]; pos = i; } printf(“ Minimum Value = %d” , min); printf(“ Position of the Minimum Value = %d” , pos); } 12/6/2020 18
  • 19.
    Two-Dimensional Arrays • Two-dimensionalArray: a collection of a fixed number of components arranged in two dimensions • All components are of the same type • The syntax for declaring a two-dimensional array is: dataType arrayName[intexp1][intexp2]; where intexp1 and intexp2 are expressions yielding positive integer values 12/6/2020 19
  • 20.
    Two-Dimensional Arrays (continued) •The two expressions intexp1 and intexp2 specify the number of rows and the number of columns, respectively, in the array • Two-dimensional arrays are sometimes called matrices or tables 12/6/2020 20
  • 21.
    Two Dimensional Array 12/6/202021 Two Dimensional Array is defined any Two of axis of XY or YZ or ZX in the graph X Y Z
  • 22.
  • 23.
    Two Dimensional Arrays Syntaxdata_type array_name[size_1][size_2]; Description Data_type valid data type in C language Array_name name given to the array Size_1 is the row size of the array Size_2 is the column size of the array Example int a[3][3]; float b[4][4]; Int a[3][2]; 12/6/2020 23
  • 24.
    Two Dimensional ArrayInitializing int table [2][3] = {0,0,0,1,1,1}; int table [2][3] = {{0,0,0},{1,1,1}}; int table [2][3] = { {0,0,0}, {1,1,1} }; int table [ ][3] = { {0,0,0} {1,1,1} }; 12/6/2020 24
  • 25.
    Two Dimensional ArrayInitializing If the values are missing in an initializer, they are automatically set to zero. For instance, the statement int table [2][3] = {{1,1}, {2}}; will initialize the first two elements of the first row to one, the first element of the second row to two , and all other elements to zero. When all the elements are to be initialized to zero, the following short – cut method may be used. int m[3][5] = { {0},{0},{0} }; The first element of each row is explicitly initialized to zero while other elements are automatically initialized to zero, The following statement will also achieve the same result: int m[3][5] = {0,0}; 12/6/2020 25
  • 26.
    Accessing Array Components •The syntax to access a component of a two-dimensional array is: arrayName[indexexp1][indexexp2] where indexexp1 and indexexp2 are expressions yielding nonnegative integer values • indexexp1 specifies the row position and indexexp2 specifies the column position 12/6/2020 26
  • 27.
    0 1 2 0 1 2 3 425.75 12/6/2020 27
  • 28.
    Multi – DimensionalArrays 12/6/2020 28 X Y Z • Three or More Dimensional Array is called the Multi – Dimensional Arrays. • Three Dimensional array defined in any three of axis of XYZ OR YZX OR ZXY in the graph
  • 29.
    Multi Dimensional Arrays •This arrays have more than one dimensions. Syntax data_type array_name[size1][size2]…….[sizen]; Description Data_type valid data type in C language Array_name name given to the array Size1,size2 are the sizes of the dimensions Example Int a[3][3][3]; Float b[4][4][4]; 12/6/2020 29
  • 30.
  • 31.
    Character and Strings •An char array is a group of characters that store related data • A String is a special char array that does not store related data, but a single piece of data made up of a number of characters OR A string is a sequence of character that is treated as a single data item. Any group of characters defined between double quotation marks is a string constant. • Example: Grades can be stored in a char array with the values A,B,C,D,F; when we want to print a specific grade we use only 1 element of the array • Example: But for grades like “Pass” and “Fail” we must print ALL the elements 12/6/2020 31
  • 32.
    String Conti… • MostComputers languages have a string data type; C does NOT • There are 3 ways to store strings in memory • Fixed Length • Stored Length • Terminated • C adopts the Terminated String approach • A string in C is an array of chars terminated by the String Terminator or NULL character 0 12/6/2020 32
  • 33.
    Common String Operation 1.Reading and Writing Strings 2. Combining strings together 3. Copying one string to another 4. Comparing strings for equality 5. Extracting a portion of a string 12/6/2020 33
  • 34.
    Declaring and Initializingof String The General form of String is char string_name [size]; Example: char city [10]; char name[30]; When the complier assigns a character string to a character array, it automatically supplies a multicharacter (‘0’) at the end of the string. Therefore, the size should be equal to the maximum number of characters in the string plus one. C Permits a character array to be initialized in either of the following two forms: char city [9] = “ NEW YORK”; char city [9] = {‘N’.’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’0’); C also permits us to initialize a character array without specifying the number of elements. In such cases, the size of the array will be determined automatically, base on the number of elements initialiazed. For Example, the statement char string [ ] = {‘G’,’O’,’O’,’D’,’0’}; 12/6/2020 34
  • 35.
    Declaring Conti…. We canalso declare the size much larger than the string size in the initializer. That is, the statement. char str[9] = “GOOD”; 12/6/2020 35 G O O D 0 0 0 0 0 The following declaration is illegal. (I) char str[5]; str = “GOOD”; This will result in a compile time error. Also note that we cannot separate the initialization from declaration. (II) char s1[4] = “abc”; char s2[4]; s2 = s2; /* Error */ is not allowed. An array name cannot be used as the left operand of an assignment operator.
  • 36.
    Creating a Stringin C 12/6/2020 36 h i ! array1820 1821 1822 h i ! /0 string2820 2821 2822 2823
  • 37.
    READING STRINGS FROMTERMINAL The familiar input function scanf can be used with %s format specification to read in a string of characters. Example: char address [10]; scanf(“%s”,address); The problem with the scanf function is that it terminates its input on the first white space it finds. Therefore, if the following line of text is typed in at the terminal, NEW YORK then only the string “NEW” will be read into the array address, since the blank space after the word ‘NEW’ will terminate the string reading. The scanf calls in the case of character arrays, the ampersand (&) is not required before the variable name. The address array is created in the memory as shown below: 12/6/2020 37 N E W O ? ? ? ? ? ? Note that the unused locations are filled with garbage. If we want to read the entire line “NEW YORK”, then we may use two character arrays of approximate sizes. That is, char adr1[5], adr2[5]; scanf(“%s %s”,adr1,adr2); With the line of text NEW YORK
  • 38.
    READING STRINGS FROMTERMINAL 12/6/2020 38 We can also specify the field width using the form %ws in the scanf statement for reading a specified number of characters from the input string. Example: scanf(“%ws”,name); Here two things may happen. 1. The width w is equal to or greater than the number of characters typed in. The entire string will be stored in the string variable. 2. The width w is less than the number of characters in the string. The excess characters will be truncated and left unread. Consider the following statements: char name [10]; scanf(“%5s”,name); The input string RAM and KRISHNA will be stored as: R A M 0 ? ? ? ? ? ? K R I S H 0 ? ? ? ?
  • 39.
    Reading a Lineof Text We have seen just now that scanf with %s or %ws can read only strings without white spaces. That is, they cannot be used for reading a text containing more than one word. However, C Supports a format specification known as the edit set conversion code % [..] that can be used to read a line containing a variety of characters, including white spaces. Recall that we have used this conversion code in the program segment char line [80]; scanf (“%[^n]”,line); printf(“%s”,line); will read a line of input from the keyboard and display the same on the screen. We would very rarely use this method. 12/6/2020 39 Using getchar and gets Functions To read a single character from the terminal, using the function getchar. We can use this function repeatedly to read successive single characters from the input and place them into a character array. Thus, an entire line of text can be read and stored in an array. The reading is terminated when the newline character (‘n’) is entered and the null character is then inserted at the end of the string. The getchar function call takes the form: char ch; ch = getchar ( ); Note that the getchar function has no parameters.
  • 40.
    12/6/2020 40 #include <stdio.h> voidmain() { char line[81], character; int c; c = 0; printf("Enter text. Press <Return> at endn"); do { character = getchar( ); line[c] = character; c++; } while(character != 'n'); c = c - 1; line [c] = '0'; printf("n%sn", line); }
  • 41.
    getchar and getsConti…. Another and more convenient method of reading a string of text containing white spaces is to use the library function gets available in the <stdio.h> header file. This is a simple function with one string parameter and called as under. gets (str); str is string variable declared properly. It reads characters into str from the keyboard until a new line character is encountered and then appends a null character to the string. Unlike scanf, it does not skip white spaces. For example the code segment char line [80]; gets (line); printf(“%s”,, line); reads a line of text from the keyboard and displays it on the screen. The last two statements may be combined as follows: printf(“%s”,gets(line)); C does not provide operators that work on strings directly. For instance we cannot assign one string to another directly. For example, the assignment statements. string = “ABC” string1 = string2; are not valid. 12/6/2020 41
  • 42.
    12/6/2020 42 #include<stdio.h> void main() { charstring1[80],string2[80]; int i; printf("Enter a string n"); printf("?"); scanf("%s",string2); for(i=0;string2[i] != 'o'; i++) string1[i] = string2[i]; string1[i] = 'o'; printf("n"); printf("%sn", string1); printf("Number of characters = %dn",i); }
  • 43.
    12/6/2020 43 WRITING ASTRINGS TO SCREEN We have used extensively the printf function with %s format to print strings to the screen. The format %s can be used to display an array of characters that is terminated by the null character. For example, the statement printf(“%s”, name); can be used to display the entire contents of the array name. We can also specify the precision with which the array is displayed. For instance, the specification %10.4 Indicates that the first four characters are to be printed in a field width of 10 columns. However, if we include the minus sign in the specification (e.g., %-10.4s), the string will be printed left-justified. Using putchar and puts Functions Like getchar, C supports another character handling function putchar to output the values of character variables. It takes the following form: char ch = ‘A’; putchar (ch); The function putchar requires one parameter. This statement is equivalent to: printf(“%c”,ch); We have used putchar function to write characters to the screen. We can use this function repeatedly to output a string of characters stored in an array using a loop:
  • 44.
    12/6/2020 44 Example: char name[6]= “PARIS”; for(i=0;i<5;i++) putchar (name[i]); putchar(‘n’); Another and more convenient way of printing string values is to use the function puts declared in the header file <stdio.h>. This is a one parameter function and invoked as under: puts (str); Where str is a string variable containing a string value. This prints the value of the string variable str and then moves the cursor to the beginning of the next line on the screen. For example, the program segment char line [80]; gets (line); puts (line); Reads a line of text from the keyboard and displays it on the screen. Note that the syntax is very simple compared to using the scanf and printf statements Using putchar and puts Functions Conti…
  • 45.
    Function Action strcat () Concatenates two strings strcmp ( ) Compares two strings strcpy ( ) Copies one strings over another strlen ( ) Finds the length of a string 12/6/2020 45 The C Library supports a large number of string – handling function that can be used to carry out many of the string manipulations. The most commonly used string – handling functions. STRING HANDLING FUNCTIONS