You get a bonus - 1 coin for daily activity. Now you have 1 coin

7. EXAMPLES in the C language (+ literature)

Lecture



Consider examples of programs that use different constructions of the C language. The first one demonstrates the use of n control characters in the printf () and scanf () functions.

  / * Example 1 * /  
  #include <stdio.h> 

  void main (void) 
  { 
      int x, n1, n2; 

      printf ("Enter an integer from -32768 to 32767 \ n"); 
      scanf ("% d% n", & x, & n1);  
      printf ("x =% d% n \ n", x, & n2);  
      printf ("n1 =% d, n2 =% d \ n", n1, n2); 
  }  
 

The results of this program are:

  Enter an integer from -32768 to 32767 
  234 <Enter> 
  x = 234 
  n1 = 3, n2 = 7  
 

The value n1 determines the number of digits entered, and n2 - the number of characters displayed in the string x = 234 (with spaces).

The following example shows the use of the% [] specifications, as well as the * and # characters.

  / * Example 2 * / 
  #include <stdio.h>  

  void main (void)  
  { 
      char str_b [21], str_c [21];  / * Last item is reserved under \ 0 * / 
      int x, n1, n2; 
      float y; 

      printf ("Enter a string of up to 20 characters \ n"); 
      scanf ("% [Computer]% s", str_b, str_c); 
      printf ("str_b =% s, str_c =% s \ n", str_b, str_c); 
      y = 12.345678; 
      n1 = 8; 
      n2 = 3; 
      x = 0x100; 
      printf ("y =% *. * f \ n", n1, n2, y); 
      printf ("x (16) =% # x, x (16) =% x, x (10) =% i \ n", x, x, x); 
  } 
 

The results of the program are as follows:

  Enter a string of up to 20 characters.  
  Comp-1-2-3-4-5 <Enter> 
  str_b = Comp, str_c = -1-2-3-4-5 
  y = 12.346  
  x (16) = 0x100, x (16) = 100, x (10) = 256 
 

Here the user entered the string Comp-1-2-3-4-5. From it, only four characters (Comp) coincide with the first characters given in square brackets of the considered specification [Computer]. Therefore, only these four characters will fall into the first line, and the remaining characters (1-2-3-4-5) will fall into the second line. The number n1 determines the minimum width of the field for output, and the number n2 = 3 - the number of digits after the comma. As a result, the number 12.345678 will be shifted relative to the left border, and after the comma three numbers will be displayed. The hexadecimal number 0x100 is inferred by the printf () function with the prefix 0x, without the prefix 0x and in decimal form.

The third program demonstrates the use of the if ... else conditional statement and the for statement for looping.

  / * Example 3 * /  
  #include <conio.h> 
  #define SYM 'X' / * Output Character * / 
  #define SPACE '' / * Space Definition * / 
  #define LF 10 / * Line feed * /  
  #define CR 13 / * carriage return * / 
  #define LEFT 24 / * Left Character Limit * /  
  #define RIGHT 51 / * Right border of the symbol * / 
  #define BOTTOM 25 / * Lower limit of the symbol * /  

  void main (void)  
  { 
      int col, line;  / * col - column number for character output * / 
                         / * line - the number of lines to display the character * / 
      clrscr ();            
      for (line = 1; line <= BOTTOM; line ++) / * Output spaces to the left  
                                                  borders of the symbol * /  
      { 
          for (col = 1; col <LEFT; col ++) putch (SPACE);  
          for (col = LEFT + 1; col <RIGHT; col ++) / * Output the X character  
                                                       in full screen */  
          if ((col == (LEFT + line)) || (col == (RIGHT - line)))  
          putch (SYM); 
          else putch (SPACE); 
          putch (LF);  / * Carriage return and line feed after * /  
          putch (CR);  / * output each line of the character * / 
      } 
      getch ();  / * Waiting for keystroke * / 
  } 
 

After its launch, the X symbol will appear in full screen.

The new library function clrscr () has the following prototype:

  void clrscr (void);  
 

It clears the screen and is declared in the conio.h header file.

The fourth program demonstrates the use of the recursive function to calculate factorial. (Note that the definition of the factorial () function may also appear after the main () function, but in this case the factorial () function must be declared before the main () function, ie, before the main () it is necessary to put the line: long factorial ( int) ;.)

  / * Example 4 * /  
  #include <stdio.h>  
  #include <values.h>  
  #include <process.h>  

  long factorial (int value) / * recursive function * / 
  {  
      long result = 1; 

      if (value! = 0)  
      {  
          result = factorial (value - 1);  
        / * Testing the possibility of calculating factorial * /  
          if (result> MAXLONG / (value + 1))  
          { 
              fprintf (stderr, "Very large number \ n"); 
              getch ();  / * Waiting for keystroke * / 
              exit (1); 
          } 
          result * = value; 
      } 
      return (result); 
  }  
  / * Recursive calculation of the factorial of the number value * /  
  void main (void)  
  { 
      int value;  / * The factorial of this value is calculated * /  
      long result;  / * Variable for the result * / 

      puts ("Which factorial?"); 
      scanf ("% d", & value); 
      result = factorial (value); 
      printf ("Result:% ld \ n", result);  
      getch ();  / * Waiting for keystroke * / 
  } 
 

The results of this program:

  What is the factorial number?  10 <Enter> 
  Result: 362880  
 

The fifth program counts the number of characters and words in the input lines (new characters and words are added to the previous ones; spaces are included in the number of characters entered).

  / * Example 5 * / 
  #include <stdio.h>  
  #include <conio.h>  
  #define ESC 27 / * 27 - ASCII code of the ESC key * /   

  void CountOfLines (void)  
  { 
  / * Static variables will keep old values ​​at each  
  New call to CountOfLines * /  
      static int words = 0, symbols = 0;  / * words is the number of words  
                                            symbols number of characters * / 
      char temp, t = 0;  / * Temporary variables * / 

      ++ symbols;  
  / * The number of characters and words is given after pressing <Enter> * / 
      while ((temp = getche ())! = '\ r') 
      { 
          ++ symbols;  / * Count each character * / 
  / * After one or more spaces, the word is counted * / 
          if ((temp == '') && (t == 1)) continue; 
          if (temp == '') {t = 1;  ++ words;  }  
          else t = 0;  
      } 
      if (t == 1) --words;   
      else ++ words; 
      printf ("\ n Words:% d; characters:% d \ n", words, symbols);  
  } 
  void main (void)  
  { 
      puts ("To end the program, press <ESC> at the beginning of the line"); 
      puts ("A string must not begin with a space and press the key"  
           "<Enter>");  
      puts ("The string must not end with a space");  
      while (getche ()! = ESC) CountOfLines ();  
      putch ('\ b'); 
      putch ('');  
      putch ('\ b'); 
  } 
 

The results of this program:

  To end the program, press <ESC> at the beginning of the line. 
  The string must not begin with a space and with the key <Enter> 
  The string must not end with a space. 
  Mouse Keyboard <Enter> 
  Words: 2 characters: 14 
  <ESC> 
 

The next group of programs demonstrates working with files. It allows you to organize a telephone directory in a file on disk and performs the following functions:

  • entering the name of the subscriber and telephone number in the directory;
  • search in the directory phone number by the name of the subscriber;
  • removal of the subscriber's last name and his phone number from the directory

The following is the text of the main.c head program:

  // Example 6   
  // ------------------------------------------------ --------- 
  // The head program for working with the telephone directory 
  // ------------------------------------------------ --------- 
  #include "A: \ my.h" // Header file with global  
                              // variables and constants 
  #include "A: \ findt.c" // Search for the string str in the file 
  #include "A: \ choicet.c" // Check for the presence of a string in the file 
  #include "A: \ addt.c" // Add a string to the file 
  #include "A: \ subt.c" // Delete line from file 

  void main (int argc, char * argv []) 
  { 
      if (argc == 3) 
         if (* argv [1] == '+') // Add entry 
         { 
             if (Choice (argv [2]) == 0) // Is there such  
                                          // file entries? 
             { 
                 puts ("This surname is in the directory"); 
                 exit (1); 
             } 
             Add (argv [2]);  // Adding an entry 
         } 
         else if (* argv [1] == '-') Sub (argv [2]);  // Delete Record 
              else puts ("The erroneous value of the argument"); 
      else if (argc == 2) Find (argv [1]);  // Record search 
           else puts ("Erroneous number of arguments"); 
  } 
 

Using the #include directives, the following files are included in the head program: my.h, findt.c, choicet.c, addt.c and subt.c. It is believed that they are all located in the root directory of the A: drive. If this is not the case, then the appropriate #include directives must be changed. Global variables and some character values ​​are defined in the my.h file.

  // Header file my.h 
  // ------------------------------------------------ -------- 
  // Definitions of global variables and character values 
  // ------------------------------------------------ -------- 
  #include <stdio.h> 
  #include <process.h> 
  #include <string.h> 
  #define MAX_NAME 20 // Maximum number of characters in last name 
  #define MAX_NUMBER 10 // Maximum number of digits per phone.  the room 
  char Name [MAX_NAME];  // Array of names 
  char Number [MAX_NUMBER];  // Array for the phone number 
  char File [] = "A: \\ tel \\ tel_num.txt";  // Directory file name  
  int Count;  // The number of names in the directory 
  FILE * F_tel;  // Logical name of the directory file 
 

The file my.h, in particular, specifies that the telephone directory will be organized in the tel directory of the A: drive. Therefore, it is necessary to create this subdirectory before using the main.exe program or use another subdirectory. In the latter case, you need to change the line:

  char File [] = "A: \\ tel \\ tel_num.txt";  
 

which sets the name of the file with the telephone directory (tel_num.txt).

The findt.c module, the text of which is shown below, contains the Find () function to search for the string str in the tel_num.txt file.

  // module findt.c 
  // ------------------------------------------------ ---------- 
  // Function Find () to search for the string str in the file tel_num.txt 
  // ------------------------------------------------ ---------- 
  void Find (char * str) 
  { 
      int i; 
  // If the file cannot be opened for reading, then the program 
  // exit 
      if ((F_tel = fopen (File, "r")) == NULL) 
      { 
          fprintf (stderr, "\"% s \ ": unable to open \ n", File);  
          exit (1); 
      } 
  // Read the number of records (Count) in the file 
      if (fread (& Count, sizeof (int), 1, F_tel)! = 1) 
      { 
          fprintf (stderr, "\"% s \ ": read error \ n", File);  
          exit (1); 
      } 
  // The for loop searches for the desired entry.  
      for (i = 1; i <count; i ++) 
      {  
          fread (Name, 1, MAX_NAME, F_tel);  // read the name 
          fread (Number, 1, MAX_NUMBER, F_tel);  // Read the number 
          if (ferror (F_tel)) // Check for no error 
          { 
              fprintf (stderr, "\"% s \ ": read error \ n '', File); 
              exit (1); 
          } 
          if (strcmp (str, Name) == 0) // If the name matches  
                                        // with the entered, the last name  
                                        // and found number       
                                        // displayed on screen 
          { 
              printf ("Last Name:% s \ n", Name); 
              printf ("Phone Number:% s \ n", Number);  
              fclose (F_tel);  
              return;  
          } 
      } 
  // If the search result is negative, it displays  
  // next message  
      fprintf (stderr, "\"% s \ ": no entry in file \ n", File); 
      fclose (F_tel); 
      return; 
  } 
 

The module choicet.c contains the function Choice (), which allows you to check if there is a given string in the tel_num.txt file.

  
  // Module choicet.c 
  // ------------------------------------------------ ---------------------- 
  // Function Choice (), checking if there is a string str in the file tel_num.txt 
  // ------------------------------------------------ ---------------------- 
  int Choice (char * str)  
  { 
      int i; 
      char temp [MAX_NAME + MAX_NUMBER]; 

      if ((F_tel = fopen (File, "r")) == NULL)  
      return 1;  // str strings are not in the file 
      if (fread (& Count, sizeof (int), 1, F_tel)! = 1) 
      { 
          fprintf (stderr, "\"% s \ ": read error \ n", File); 
          exit (1); 
      } 
      for (i = 0; i <count; i ++) 
      { 
          fread (temp, 1, MAX_NAME + MAX_NUMBER, F_tel); 
          if (ferror (F_tel)) 
          { 
              fprintf (stderr, "\"% s \ ": read error \ n", File); 
              exit (1); 
          } 
          if (strcmp (str, temp) == 0) 
          { 
              fclose (F_tel); 
              return 0;  // The string str is in the file 
          } 
      } 
      fclose (F_tel); 
      return 1;  // str strings are not in the file 
  } 
 

The addt.c module contains the Add () function, which adds the specified string to the tel_num.txt file.

  // addt.c module  
  // ------------------------------------------------ ------- 
  // The Add () function adds the string str to the file tel_num.txt  
  // ------------------------------------------------ ------- 
  void Create (void) // Creates a file if it does not exist 
  { 
      if ((F_tel = fopen (File, "wb +")) == NULL) 
      { 
          fprintf (stderr, "\% s \": unable to open \ n ", File); 
          exit (1); 
      } 
      Count = 0; 
      if (! fwrite (& Count, sizeof (Count), 1, F_tel)) 
      { 
          fprintf (stderr, "\"% s \ ": write error \ n", File); 
          exit (1); 
      } 
  } 
  void Add (char * s) // Adds an entry to the file 
  { 
      char str [MAX_NAME], sn [MAX_NUMBER];  // Temporary arrays 
      int i; 

      for (i = 0; i <MAX_NAME; i ++)     
      str [i] = '';  // Spaces in str 
      strcpy (str, s);  // copy string to str 
      if ((F_tel = fopen (File, "rb +")) = = NULL)  
      Create ();  // Create file if it is not  
                                       //exists 
      else if (fread (& Count, sizeof (Count), 1, F_tel)! = 1) 
           { 
               fprintf (stderr, "\"% s \ ": read error \ n", File); 
               exit (1); 
           } 
           printf ("Phone Number:");  // Requesting and entering a number 
           if (gets (Number) == NULL || * Number == '\ 0') 
           { 
               fclose (F_tel); 
               return;  // return, if the number is not entered 
           } 
  // Set the pointer in the file to the first free entry 
           if (fseek (F_tel, (long) ((MAX_NAME + MAX_NUMBER) * Count), SEEK_CUR)! = 0) 
           { 
               fprintf (stderr, "\"% s \ ": search error \ n", File); 
               exit (1); 
           } 
           fwrite (str, 1, MAX_NAME, F_tel);  // Write to last name file 
           for (i = 0; i <MAX_NUMBER; i ++)  
           sn [i] = '';  // Spaces in sn [] 
           strcpy (sn, Number);  // Copy the timeline Number to string sn 
           fwrite (sn, 1, MAX_NUMBER, F_tel);  // Write to the file number 
           if (ferror (F_tel)) // Check for error 
           { 
               fprintf (stderr, "\"% s \ ": write error \ n", File); 
               exit (1); 
           } 
  // Set the pointer in the file to the first byte 
           if (fseek (F_tel, 0L, SEEK_SET)! = 0) 
           { 
               fprintf (stderr, "\"% s \ ": positioning error \ n", File); 
               exit (1); 
           } 
           ++ Count;  // Increase the number of records by one 
  // Write Count to file 
           if (fwrite (& Count, sizeof (int), 1, F_tel)! = 1)   
           { 
               fprintf (stderr, "\"% s \ ": write error \ n", File); 
               exit (1); 
           } 
           fclose (F_tel); 
           return; 
  } 
 

The subt.c module contains the Sub () function, which removes the specified string from the tel_num.txt file.

  // Module subt.c 
  // ------------------------------------------------ ------------ 
  // The Sub () function removes the specified string from the tel_num.txt file  
  // ------------------------------------------------ ------------ 
  void Sub (char * str) 
  { 
      int i, j; 
      char temp [MAX_NAME + MAX_NUMBER];  // Temporary array 

      if ((F_tel = fopen (File, "r +")) == NULL) 
      { 
          fprintf (stderr, "\"% s \ ": unable to open \ n", File); 
          exit (1); 
      } 
      if (fread (& Count, sizeof (int), 1, F_tel)! = 1) 
      { 
          fprintf (stderr, "\"% s \ ": read error \ n", File); 
          exit (1); 
      } 
  // The loop searches for the deleted line in the file. 
      for (i = 0; i <count; i ++) 
      { 
          fread (temp, 1, MAX_NAME + MAX_NUMBER, F_tel); 
          if (ferror (F_tel)) 
          { 
              fprintf (stderr, "\"% s \ ": read error \ n", File); 
              exit (1); 
          } 
          if (strcmp (str, temp) == 0) // If a term is found  
          { 
              for (j = i; j <count; j ++) // it is removed 
              {   
                  fread (temp, 1, MAX_NAME + MAX_NUMBER, F_tel); 
                  fseek (F_tel, (long) (j * (MAX_NAME + MAX_NUMBER) + 2L), SEEK_SET); 
                  fwrite (temp, 1, MAX_NAME + MAX_NUMBER, F_tel); 
                  fseek (F_tel, (long) ((j + 2) * (MAX_NAME + MAX_NUMBER) + 2L), SEEK_SET); 
                  if (ferror (F_tel)) 
                  { 
                      fprintf (stderr, "\"% s \ ": read error \ n", File); 
                      exit (1); 
                  } 
              } 
              --Count;  // when deleting a string, decrement Count 
              fseek (F_tel, 0L, SEEK_SET);  // Set the pointer 
  // Write the reduced Count value to the file 
              if (fwrite (& Count, sizeof (Count), 1, F_tel)! = 1) 
              { 
                  fprintf (stderr, "\"% s \ ": write error \ n", File); 
                  exit (1); 
              } 
              fclose (F_tel); 
              puts ("The entry was removed from the file"); 
              return; 
          } 
      } 
      fprintf (stderr, "\"% s \ ": not in the database \ n", File); 
      fclose (F_tel); 
  } 
 

Below is a possible scenario for working with the main program.

  main + Petrov <Enter> 
  Telephone Number: 77-17-89 <Enter> 
  main + Ivanov <Enter> 
  Telephone Number: 52-98-02 <Enter> 

  main Ivanov <Enter> 
  Surname: Ivanov 
  Telephone Number: 52-98-02 

  main - Petrov <Enter>  
  Record removed from file 

  main Petrov <Enter> 
  "tel_num.txt": no record in file 
 

The latest program showt.c allows you to display the contents of the telephone directory.

  // Program showt.c  
  // ------------------------------------------------ - 
  // Displays all entries from the tel_num.txt file  
  // ------------------------------------------------ - 
  #include "my.h"  
  void Show (void)  
  {  
      int i;  
  // If the file cannot be opened for reading, then the program will end  
      if ((F_tel = fopen (File, "r")) == NULL)  
      { 
          fprintf (stderr, "\"% s \ ": unable to open \ n", File); 
          exit (1); 
      } 
  // Read the number of records (Count) in the file 
      if (fread (& Count, sizeof (int), 1, F_tel)! = 1)   
      { 
          fprintf (stderr, "\"% s \ ": read error \ n", File); 
          exit (1); 
      } 
  // In the loop, all records are displayed.  
      for (i = 0; i <count; i ++)  
      { 
          fread (Name, 1, MAX_NAME, F_tel);  // Read the name 
          fread (Number, 1, MAX_NUMBER, F_tel);  // Read the number 
          if (ferror (F_tel)) // Check for no error  
          { 
              fprintf (stderr, "\"% s \ ": read error \ n '', File); 
              exit (1); 
          } 
          printf ("Last Name:% s; phone number:% s \ n", Name, Number); 
      } 
      fclose (F_tel); 
  } 
  void main (void) 
  { 
      Show (); 
  } 
 
  7. EXAMPLES in the C language (+ literature)

LITERATURE

  1. Sklyarov V.A. Programming in C and C ++ .- M .: Higher School, 1996.
  2. Berezin BI, Berezin S.B. The initial course of C and C ++ .- M .: DIALOG-MEPI, 1999.
  3. Kernigan B., Ritchie D. C Programming Language. M: Finance and Statistics, 1992.
  4. Podbelsky V.V., Fomin S.S. C programming. Training allowance.- M .: Finance and Statistics, 2000.
  5. Pavlovskaya T.A. C / C ++, Programming in a high-level language. - SPb .: Peter, 2005.
  6. Kasatkin A.I. Professional C programming. System programming .- Minsk: Higher School, 1993.
  7. Kasatkin A.I. Professional C programming. Resource Management.- Minsk: Higher School, 1993.
  8. Kasatkin A.I., Valvachev A.N. Professional C programming. From Turbo C to Borland C ++ .- Minsk: High School, 1995.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Algorithmization and programming. Structural programming. C language

Terms: Algorithmization and programming. Structural programming. C language