Program to alphabetize a customer list

The increasing popularity of C is probably due to its many desirable qualities. It is a robust language whose rich set of built-in functions amd operators can be used to write any complex program. The C complier combines the capabilities of an assembly language with the features of the high level language  and therefore it is  well suited for writing both system software and business packages. In this blog, about 68 examples of C programming are written which is understand to you that how C programming works. 





Program :          Processing of a Customer List

Telephone number of important customers are recorded as follows:
                  Full name                              Telephone number
                 Joseph Louis Lagrange        869245
                 Jean Robert Argand              900823
                     Carl Freidrich Gauss             806788
                 ----------                                    ---------
                -----------                                    ---------
It is desired to prepare a revised alphabetical list with surname (last name) first, followed by a comma and the initials of the first and the middle names. For example,
    Argand, J.R
We create a table of strings, each row representing the details of one person, such as first_name, middle_name, last_name, and telephone_number. The columns are interchanged as required and the list is sorted an the last_name.

                                  PROGRAM

# define CUSTOMERS 10
main ( )
 {
        char  first_name [20] [10], second name [20] [10],
        surname [20] [10], name [20] [20], telephone [20] [10],
        dummy [20] ;
        int i, j ;
          printf ("Input names and a telephone number \n") ;
          printf ("?") ;
          for (i = 0; i < CUSTOMER; i++)
          {
              scanf ("%s %s %s %s", first_name[i],
                        second_name [i], surname [i], telephone[i]) ;

              /*  converting full name to surname with initials  */

              strcpy (name[i], surname [i]) ;
              strcat (name[i], ",") ;
              dummy [0] = first_name [i] [0] ;
              dummy [1] = '\0' ;
              strcat (name [i], dummy) ;
              strcat (name [i], ".") ;
              dummy [0] = second_name [i] [0] ;
              dummy [1] = '\0' ;
              strcat (name [i], dummy) ;
         }
           /*  Alphabetical ordering of surnames  */
                 
                 for (i = 1; i <= CUSTOMERS - 1; i++)
                     for (j = 1; j<= CUSTOMERS - i; j++)
                         if (strcmp (name[j - i], name [j]) > 0)
                         {
                         /*   Swaping names  */
                                 strcpy (dummy, name [j - 1]) ;
                                 strcpy (name [j - 1], name [j]) ;
                                 strcpy (name [j], dummy) ;

                       /*     Swaping telephones numbers   */
                               strcpy (dummy, telephone [j - 1]) ;
                               strcpy (telephone [j - 1], telephone[j]) ;
                               strcpy (telephone [j], dummy) ;
                        }
                 /*   Printing alphabetical list  */
             printf ("\nCUSTOMERS LIST IN ALPHABETICAL 
                                 ORDER \n\n") ;
             for (i = 0; i < CUSTOMERS; i++) 
              printf (" %-20s\t  %-10s\n", name [i], telephone[i]);
  }

Output:    Input names and telephone number
                 ? Gottfreind Wilhelm Leibniz 7115198
                 Joseph Louis LAGRANGE 869245


                 Jean Robert Argand  900823
                 Carl Freidrich Gauss  806788
                 Simon Denis Poisson  853240
                 Friedrich Withelm Bessel  719731
                 Charles Francois Sturm  222031
                George Gabriel Srokes  545454
                Mohandas Kramachand Gnadhi  362718
                Josian Willard Gibbs 123145


             CUSTOMERS LIST IN ALPHABETICAL ORDER
               Argand,J.R       900823
               Bessel,F.W       719731
               Gandhi,M.K      362718
               Gauss,C.F        806788
               Gibbs,J.W        123145
               Lagrange,J.L   869245
               Leibniz,G.W     711518
               Poission,S.D    853240
               Strokes,G.G     545454
               Strum,C.F         222031
     
 

 

Using structure as a function parameter

Program 50) Write a simple program to illustrate the method of sending an entire structure as a function to a function.
A program to update an item as shown below. The function updates receives a copy of the structure variable item as one of its parameters. Note that both the function update and the formal parameter product are declared as type struct stores. It is done so because the function uses the parameter product to receive the parameter product to receive the structure variable item and also to return the updated values of item.

The function mul is of type float because it returns the product of price abd quantity. However, the parameter stock, which receives the structure variable item is declared as type struct stores.  
  The entire structure returned by update can be copied 
into a structure of identical type. The statement
                 item = update (item, p_increment, q_increment) ;
replaces the old values of item by the new ones.

                                  PROGRAM
/*         Passing a copy of the entire structure        */
   struct      stores
   {
            char name [20] ;
            float price ;
            int  quantity ;
  } ;
 struct stores update (struct stores product, float p, int q) ;
 float mul  (struct stores stock) ;
 main ( )
  {
        float   p_increment, value ;
        int      q_increment ;

       struct stores item = {"XYZ", 25.75, 12) ;

      printf ("\nInput Increment values:") ;
      Printf ("    price increment and quantity increment\n") ;
      scanf ("%f %d", &p_increment, &q_increment) ;

/*  ----------------------------------------------------------------------*/
       item = update (item, p_increment, q_increment) ;
/*  ----------------------------------------------------------------------*/
      printf ("Updated values of item\n\n") ;
      printf ("Name        : %s\n", item.name) ;
      printf ("Price         : %f\n", item.price) ;
      printf ("Quantity   : %d\n", item.quantity) ;

/*  ---------------------------------------------------------------------*/
      Value = mul (item) ;
/*  --------------------------------------------------------------------*/
      Printf ("\nvalue of the item = %f\n", value) ;
 }
 struct stores update (struct stores product, float p, int q)
 {
          product.price += p ;
          product.quantity += q ;
          return (product) ;
 }
 float mul (struct stores stock)
 {
       return (stock.price * stock . quantity) ;
 }

                              Output    

Input increment values : price increment and quality
                                                                                                                  increment
10  12
Updated values of item
NAME      :  XYZ
Price        :  35.750000
Quantity  :  24
Value of the item = 858.000000


You may notice that the template of stores is defined before main( ). This has made the data type struct stores as global and has enabled the functions update and mul to make use of this definition.

Arrays of structures: Illustration of subscripted structure variables

Program 49) For the student array. Writ a program t calculate the subject-wise and student-wise totals and store them as a part of the structure.
 This program is shown below. We have declared a four-member structure, the fourth one for keeping the student-totals. We have also declared as array total o keep the subject totals and the grand total. The grand total is given by total.total. Note that a member name can be any valid C name and can be the same as an existing structure variables names. The linked name total.total represents the total member of the structure variable total.
                                                                                     
              student [0].subject 1         |           45         |
                                 .subject 2         |         68          |
                                 .subject 3         |          81          |
              student [1].subject 1         |          75          |
                                 .subject 2         |          53          |
                                 .subject 3         |          69          |
              student [2].subject 1         |          57          |
                                 .subject2          |          36          |
                                 .subject 3         |          71          |   

                       The array student inside memory 

                                      PROGRAM

struct marks
{
        int sub1 ;
        int sub2 ;
        int sub3 ;
        int total ;
} ;
main ( )
 {
       int i ;
       struct marks student [3] = { {45,67,81,0},
                                                       {75,53,69,0},
                                                       {57,36,71,0} } ;
      struct marks total ;
      for (i = 0; i <= 2; i++)
      {
             student [i].total = student [i].sub1 +
                                            student [i].sub2 +
                                            student [i]sub3 ;
             total.sub1 = total . sub1 + student [i] . sub1 ;
             total.sub2 = total . sub2 + student [i] . sub2 ;
             total.sub3 = total . sub3 + student [i] . sub3 ;
             total.total = total . total + student [i] . total ;
     }
     printf ("  STUDENT             TOTAL\n\n") ;
     for (i = 0; i <= 2; i++)
            printf ("Student [%d]      %d\n", i + 1, 
                                    student [i] . total) ;
     printf ("\n  SUBJECT            TOTAL\n\n") ;
     printf ("%s    %d\n%s       %d\n%s        %d\n",
                                 "Subject 1   ", total.sub1,
                                 "Subject 2   ", total.sub2,
                                 "Subject 3   ", total.sub3) ;
   printf ("\nGrand Total = %d\n", total.total) ;
 }

Output:            STUDENT             TOTAL
                         Student [1]              193
                         Student [2]              197
   
                         Student [3]               164

                         SUBJECT               TOTAL 
                         Subject 1                   177
                         Subject 2                   156
                         Subject 3                   221

                         Grand total      =    554         
2) The program calculates cosines values for angle 0,10,20.......180 and prints out the results with headings.

#include <math.h>
#define    PI3.1416
#define    MAX 180

main( )
 {
        int angle;
        float x,y;
      
        angle = 0;
        printf(" Angle    Cos(angle)\n\n);
        
        while(angle <= MAX)
         {
                 x = (PI/MAX)*angle;
                 y = cos(x);
                 printf("%15d %13.4f\n", angle, y);
                 angle = angle + 10;
         }
       getch();
 } 

Output: Angle         Cos(angle)
                   0                 1.0000
                   10               0.9848
                   20               0.9397
                   30               0.8660
                   40               0.7660
                   50               0.6428
                   60               0.5000
                   70               0.3420
                   80               0.1736
                   90              -0.0000
                  100             -0.1737
                  110             -0.3420
                  120             -0.5000
                  130             -0.6428
                  140             -0.7660
                  150             -0.8660
                  160             -0.9397
                  170             -0.9848
                  180             -1.0000

                         Program using a math function
  

Accessing a variable through its pointer

Program 51) Write a program to illustrate the use of indirection operator '*' to access the value p[ointed to by a printer.
The program clearly shows how weanm access the value of a variable using a pointer. You may notice that the value of the pointer is 4104 and the value its points to is 10. Further, you may also note the following  equivalness:
                 x = * (&x) = * ptr = y
                 &x = & *ptr

                                        PROGRAM

main ( )
 {
      int x, y ;
      int *ptr ;
      x = 10 ;
      ptr = &x ;
     y = * ptr ;

     printf ("Vlue of x is %d\n\n", x) ;
     printf ("%d is stored at addr %u\n", x, &x) ;
     printf ("%d is stored at addr %u\n", *&x, &x) ;
     printf ("%d is stored at addr %u\n", *ptr, ptr) ;
     printf ("%d is stored at addr %u\n", ptr, &ptr) ;
     printf ("%d is stored at addr %u\n", y, &y) ;
     *ptr = 25 ;
     printf ("\nNOW x = %d\n", x) ;
 }

Output:            Value of x is 10
                         10        is stored at addr 4104
                         10        is stored at addr 4104
                         10        is stored at addr 4104
                         4104    is stored at addr 4106
                         10        is stored at addr 4108
                         Now x = 25

 

Evaluation of pointer expressions

Program 52) Write a program to illustrate the use of pointers in airthmetic operations.
This program shows how the pointer variables can be directly used in expressions. It also illustrates the order of evaluation of expressions. For example, the expression
                       
                          4* - *p2 / *p1 + 10
is evaluated as follows:
                        ( (4* (-(*p2))) / (*p1)) + 10

When *p1 = 12 and *p2 = 4, this expression evaluates to 9. Remember, since all the variables are of type int, the entire evaluation is carried out using the integer airthmetic.

                                  PROGRAM

main ( )
 {
     int a, b, *p1, *p2, x, y, z ;
     a = 12 ;
     b =  4 ;
     p1 = &a ;
     p2 = &b ;
     x = *p1 *  *p2 - 6 ;
     y = 4* - *p2 / *p1 + 10 ;
     printf ("Address of a = %u\n", p1) ;
     printf ("Address of b = %d\n",p2) ;
     *p2 = *p2 + 3 ;
     *p1 = *p2 - 5 ;
     z    =  *p1 *  *p2 - 6 ;
    printf ( "\na = %d, b = %d,", a, b) ;
    printf (" z = %d\n", z) ;
 }

Output:        Address of a = 4020
                     Address of b = 4016
                     a = 12, b = 4
                     x = 42, y = 9
                     a = 2, b = 7, z = 8 

  

Accessing one dimensional array elements using the pointer

Program 53) Write a program using pointers to compute the sum of all elements stored in an array.

This program shows illustrates how a pointer can be used to traverse an array element. Since incrementing an array pointer causes it to point to the next element, we need only to add one to p each time we go through the loop.

                                     PROGRAM

main ( )
 {
      int *p, sum, i ;
      int x[5] = {5, 9, 6, 3, 7} ;
      i = 0 ;
     p = x ;    /*    Initializing with base address of     */
     printf ("Element value address\n\n) ;
     while (i < 5)
     {
          printf (" x[%d] %d %u\n", i, *p, p) ;
          sum = sum + *p ;    /*  accessing array element   */
          i++, p++ ;                /*   incrementing pointer   */
     }
     printf ("\n   Sum   =   %d\n",  sum) ;
     printf ("\n   &x [10]   =   %u\n",  &x [10]) ;

     printf ("\n  p   =   %u\n",   p) ;
 }

Output:              Element               Value           Address
                          x [0]                      5                     166
                          x [1]                      9                     168
                          x [2]                      6                     170
                          x [3]                      3                     172
                          x [4]                      7                     174
                         Sum    =    55
                         &x [0]  =    166
                         p         =    176

Passing of pointers as function parameters

Program 54) Write a function using pointers to exchange the values in tw2o location in the memory.
This program shows how the content of two locations can be exchanged using their address locations. The function exchange ( ) recieves the addresses of the variables x and y exchanges their contents.

                                   PROGRAM

void exchange (int *, int *) ;       /*     prototype       */
main ( )
 {
       int x, y ;
      x = 100 ;
      y = 200 ;
      printf ("Before exchange  : x = %d   y = %d\n\n", x, y) ;
      exchange (&x, &y) ;    /*      call      */
      printf ("After exchange   :  x = %d   y = %d\n\n", x, y) ;
 }
 exchange (int *a, int *b)
 {
         int t ;     /*  Assign the value at address a to t  */
         t = *a ;   /*  put b into a  */
         *a = *b ;   /*  put t into b   */
 }

Output:           Before exchange   :  x = 100   y = 200
                       After exchange      :  x = 200   y = 100


You may note the following points:
1. The function parameters are declared as pointers.
2. The dereferenced pointers are used in the function
    body.
3. When the function is called, the addresses are passed
    as actual arguements.

Use of pointers to function

Program 55) Write a program that uses a function pointer as a function arguement.
A program to print the function values over a given range of values. The printing is done by the function table by evaluating the function passed to it by the main.

With table, we declare the parameter f as a pointer to a function as follows:
                          double  (* f) () ;
The value returned bythe function is of type double. When table is called in the statement
                         table (y, 0.0, 2, 0.5) ;
we pass a pointer to the function y as the first parameter of table. Note that y is not followed by a parameter list.
During the execution of table, the statement
                                value = (* f) (a) ;
calls the function y which is pointed to by f, passing it the parameter a. Thus the function y is evaluated over the range 0.0 to 2.0 at the intervals of 0.5.
    Similarly the call
                              table (cos, 0.0, PI, 0.5) ;
passes a pointer to cos as its first parameter and therefore, the function table evaluates the value of cos over the range 0.0 to PI at the intervals of 0.5.

                                     PROGRAM

#include <math.h>
#define  PI  3.1415926
double y (double) ;
double cos (double) ;
double table (double (*f) (), double, double, double) ;

main ( )
 {
       printf ("Table of y(x) = 2 * x * x - x + 1\n\n") ;
       table (y, 0.0, 2.0, 0.5) ;
       printf ("\nTable of cos (x) \n\n") ;
       table (cos, 0.0, PI, 0.5) ;
 }
double table (double (*f) (), double min, double max, 
                                             double max, double step)
{       double a, value ;
        for (a = min; a <= max; a += step)
        {
                value  = (*f) (a) ;
                printf ("%5.2f  %10.4f\n", a, value) ;
        }
}
double y (double x)
{
           return (2 * x * x - x + 1) ;
}

Output:                Table of y (x) = 2 * x * x - x + 1
                                0.00              1.0000
                                0.50              1.0000
                                1.00              2.0000
                                1.50              4.0000
                                2.00              7.0000
                           Table of cos (x)
                                0.00              1.0000
                                0.50              0.8776
                                1.00              0.5403
                                1.50              0.0707
                                2.00             -0.4161
                                3.00             -0.9900