CHAPTER 7

Characters and String Handling

Handling characters and sequences of characters with computers is one of the very important activities. Sequences of characters are generally referred to as strings. In C, strings are written within a pair of double quote marks (“) and are stored in the form of character arrays with a null character () as it 's last element. This null character will be automatically inserted by the C compiler. For example, “World Cup” is a string and is stored as shown in the following figure.

images

We have been using character arrays or strings right from the very first example to display messages along with the printf() functions. However, none of the examples so far have discussed the processing of either a character or a sequence of characters, i.e. strings. For processing of characters and strings it is necessary to know how the characters are stored inside computers. In computers characters are stored using numeric codes. The most popular text codes that have been employed hitherto are EBCIDIC ( pronounced as Eb-si- dic), ASCII ( As-key) and Unicode. Among these ASCII code is by far the most widely used, particularly with personal computers. ASCII stands for American Standard Code for Information Interchange and is the contribution of American National Standards Institute (ANSI). In it's original form ASCII has 128 codes ranging from 0 to 127. Among these codes, 48 to 57 are used to represent decimal digits, codes 65 to 90 are used to represent the upper case English alphabets, codes 97 to 122 are used to represent the lower case English alphabets and the remaining are used to represent various control, special and white space characters. The point the reader has to understand here is that numeric codes are used to represent the characters. Therefore, processing of characters is somewhat similar (not exactly same) to the processing of integer numbers, which has been discussed in the preceding chapters. For example, two character strings can be compared just like integers, names in the form of strings can be sorted using Bubble sort or any other sorting procedures, upper case alphabets can be converted into lower case alphabets by adding a numeric digit (32) to each one of them, and so on.

Typically, character processing also deals with the techniques used for counting number of characters, number of words and/ or number of lines in a given text. However, while dealing examples of these types, one has to carefully identify the source, from where the input stream is coming and how its end is identified. The source could be either a string or a file. In the case of strings, a null character indicates the end of the input stream, whereas in the case of a file, an end-of- file (EOF) character indicates the end of the input stream. Here, it may be carefully noted that the C compiler, by default, considers the keyboard as a file. The stream of characters input via a keyboard is therefore considered to be coming from a file. It is important to note that in the case of input via a keyboard, the Ctrl-z character is taken as the EOF character. Of course, when the input comes from a string the null character () indicates the end. This chapter discusses some examples like the ones cited in this as well as the previous paragraph.

7.1 FINDING THE LENGTH OF A GIVEN STRING

The Method

In C, a string is stored as an array with a null character () as its last element. For example, the string “The University” is stored in an array as shown in the following figure.

images

The length of the string is equal to the actual 'number of characters' in the string (i.e. the character ‘’ is not considered as a part of the string). Thus the length of the string shown in the figure above is 14. Obviously, in order to find the length of the string one has to count the number of characters from the beginning till ‘’. As in the case of an array each element of a character array, i.e. string, is also accessed using a subscript. The flowchart on page 138 gives the procedure for determining the length of the string.

C-Tips

The contents of a string are considered as characters. Therefore a string is declared both as of char data type and as an array by mentioning the size of the array. As strings are of variable lengths, the size of the string need not be mentioned explicitly.

The function gets () is used to input a string terminated by a ‘ ’, the newline character, via the keyboard. The input string will be stored in the variable name that appears as the argument of the gets () function in the form of an array with a '' as its last character. Here it may be noted that blanks input as part of the input string, till a new line character ( ) are also taken as valid characters.

As finding the length of a string is one of the quite frequently used activity, it is available as a predefined or library function in C. The function strlen( ) is this predefined function. It is available in a header file called <string.h> which has to be included in the beginning of a program in order to use it.

Flowchart

images

The Program

/* Program to find the length of a given string */

#include<stdio.h>
main()
{
  char str[’ ’]; /* In strings, the size need not be mentioned */
  int length,i;
  clrscr();

  printf(“Enter a string :
”);
  gets(str);

  length=0;

  /* Characters are counted, one by one, by moving along the string
    with the help of the subscript i, till the null character ‘’ */

  for(i = 0; str [i] != ‘’;++i)
  length++;

  printf (“The length of the given string is : %d
” , length) ;
}

7.2 DETERMINING WHETHER A GIVEN STRING IS PALINDROME OR NOT

By definition a palindrome is a string that reads alike backward and forward. For example, the string “malayalam” is a palindrome.

The Method

The given sentence is first read in as a string, say str. As already mentioned it gets stored as a character array with a null character () at the end, as shown in the following figure.

images

In order to identify whether the given string is a palindrome or not, the first character at str[0] is compared with the last character at str[8]. If they are same, then the character at str[1] is compared with the character at str[7]. Again, if they are same, the character at str[2] is compared with the character at str[6], and so on.

Obviously, it is recommended to use two subscripts, like i and j, to move along the character array.

  • Subscript i is used to move up the string starting from 0 (zero).
  • Subscript j is used to move down the string from the last character's position value.

    For example, here, the initial value of j is 8.

Flowchart

images

The Program

/* Program to test whether a given string is Palindrome or not */

#include<stdio.h>
main()
{
   int i, j;
   char str [‘ ‘] ;
   clrscr();

   printf(“Input a string :
”);
   gets(str);

   printf(“

The input string is :
”);
   puts(str);

   for(j=0; str [ j] !=‘’ ; j++);

   j=j-i;

   i=0;

   while(i<=j)
   {
      if(str[i]==str[j])
      {
     i = i+1;       /* Moving up the string */

     j = j -1 ;     /* Moving down the string */

      }
      else
      {
      printf(“The given string : %s IS NOT A Palindrome”,str) ;
      exit(1);
      }
   }
   printf (“The given string : %s IS A Palindrome” , str) ;
}

7.3 REVERSING A GIVEN STRING

The Method

The procedure of obtaining the reverse of a given string is explained through a simple illustration as follows.

Illustration Consider a string str of length equal to 4. The reverse of the string str is stored in a string called rev_str.

images

In order to reverse the given string the control has to move on both the strings str and rev_str. The subscript i is used to move on the given string str and the subscript j is used to move on the reversed string rev_str.

In this example, the reversing process starts with the initial value of i as 3, i.e. the position value of the last character of the string str. Here, it may be noted that the last character is the one that appears just before the string termination character ‘’. The subscript i is set to the necessary initial value (i.e. 3) by incrementing (i.e. by moving) its value from 0, as shown in the following flowchart segment.

images

The next step is to copy the elements of the given string str onto the reverse string rev_str in the reversed order. This is done using the relation rev_str[j]=str[i] with the decreasing values of i and increasing values of j. With the decreasing values of the subscript i, the control is moving down on the string str and with the increasing values of the subscript j, the control is moving up the rev_str. The above copying process is terminated when the beginning of the str is reached, i.e. when the subscript i becomes less than 0 (zero). In otherwords, the copying process is done while i ≥ 0. The string reversing process discussed above is shown in the form of a flowchart in the adjoining figure.

Flowchart

images

C-Tips

A for statement, without body, may be used just to move along a string or array, as is used in this example.

The Program

/* Reversing a given string */

#include<stdio.h>
main()
{
  int i,j;
  char str [‘ ’],rev_str[‘ ’];
  clrscr();


  printf(“Input a string :
”) ;
  gets(str);

  printf(“

The input string is :
”);
  puts(str);

  for(i=0; str[i]!=‘’ ; i+ + ) ;   /* Moving upto the termination
                                        character */

  i = i-1;                           /* Going back to the last character */

  j=0;

  while(i>=0)
  {
   rev_str[j]=str[i];

   i=i-1 ;                          /* Moving down str */
   j = j +1 ;                       /* Moving up rev_str */

  } 

  rev_str[j]=‘’;

  printf(“The reverse of the given string is %s”,rev_str);

 }

7.4 COPYING THE CONTENTS OF A GIVEN STRING INTO ANOTHER STRING

The Method

Let strl be the given string. The problem here is to copy its contents into another string, say str2. Copying the contents of a variable into another variable is straightforward and is done using an assignment statement. However, for copying the contents of a string (i.e. a character array) into another string, every element of the first string has to be copied into the corresponding location on the second string, one by one.

As copying process of every element is similar and has to be done repeatedly from the beginning (i.e. from index = 0) till the end (i.e. the null character '' is reached), we can use a loop control structure like ‘for’ and get the necessary work done. The mechanism of copying each element is illustrated in the figure below.

images

The flowchart segment given below shows the copying process, element by element.

images

C-Tips

As is known, ordinarily copying is done by just assigning the value of a variable to another variable using an assignment statement like var1=var2 ;. However, this is not possible in the case of strings. In this case copying is done element by element. As string copying is one of the frequently used activity in C there is a predefined string copying function called strcpy( ) function which takes two string arguments and copies the contents of the second argument on to the first argument. This function automatically puts a null character at the end of the copied string.

As already discussed, predefined string functions are available on a header file called <string.h> which has to be included in the beginning of the program. Though it is possible to input a string using getchar() function, it is recommended to use the gets() function to input the string, as is done in this example.

When examples like the one discussed here are dealt, care should be taken to see that the null character ‘’ is the last element on the second string (str2) also. Below is given the complete flowchart.

Flowchart

images

The Program

/* Program to copy a string into another string */

#include<stdio.h>
#include<conio.h>
main()
{
   char strl [‘ ‘],str2 [‘ ‘] ;
   int i;
   clrscr();

   printf(“Enter a string
”);
   gets(strl);                   /* Reading in the given string */

   printf (“The given string is : %s
”,str1);

   /* following statements copy contents of strl on to str2, one by one */

   for(i=0;str1[i]!=‘’;i++)
     str2[i]=str1[i];

   /* appending the null character to the end of str2 */

   str2[i]=‘’;

   printf (“
 %s is now copied onto str2
” , str1);
   printf(“The contents of str2 is : %s”,str2);
}

7.5 CONCATENATING TWO GIVEN STRINGS

Concatenating two strings means attaching the second string to the end of the first string.

The Method

Let str1 and str2 be the two strings to be concatenated. Also let str1 has “Abdul” and str2 has “Kalam” stored in them respectively as shown in the figure below. It may be observed that both “Abdul” and “Kalam” have a '' as their last characters.

images

As concatenation ‘appends’ or ‘attaches’ the second string (str2) to the first string (str1), the final string (str1, itself) will be as shown in the following figure.

images

A careful observation of the above figure reveals the following two facts :

  1. The ‘’ character at the end of the first string which appears in between “Abdul” and “Kalam” after concatenation has to be replaced by a blank.
  2. Since “Kalam” (i.e. str2) has to be attached to “Abdul” (i.e. str1), there should be sufficient space allotted along with the declaration of “Abdul”, i.e. str1.

The first figure given above is redrawn as shown in the figure on page 149 with sufficient space on the first string “Abdul” to accommodate the second string “Kalam”.

images

The concatenation process needs the control to move along both the character arrays, i.e. strings. Let the subscript i is used to move along str1 and the subscript j is used to move along str2.

Since ‘’ at the end of str1 (i.e. “Abdul”) has to be replaced by a blank, let us start moving on str1 with the help of i. We have to keep moving on str1 as long as str1[i]‘’, As soon as str1[i] is equal to ‘’, a blank character is placed at that position on str1, i.e. at current value of str1[i]. Now str2 is copied on to str1 starting from the next position on str1, i.e. the position which is next to the one where a blank was inserted, character by character.

images

C-Tips

In C there is a predefined function called strcat() which is used to concatenate two given strings i.e. to copy the contents of second string on to the end of the first string. As already mentioned, in order to use this function the header file <string.h> has to be included in the beginning of the program.

Flowchart

images

The Program

/* Concatenating two given strings */

#include<stdio.h>
main()
{
   int i, j;
   char str1 [‘ ‘] , str2 [‘ ‘] ;

   clrscr();

   printf(“Input the first string :
”);
   gets(str1);                     /* input str1 */
   printf(“First string is :% s
”, str1);
   printf(“Input the second string :
”);
   gets(str2);                     /* input str2 */
   printf (“Second string is :% s/n”, str2);
   for (i = 0 ; str1 [i] ! = ‘  ‘ ; i++);  /* Moving to the end of str1 */

   str1[i]=‘ ’        /* replacing ‘’ at the and of str1 by a blank */

   i=i+1;               /* moving to the next position on str1 */

   for(j = 0 ; str2 [ j] ! = ‘’ ; j++)
   {
      str1 [i] =str2 [j] ;        /* Copying str2 to the end of str1 */ i=i+1;
   }
   str1[i]=‘’;        /* Placing a ‘’ at the end of the concatenated
                      string str1 */
                
  printf(“The concatenated string is:%s”,str1);

}

7.6 CONVERTING THE UPPERCASE ALPHABETS INTO LOWERCASE ALPHABETS IN A GIVEN STRING AND VICE - VERSA

As discussed in the introduction of this chapter, in a computer all the characters, including alphabets, are stored in some form of integer codes. The one that is widely used is the ASCII code. In this code the uppercase alphabets A to Z are represented using the codes ranging from 65 to 90 and the lower case alphabets a to z are represented using codes ranging from 97 to 122. A careful observation of these codes reveals the fact that uppercase alphabets are converted into their lowercase equivalents by adding 32. Obviously, lowercase alphabets are converted into their uppercase equivalents by subtracting 32.

The Method

The given string is first read in. Then every character on this string is accessed, starting from the beginning till the end, i.e. till the null character () that appears at the end. This accessed character is tested to find out whether it is an uppercase alphabet or a lowercase alphabet.

A statement of the form “is the character greater than or equal to ‘A’ and less than or equal to ‘Z’ ?” is used to test for an uppercase alphabet. Similarly a statement of the form “is the character greater than or equal to 'a' or less than or equal to ‘z’ ?” is used to test for a lowercase alphabet.

Once the character under consideration does not belong to any one of the above two groups of characters, it will not be an alphabet. Under such circumstances nothing is done with the current character and the next character on the string is accessed and tested. If, at any point of time, the current character belongs to the upper case alphabets range, then it is converted in to its lower case equivalent by adding a 32 to it. However, if the current character belongs to the lowercase alphabets range, then it is converted to its uppercase equivalent by subtracting a 32 from it.

The above process of accessing characters of the string one after the other, ‘testing for its range and either adding or subtracting a 32 to/from the current character’ is repeated till the null character () is reached. This process is shown pictorially in the form of a flowchart as follows.

Flowchart

images

The Program

/* Converting the uppercase alphabets into lowercase alphabets in a
given string and vice - versa. */

#include<conio.h=        /* Including header file */
#include<stdio.h=

main()
{
   char str [’ ’] ; int i;
   clrscr();

   printf(“

Enter a string
”);
   gets (str) ;                  /* Reading a string */

   printf (“
Given string is : %s
”, str) ; /* Printing a string */

   for ( i=0 ; str [i] ! =‘ ’ ; ++i)     /* Repeat till the end of string */

   {
     /* Converting upper to lower */

     if ( str[i]>=‘A’ && str [i]< = ‘Z’)
            str [i] = str [i] + 32 ;
    
     /* Converting lower to upper */

     else if ( str [i]>=‘a’ && str [i]< = ‘z’)
           str [i] = str [i] − 32 ;
    }

    printf (“
Case converted string is : %s
” , str) ;
}

7.7 COUNTING THE NUMBER OF VOWELS AND CONSONANTS IN A GIVEN LINE

The Method

First the given line is input with an appropriate input function. It is recommended to use the gets( ) function and to store the given line in the form of a string. We know that the string will be stored in the form of a character array with the null character () as its termination character. In order to count the required type of character, every character of the line, i.e. string, is accessed starting from the beginning till the end of the string is reached. In this example, every accessed character is verified to find out whether it is an alphabet (lowercase or uppercase) or not. Whenever it is an alphabet it is tested to find out whether it is an vowel ( a, e, i, o, u, or A, E, I, O, U ) or not. If it is a vowel, the vowel count (vow_cnt) is incremented. Otherwise, the alphabet has to be a consonant and hence the consonant count (con_cnt) is incremented. Obviously, whenever the character under current consideration is not an alphabet, the next character on the string is accessed without counting. The entire process is repeated till the end of the string is reached, i.e. the null character ‘' is reached.

C-Tips

A function like gets() is used to input the line of text as blanks will be present between consecutive words. A statement like “ is the current character (str[i]) is within the range of a to z or A to Z ?” is used to find out whether the current character is an alphabet or not“ A relational expression like: str(i) ≥ ‘a ‘ and str(i) ≤ ‘z’ is used to find out whether a character at the position indicated by the subscript i on the string str is a lowercase alphabet or not.

Flowchart

images

It may be observed that in this example a switch statement is used repeatedly under the control of a for loop control structure.

The Program

/* Counting the number of vowels and consonants in a given line */

#include<stdio.h>
#include<conio.h>

main()
{
   char str [‘ ‘];
   int i,vow_cnt = 0, con_cnt = 0;   /* Initializing vowel and consonant
                                       counters to zero */

   clrscr();
   printf (“
Enter the line: 
”) ;
   gets(str);               /*Reading a string*/

   printf (“Given line is: 
%s
” , str) ; /* Printing a string */

   for(i=0; str[i]!=‘’; + + i) /* Repeat till the end of the string */
   {
                      /* Checking only letters */
     if((str[i]>=‘a’ && str[i]< = ‘z’) || (str[i]>=‘A’ && str[i] < = ‘Z’))
     {

    switch ( str [i] )
    {

       case ‘a’:
       case ‘e’:
       case ‘i’:
       case ‘o’:
       case ‘u’:
       case ‘A’:
       case ‘E’:
       case ‘I’:
       case ‘O’:
   case ‘U’:   vow_cnt + +;  /* If character is vowel increment
                                   vowel counter */
                      break;
       default: con_cnt++; /* Otherwise increment consonant
                 counter */
     }

    }

  }
  printf(“Number of vowels = %d
”, vow_cnt);
  printf(“Number of consonants = %d
”, con_cnt);
}

7.8 SORTING A GIVEN SET OF NAMES

The Method

Names may be made up of just a single word (like Vasanth) or more than one word (like George Bush). In this example, names made up of more than one word have been considered. The technique employed here is to input all the names and store them in an array of some suitable name (say, name). It may be remembered that all strings (i.e. names) are stored with ASCII codes, which are nothing but integers. For sorting names they are mutually compared, to find out which one is smaller or bigger. Actually this comparison takes place on ASCII values of the names. While sorting names in alphabetical order we have to see that names with lower ASCII values appear first. Any commonly available sorting method may be used. Here, the Bubble sort method (discussed in Section 6.8) has been used.

C-Tips

Since we have assumed names of more than one word the gets() function is used for reading in the names. If names of only single word are involved we may use the scanf() function. For comparing strings, i.e. names, the string-compare function strcmp () is used. In this program, it is necessary to exchange the positions of two names. In the case of sorting numeric values, exchanging the values of two variables was managed using assignment statements. The use of assignment statements to exchange values of strings is not possible. Here, string-copy function strcpy() has to be used to exchange two names.

String handling functions like strcmp(), strcpy() are available in the header file <string.h>. Therefore, this file has to be included in the beginning. For printing out names the function puts() is used.

The string compare function strcmp() takes two strings as its arguments and returns a numeric value as a result of the comparison. If the two strings are equal, a zero (0) is returned. If the first string is alphabetically above the second string then a negative value is returned. If the first string is alphabetically below the second string, a +ve value is returned.

Flowchart

images

The Program

/* Program to read n names and to sort them in an alphabetical order
*/

#include<stdio.h>
#include<conio.h>
#include<string.h>

main()
{
   char name [‘ ‘] [‘ ‘] , temp [‘ ‘] ;
   int i, j , n;
   clrscr();

   printf (“How many names 
“ ) ;
   scanf(“%d”, &n) ;

   printf(“Enter %d names
”, n) ;
   getchar() ;      /* To absorb the new line character */

   for(i = 0; i<n; ++i)
       gets(name[i]);

   printf(“Given names are :
”) ;
   for(i = 0; i<n; ++i)
      puts(name[i]);

   for(j = 0 ; j<n−1; ++j) /* Performing n−1 passes */

     for(i=0; i<n−1; ++i) /* Performing n-1 comparisons in each pass */

    if(strcmp(name[i], name[i+1]) > 0) /* Comparing adjacent names */
    {
          /* Exchanging names */
          strcpy(temp ,name[i]);
         strcpy(name[i], name[i+1]) ;
          strcpy(name[i+1], temp);
    }
   printf (“
Given Names in sorted order : 
”) ;
   printf (“________________
”);
   for(i = 0; i<n; ++i)
       printf(“%s
” , name[i]);
}

7.9 COUNTING THE NUMBER OF CHARACTERS IN AN INPUT

The Method

Characters are input via the standard input, i.e. the keyboard, one by one. As the characters are input they are counted. The counting is stopped whenever the input character is a end of file [EOF] character. Conventionally -1 is taken as the EOF character. However, this is implementation dependent.

C-Tips

Whenever text form of inputs are given via keyboard, ctrl-Z is used as the end of file character. As there could be large number of characters, it is recommended to use a long type variable to store the characters count. The format specifier %ld is used to handle long data type variable used to count the total number of characters.

Flowchart

images

The Program

/* To count the number of characters in an input */

#include<stdio.h>
#include<conio.h>

main()
{
   long char_count = 0 ;    /* Notice the use of long data type */
   clrscr();

   printf(“Enter text: Press Ctrl-Z to terminate 
”);

   /* Keying-in a character and testing for EOF */

   while(getchar()!= EOF)
   {
     char_count = char_count +1; /* Counting */
   }
   printf(“
Number of characters = %ld”, char_count);
}

Note: In this example, the characters are counted as and when they are input through the keyboard. The input character stream is not stored anywhere. If required, it may be stored in a string or a separate file. Also it may be noted that the EOF character is not counted.

7.10 COUNTING THE NUMBER OF WORDS IN A GIVEN LINE

A line will be made up of many number of words and ends with a newline character ( ). Two successive words will be separated by one or more blank characters. Normally only one blank character appears between two consecutive words. Therefore the following discussion assumes only one blank between two consecutive words.

When a line is the very first line of a given text, the general practice is to indent it by using one or more number of white space characters. These are called leading white spaces. The procedure discussed here takes care-of these leading white spaces. In other words, it neglects the leading white spaces, if any, and starts actual word counting only after a non- white space character is input.

The Method

Words can be counted by counting them as and when the characters of the input are keyed in from the standard input i.e. the keyboard. Also we can input an entire line into a string and count the words by going through that string, character by character, till the null character () is reached. The following flowchart is based on the former type of input, i.e. the input keyed in from a keyboard. If any white space characters are input in the beginning, the idea is to recognize it and loop back to accept the next input character, neglecting the present one. The control flows forward, i.e. the counting starts, only after the input character is a non-white space character. Here afterwards, the word count is incremented as and when the input character is a blank character. The counting process stops after a newline character ( ) is input. It may be noted that the line terminating character ( ) not only signals the end of a line but also signals the end of last word. Therefore, care should be taken to count the last word also. The method discussed is shown diagrammatically in the following flowchart.

C-Tips

White space characters mean the blank (‘ ‘), the tab (‘ ’) and the newline character (‘ ’). As one can easily guess these white space characters are generally used to improve the readability of any text. Thus, we have been using these characters in the control strings of statements like printf ( ) statements all along.

Flowchart

images

Sequences of characters like ‘ ’ and ‘ ’ which have special meanings attached to them are called escape sequences. In C there are many more such escape sequences. For example, ‘’ is used for backspacing, ‘a’ is used for ringing a bell, and so on. The input characters are read-in using the getchar () function and stored in some convenient variable like inchar.

The Program

/* Counting the number of words in a line */

#include<stdio.h>
#include<conio.h>
main()
{
   char inchar;
   int word_cnt=0;
   clrscr();

   printf (“Enter a line of text : 
”) ;

   /* Following while takes care of leading white spaces */

   while((inchar=getchar())==‘ ’ || inchar==‘	’ || inchar==‘
’);

   while (inchar != ‘
’ )    /* Actual word counting begins here */
   {
     if(inchar == ‘ ‘)
     word_cnt++;

     inchar=getchar();          /* Accepts the remaining characters
*/
    }

    word_cnt++;
    printf (“
The number of words in the given line is: %d” , word_cnt ) ;
}

7.11 COUNTING THE NUMBER OF LINES IN A GIVEN TEXT

It is known that a text consists of many numbers of lines and every line is terminated by a newline character (‘ ’). This fact is used to count the number of lines.

The Method

The given text is keyed in via the standard input i.e. the keyboard. If white space characters are input as leading characters of the text they are just overlooked. As in the previous example, the actual counting begins from the appearance of the first non-white space character. A variable like line_cnt is used to count the number of lines and to store the count. As already mentioned the arrival of a newline character (‘ ’) signals the end of a line. The text input operation is terminated by using the ctrl-z, the end-of-file character.

After typing in the last line of the text, the normal practice is to close the file i.e. the input operation. In other words, a new line character is not used after keying in the last line. By keeping in mind this normal practice the line_cnt must be incremented after signaling the last line input i.e. the entry of the entire given text. Keying in the text is terminated by using the ctrl-z (EOF) keys.

Flowchart

images

The Program

/* Counting the number of lines in a given text */

#include<stdio.h>
#include<conio.h>
main()
{
   char inchar;
   int line_cnt=0;
   clrscr();
   printf (“Enter a passage of text : 
” ) ;

   /* To take care of leading white spaces */

   while((inchar=getchar())==‘ ’ || inchar==‘	’ || inchar==‘
’);

   while (inchar != EOF)     /* Actual line counting begins here */
   {
   if ( inchar == ‘
’)
   line_cnt++;

   inchar=getchar ( ) ;     /* Accepts the remaining characters */
   }
   line_cnt++;
   printf (“
The number of lines in the given passage is: %d” , line_cnt);
}

EXERCISES

  1. Develop a flowchart to read in a line and count the number of words beginning with a specific letter, say ‘E’ or ‘e’. Code the same using C.
  2. Develop a flowchart to find whether a required substring exists in a given line of text or not. Code the same using C.
  3. Develop a flowchart to count the number of characters belonging to the alphabets group, digits group and special characters group. Report the total number of characters also. Code the same using C.
  4. Develop a flowchart to count the number of words in a given line of text assuming that there could be more than one blank or a tab in between the consecutive words. Code the same using C.
  5. Develop a flowchart to count the number of characters, number of words as well as number of lines in a given text. The procedure should handle leading white space characters, if any, properly. Code the same using C.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.21.152