Vb, Delphi, .net, framework, C++, Java, Pascal,Visual Studio, Asm, Ruby, C#, j#, Cs, Html, Php, Perl, Asp, xHtml Get Free Souce Code Here...



Further Data Types

This Chapter discusses how more advanced data types and structures can be created and used in a C program.

Structures

Structures in C are similar to records in Pascal. For example:

  struct gun
    {
    char name[50];
    int magazinesize;
    float calibre;
    };
 
  struct gun arnies;

defines a new structure gun and makes arnies an instance of it.

NOTE: that gun is a tag for the structure that serves as shorthand for future declarations. We now only need to say struct gun and the body of the structure is implied as we do to make the arnies variable. The tag is optional.

Variables can also be declared between the } and ; of a struct declaration, i.e.:

  struct gun
    {
    char name[50];
    int magazinesize;
    float calibre;
    } arnies;

struct's can be pre-initialised at declaration:

  struct gun arnies={"Uzi",30,7};


which gives arnie a 7mm. Uzi with 30 rounds of ammunition.
To access a member (or field) of a struct, C provides the . operator. For example, to give arnie more rounds of ammunition:

   arnies.magazineSize=100;

Defining New Data Types

typedef can also be used with structures. The following creates a new type agun which is of type struct gun and can be initialised as usual:

  typedef struct gun
    {
    char name[50];
    int magazinesize;
    float calibre;
    } agun;
 
   agun arnies={"Uzi",30,7};

Here gun still acts as a tag to the struct and is optional. Indeed since we have defined a new data type it is not really of much use,

agun is the new data type. arnies is a variable of type agun which is a structure.

C also allows arrays of structures:

  typedef struct gun
    {
    char name[50];
    int magazinesize;
    float calibre;
    } agun;
 
  agun arniesguns[1000];

This gives arniesguns a 1000 guns. This may be used in the following way:

          arniesguns[50].calibre=100;

gives Arnie's gun number 50 a calibre of 100mm, and:


          itscalibre=arniesguns[0].calibre;
assigns the calibre of Arnie's first gun to itscalibre.

Unions

A union is a variable which may hold (at different times) objects of different sizes and types. C uses the union statement to create unions, for example:

          union number
     {
     short shortnumber;
     long longnumber;
     double floatnumber;
     } anumber

defines a union called number and an instance of it called anumber. number is a union tag and acts in the same way as a tag for a structure.
Members can be accessed in the following way:

          printf("%ld$\setminus$n",anumber.longnumber);

This clearly displays the value of longnumber.

When the C compiler is allocating memory for unions it will always reserve enough room for the largest member (in the above example this is 8 bytes for the double).

In order that the program can keep track of the type of union variable being used at a given time it is common to have a structure (with union embedded in it) and a variable which flags the union type:

An example is:

  typedef struct
     { int maxpassengers;
     } jet;
 
  typedef struct
     { int liftcapacity;
     } helicopter;
 
  typedef struct
     { int maxpayload;
     } cargoplane;
 
   typedef    union
     { jet jetu;
       helicopter helicopteru;
       cargoplane cargoplaneu;
     } aircraft;
 
  typedef    struct
     { aircrafttype kind;
       int speed;
       aircraft description;
     } an_aircraft;

This example defines a base union aircraft which may either be jet, helicopter, or
cargoplane.

In the an_aircraft structure there is a kind member which indicates which structure is being held at the time.

Coercion or Type-Casting

C is one of the few languages to allow coercion, that is forcing one variable of one type to be another type. C allows this using the cast operator (). So:


  int integernumber;
   float floatnumber=9.87;
 
     integernumber=(int)floatnumber;


assigns 9 (the fractional part is thrown away) to integernumber.


And:


  int integernumber=10;
   float floatnumber;
 
     floatnumber=(float)integernumber;

assigns 10.0 to floatnumber.

Coercion can be used with any of the simple data types including char, so:

          int integernumber;
   char letter='A';
 
     integernumber=(int)letter;

assigns 65 (the ASCII code for `A') to integernumber.
Some typecasting is done automatically -- this is mainly with integer compatibility.

A good rule to follow is: If in doubt cast.

Another use is the make sure division behaves as requested: If we have two integers internumber and anotherint and we want the answer to be a float then :


e.g.
 floatnumber =
   (float) internumber / (float) anotherint;

ensures floating point division.

Enumerated Types

Enumerated types contain a list of constants that can be addressed in integer values.

We can declare types and variables as follows.

  enum days {mon, tues, ..., sun} week;
  enum days week1, week2;

NOTE: As with arrays first enumerated name has index value 0. So mon has value 0, tues 1, and so on.

week1 and week2 are variables.


We can define other values:


  enum escapes { bell = `$\backslash$a',
   backspace = `$\backslash$b',  tab = `$\backslash$t',
   newline = `$\backslash$n', vtab = `$\backslash$v',
   return = `$\backslash$r'};
We can also override the 0 start value:

  enum months {jan = 1, feb, mar, ......, dec};


Here it is implied that feb = 2 etc.

Static Variables

A static variable is local to particular function. However, it is only initialised once (on the first call to function).
Also the value of the variable on leaving the function remains intact. On the next call to the function the the static variable has the same value as on leaving.
To define a static variable simply prefix the variable declaration with the static keyword. For example:


  void stat(); /* prototype fn */ 
 
   main()
    { int i;
 
     for (i=0;i<5;++i)
       stat();
    }
 

stat()
    {  int auto_var = 0;
     static int static_var = 0;
 
     printf( ``auto = %d, static = %d $\backslash$n'',
       auto_var, static_var);
     ++auto_var;
     ++static_var;
    }
Output is:


  auto_var = 0, static_var= 0
  auto_var = 0, static_var = 1
  auto_var = 0, static_var = 2
  auto_var = 0, static_var = 3
  auto_var = 0, static_var = 4

Clearly the auto_var variable is created each time. The static_var is created once and remembers its value.

Exercises

Exercise 12386
Write program using enumerated types which when given today's date will print out tomorrow's date in the for 31st January, for example.
Exercise 12387
Write a simple database program that will store a persons details such as age, date of birth, address etc.

Functions

C provides functions which are again similar most languages. One difference is that C regards main() as function. Also unlike some languages, such as Pascal, C does not have procedures -- it uses functions to service both requirements.
Let us remind ourselves of the form of a function:

  returntype fn_name(1, parameterdef2,$\cdots$)
 
    
 
    {
 
     localvariables
 
     functioncode
 
     }

Let us look at an example to find the average of two integers:


  float findaverage(float a, float b)
    { float average;
 
>     average=(a+b)/2;
       return(average);
    }
 
We would call the function as follows:
 
   main()
    {    float a=5,b=15,result;
 
       result=findaverage(a,b);
       printf("average=%f$\setminus$n",result);
    }
 
Note: The return statement passes the result back to the main program.

void functions

The void function provide a way of emulating PASCAL type procedures.
If you do not want to return a value you must use the return type void and miss out the return statement:


  void squares()
    { int loop;
 
       for (loop=1;loop<10;loop++);
         printf("%d$\setminus$n",loop*loop);
    }
 
   main() 
 
    {    squares();
    }
NOTE: We must have () even for no parameters unlike some languages.

Functions and Arrays

Single dimensional arrays can be passed to functions as follows:-

  float findaverage(int size,float list[])
 
    { int i;
       float sum=0.0;
 
       for (i=0;i
         sum+=list[i];
       return(sum/size);
    }

Here the declaration  float list[] tells C that list is an array of float. Note we do not specify the dimension of the array when it is a parameter of a function.
Multi-dimensional arrays can be passed to
functions as follows:



  void printtable(int xsize,int ysize,
       float table[][5])
 
    { int x,y;
 
       for (x=0;x
         { for (y=0;y
           printf("$\setminus$t%f",table[x][y]);
         printf("$\setminus$n");
      }
    }
Here float table[][5] tells C that table is an array of dimension N$\times$5 of float. Note we must specify the second (and subsequent) dimension of the array BUT not the first dimension.

Function Prototyping

Before you use a function C must have knowledge about the type it returns and the parameter types the function expects.
The ANSI standard of C introduced a new (better) way of doing this than previous versions of C. (Note: All new versions of C now adhere to the ANSI standard.)
The importance of prototyping is twofold.
  • It makes for more structured and therefore easier to read code.
  • It allows the C compiler to check the syntax of function calls.
How this is done depends on the scope of the function (See Chapter 34). Basically if a functions has been defined before it is used (called) then you are ok to merely use the function.
If NOT then you must declare the function. The declaration simply states the type the function returns and the type of parameters used by the function.
It is usual (and therefore good) practice to prototype all functions at the start of the program, although this is not strictly necessary.
To declare a function prototype simply state the type the function returns, the function name and in brackets list the type of parameters in the order they appear in the function definition.

e.g.
int strlen(char []);

This states that a function called strlen returns an integer value and accepts a single string as a parameter.
NOTE: Functions can be prototyped and variables defined on the same line of code. This used to be more popular in pre-ANSI C days since functions are usually prototyped separately at the start of the program. This is still perfectly legal though: order they appear in the function definition.

e.g.
int length, strlen(char []);

Here length is a variable, strlen the function as before.

Exercises

Exercise 12346
Write a function ``replace'' which takes a pointer to a string as a parameter, which replaces all spaces in that string by minus signs, and delivers the number of spaces it replaced.
Thus
char *cat = "The cat sat";
        n = replace( cat );
should set
cat to "The-cat-sat"
and
n to 2.
Exercise 12347
Write a program which will read in the source of a C program from its standard input, and print out all the starred items in the following statistics for the program (all as integers). (Note the comment on tab characters at the end of this specification.)
Print out the following values:
Lines:
  *  The total number of lines
  *  The total number of blank lines
        (Any lines consisting entirely of white space should be
        considered as blank lines.)
     The percentage of blank lines (100 * blank_lines / lines)

  Characters:
  *  The total number of characters after tab expansion
  *  The total number of spaces after tab expansion
  *  The total number of leading spaces after tab expansion
      (These are the spaces at the start of a line, before any visible
        character; ignore them if there are no visible characters.)
    The average number of
      characters per line
      characters per line ignoring leading spaces
      leading spaces per line
      spaces per line ignoring leading spaces

  Comments:
  *  The total number of comments in the program
  *  The total number of characters in the comments in the program
       excluding the "/*" and "*/" thenselves
    The percentage of number of comments to total lines
    The percentage of characters in comments to characters

  Identifiers:
    We are concerned with all the occurrences of "identifiers" in the
      program where each part of the text starting with a letter,
      and continuing with letter, digits and underscores is considered
      to be an identifier, provided that it is not
          in a comment,
          or in a string,
          or within primes.
        Note that
            "abc\"def"
        the internal escaped quote does not close the string.
        Also, the representation of the escape character is
            '\\'
 and of prime is
            '\''
      Do not attempt to exclude the fixed words of the language,
      treat them as identifiers. Print
  *  The total number of identifier occurrences.
  *  The total number of characters in them.
    The average identifier length.

  Indenting:
  *  The total number of times either of the following occurs:
      a line containing a "}" is more indented than the preceding line
      a line is preceded by a line containing a "{" and is less
        indented than it.
      The "{" and "}" must be ignored if in a comment or string or
        primes, or if the other line involved is entirely comment.
    A single count of the sum of both types of error is required.
NOTE: All tab characters ('') on input should be interpreted as multiple spaces using the rule:
"move to the next modulo 8 column"
  where the first column is numbered column 0.
 col before tab | col after tab
        ---------------+--------------
                0      |      8
                1      |      8
                7      |      8
                8      |     16
                9      |     16
               15      |     16
               16      |     24
To read input a character at a time the skeleton has code incorporated to read a line at a time for you using
char ch;
        ch = getchar();
Which will deliver each character exactly as read. The "getline" function then puts the line just read in the global array of characters "linec", null terminated, and delivers the length of the line, or a negative value if end of data has been encountered. You can then look at the characters just read with (for example)
switch( linec[0] ) {
        case ' ': /* space ..... */
                break;
        case '\t': /* tab character .... */
                break;
        case '\n': /* newline ... */
                break;
        ....
        } /* end switch */
End of data is indicated by scanf NOT delivering the value 1.

Your output should be in the following style:
Total lines                     126
        Total blank lines               3
        Total characters                3897
        Total spaces                    1844
        Total leading spaces            1180
        Total comments                  7
        Total chars in comments         234
        Total number of identifiers     132
        Total length of identifiers     606
        Total indenting errors          2
You may gather that the above program (together with the unstarred items) forms the basis of part of your marking system! Do the easy bits first, and leave it at that if some aspects worry you. Come back to me if you think my solution (or the specification) is wrong! That is quite possible! Exercise 12348
It's rates of pay again!
Loop performing the following operation in your program:


Read two integers, representing a rate of pay (pence per hour) and a number of hours. Print out the total pay, with hours up to 40 being paid at basic rate, from 40 to 60 at rate-and-a-half, above 60 at double-rate. Print the pay as pounds to two decimal places.


Terminate the loop when a zero rate is encountered. At the end of the loop, print out the total pay.
The code for computing the pay from the rate and hours is to be written as a function.
The recommended output format is something like:
Pay at 200 pence/hr for 38 hours is 76.00 pounds
        Pay at 220 pence/hr for 48 hours is 114.40 pounds
        Pay at 240 pence/hr for 68 hours is 206.40 pounds
        Pay at 260 pence/hr for 48 hours is 135.20 pounds
        Pay at 280 pence/hr for 68 hours is 240.80 pounds
        Pay at 300 pence/hr for 48 hours is 156.00 pounds
        Total pay is 928.80 pounds
The ``program features'' checks that explicit values such as 40 and 60 appear only once, as a #define or initialised variable value. This represents good programming practice.

Arrays and Strings

  In principle arrays in C are similar to those found in other languages. As we shall shortly see arrays are defined slightly differently and there are many subtle differences due the close link between array and pointers. We will look more closely at the link between pointer and arrays later in Chapter 9.

Single and Multi-dimensional Arrays

Let us first look at how we define arrays in C:

  int listofnumbers[50];

BEWARE: In C Array subscripts start at 0 and end one less than the array size. For example, in the above case valid subscripts range from 0 to 49. This is a BIG difference between C and other languages and does require a bit of practice to get in the right frame of mind.
Elements can be accessed in the following ways:-


  thirdnumber=listofnumbers[2];
   listofnumbers[5]=100;
Multi-dimensional arrays can be defined as follows:


  int tableofnumbers[50][50];
for two dimensions.
For further dimensions simply add more [ ]:


  int bigD[50][50][40][30]......[50];
Elements can be accessed in the following ways:


  anumber=tableofnumbers[2][3];
   tableofnumbers[25][16]=100;

Strings

In C Strings are defined as arrays of characters. For example, the following defines a string of 50 characters:

  char name[50];
C has no string handling facilities built in and so the following are all illegal:


  char firstname[50],lastname[50],fullname[100];
 
   firstname= "Arnold"; /* Illegal */
   lastname= "Schwarznegger"; /* Illegal */
   fullname= "Mr"+firstname
     +lastname; /* Illegal */ 
However, there is a special library of string handling routines which we will come across later.
To print a string we use printf with a special %s control character:
   printf(``%s'',name);
NOTE: We just need to give the name of the string.
In order to allow variable length strings the $\backslash$0 character is used to indicate the end of a string.
So we if we have a string, char NAME[50]; and we store the ``DAVE'' in it its contents will look like:


Exercises

Exercise 12335
Write a C program to read through an array of any type. Write a C program to scan through this array to find a particular value.
Exercise 12336
Read ordinary text a character at a time from the program's standard input, and print it with each line reversed from left to right. Read until you encounter end-of-data (see below).
You may wish to test the program by typing
prog5rev | prog5rev
to see if an exact copy of the original input is recreated. To read characters to end of data, use a loop such as either
char ch;
        while( ch = getchar(), ch >= 0 ) /* ch < 0 indicates end-of-data */
or
char ch;
        while( scanf( "%c", &ch ) == 1 ) /* one character read */
Exercise 12337
Write a program to read English text to end-of-data (type control-D to indicate end of data at a terminal, see below for detecting it), and print a count of word lengths, i.e. the total number of words of length 1 which occurred, the number of length 2, and so on.
Define a word to be a sequence of alphabetic characters. You should allow for word lengths up to 25 letters.
Typical output should be like this:
length 1 : 10 occurrences
      length 2 : 19 occurrences
      length 3 : 127 occurrences
      length 4 : 0 occurrences
      length 5 : 18 occurrences
      ....
To read characters to end of data see above question.

Looping and Iteration

This chapter will look at C's mechanisms for controlling looping and iteration. Even though some of these mechanisms may look familiar and indeed will operate in standard fashion most of the time. NOTE: some non-standard features are available.

The for statement

The C for statement has the following form:

  for  (expression1; 2; expression3)
     statement;
     or {block of statements}
expression1 initialises; expression2 is the terminate test; expression3 is the modifier (which may be more than just simple increment);

NOTE: C basically treats for statements as while type loops

For example:

  int x;
 
   main()
     {
    for (x=3;x>0;x-)
       {
       printf("x=%d$\setminus$n",x);
       }
     }

...outputs:


  x=3
  x=2
  x=1
...to the screen

All the following are legal for statements in C. The practical application of such statements is not important here, we are just trying to illustrate peculiar features of C for that may be useful:-

  for (x=0;((x>3) && (x<9)); x++)
 
   for (x=0,y=4;((x>3) && (y<9)); x++,y+=2)
 
   for (x=0,y=4,z=4000;z; z/=10)

The second example shows that multiple expressions can be separated a ,.

In the third example the loop will continue to iterate until z becomes 0;

The while statement

The while statement is similar to those used in other languages although more can be done with the expression statement -- a standard feature of C.
The while has the form:

  while (expression)
     statement
For example:

  int x=3;
 
   main()
     { while (x>0)
       { printf("x=%d$\setminus$n",x);
         x-;
       }
     }

...outputs:

  x=3
  x=2
  x=1
...to the screen.

Because the while loop can accept expressions, not just conditions, the following are all legal:-

  while (x-);
  while (x=x+1);
  while (x+=5);

Using this type of expression, only when the result of x-, x=x+1, or x+=5, evaluates to 0 will the while condition fail and the loop be exited.

We can go further still and perform complete operations within the while expression:

  while (i++ < 10);
 
  while ( (ch = getchar()) != `q')
    putchar(ch);

The first example counts i up to 10.

The second example uses C standard library functions (See Chapter 18) getchar() - reads a character from the keyboard - and putchar() - writes a given char to screen. The while loop will proceed to read from the keyboard and echo characters to the screen until a 'q' character is read. NOTE: This type of operation is used a lot in C and not just with character reading!! (See Exercises).

The do-while statement

C's do-while statement has the form:

  do 
     statement;
     while (expression);
It is similar to PASCAL's repeat ... until except do while expression is true.

For example:

  int x=3;
 
   main()
     { do {
       printf("x=%d$\setminus$n",x-);
       }
     while (x>0);
     }

..outputs:-

  x=3
   x=2
   x=1
NOTE: The postfix x- operator which uses the current value of x while printing and then decrements x.

break and continue

C provides two commands to control how we loop:
  • break -- exit form loop or switch.
  • continue -- skip 1 iteration of loop.
Consider the following example where we read in integer values and process them according to the following conditions. If the value we have read is negative, we wish to print an error message and abandon the loop. If the value read is great than 100, we wish to ignore it and continue to the next value in the data. If the value is zero, we wish to terminate the loop.

   while (scanf( ``%d'', &value ) == 1 && value != 0) { 
 
     if (value < 0) {
       printf(``Illegal value$\backslash$n'');
       break;
       /* Abandon the loop */
     }
 
     if (value > 100) {
       printf(``Invalid value$\backslash$n'');
       continue;
       /* Skip to start loop again */
     }
 
     /* Process the value read */
       /* guaranteed between 1 and 100 */
           ....;
 
     ....;
   } /* end while value != 0 */

Exercises

Exercise 12327
Write a program to read in 10 numbers and compute the average, maximum and minimum values.
Exercise 12328
Write a program to read in numbers until the number -999 is encountered. The sum of all number read until this point should be printed out.
Exercise 12329
Write a program which will read an integer value for a base, then read a positive integer written to that base and print its value.
Read the second integer a character at a time; skip over any leading non-valid (i.e. not a digit between zero and ``base-1'') characters, then read valid characters until an invalid one is encountered.
Input       Output
        ==========     ======
        10    1234      1234
         8      77        63   (the value of 77 in base 8, octal)
         2    1111        15   (the value of 1111 in base 2, binary)
The base will be less than or equal to 10. Exercise 12330
Read in three values representing respectively
a capital sum (integer number of pence),
a rate of interest in percent (float),
and a number of years (integer).
Compute the values of the capital sum with compound interest added over the given period of years. Each year's interest is calculated as
interest = capital * interest_rate / 100;
and is added to the capital sum by
capital += interest;
Print out money values as pounds (pence / 100.0) accurate to two decimal places.
Print out a floating value for the value with compound interest for each year up to the end of the period.
Print output year by year in a form such as:
Original sum 30000.00 at  12.5 percent for 20 years

Year Interest  Sum
----+-------+--------
  1  3750.00 33750.00
  2  4218.75 37968.75
  3  4746.09 42714.84
  4  5339.35 48054.19
  5  6006.77 54060.96
  6  6757.62 60818.58
  7  7602.32 68420.90
  8  8552.61 76973.51
  9  9621.68 86595.19
 10 10824.39 97419.58
Exercise 12331
Read a positive integer value, and compute the following sequence: If the number is even, halve it; if it's odd, multiply by 3 and add 1. Repeat this process until the value is 1, printing out each value. Finally print out how many of these operations you performed.
Typical output might be:
Inital value is 9
 Next value is  28
 Next value is  14
 Next value is   7
 Next value is  22
 Next value is  11
 Next value is  34
 Next value is  17
 Next value is  52
 Next value is  26
 Next value is  13
 Next value is  40
 Next value is  20
 Next value is  10
 Next value is   5
 Next value is  16
 Next value is   8
 Next value is   4
 Next value is   2
 Final value 1, number of steps 19
If the input value is less than 1, print a message containing the word
Error
and perform an
exit( 0 );
Exercise 12332
Write a program to count the vowels and letters in free text given as standard input. Read text a character at a time until you encounter end-of-data.
Then print out the number of occurrences of each of the vowels a, e, i, o and u in the text, the total number of letters, and each of the vowels as an integer percentage of the letter total.
Suggested output format is:
Numbers of characters:
        a   3 ; e   2 ; i   0 ; o   1 ; u   0 ; rest  17
        Percentages of total:
        a  13%; e   8%; i   0%; o   4%; u   0%; rest  73%
Read characters to end of data using a construct such as
char ch;
        while(
            ( ch = getchar() ) >= 0
        ) {
            /* ch is the next character */    ....
        }
to read characters one at a time using getchar() until a negative value is returned. Exercise 12333
Read a file of English text, and print it out one word per line, all punctuation and non-alpha characters being omitted.
For end-of-data, the program loop should read until "getchar" delivers a value <= 0. When typing input, end the data by typing the end-of-file character, usually control-D. When reading from a file, "getchar" will deliver a negative value when it encounters the end of the file.
Typical output might be
Read
a
file
of
English
text
and
print
it
out
one
etc.

Conditionals

This Chapter deals with the various methods that C can control the flow of logic in a program. Apart from slight syntactic variation they are similar to other languages.
As we have seen following logical operations exist in C:

   ==, !=, $\parallel$, &&.

One other operator is the unitary - it takes only one argument - not !.

These operators are used in conjunction with the following statements.

The if statement

The if statement has the same function as other languages. It has three basic forms:

  if  (expression)
     statement
...or:

  if  (expression)
     statement1
   else
     statement2
...or:

  if  (expression)
     statement1
   else if (expression)
     statement2
   else
     statement3
For example:-

  int x,y,w;
 
   main()
     {
 
     if (x>0)
      {
      z=w;
      ........
      }
    else
      {
      z=y;
      ........
      }
 
     }

The ? operator

The ? (ternary condition) operator is a more efficient form for expressing simple if statements. It has the following form:

  expression1 ? expression2:  expression3


It simply states:

if expression1 then expression2 else expression3

For example to assign the maximum of a and b to z:

  z = (a>b) ? a : b;

which is the same as:


  if (a>b)
     z = a;
   else
     z=b;

The switch statement

The C switch is similar to Pascal's case statement and it allows multiple choice of a selection of items at one level of a conditional where it is a far neater way of writing multiple if statements:

  switch (expression) {
     case item1:
       statement1;
       break;
     case item2:
       statement2;
       break;
       $\vdots$       $\vdots$     case itemn:
       statementn;
       break;
     default:
       statement;
       break;
    }
In each case the value of itemi must be a constant, variables are not allowed.
The break is needed if you want to terminate the switch after execution of one choice. Otherwise the next case would get evaluated. Note: This is unlike most other languages.
We can also have null statements by just including a ; or let the switch statement fall through by omitting any statements (see e.g. below).
The default case is optional and catches any other cases.


For example:-

          switch (letter)
    {
     case `A':
     case `E':
     case `I':
     case `O':
     case `U':
       numberofvowels++;
       break;
 
     case ` ':
       numberofspaces++;
       break;
 
     default:
       numberofconstants++;
       break;
    }

In the above example if the value of letter is `A', `E', `I', `O' or `U' then numberofvowels is incremented.
If the value of letter is ` ' then numberofspaces is incremented.
If none of these is true then the default condition is executed, that is numberofconstants is incremented.

Exercises

Exercise 12304
Write a program to read two characters, and print their value when interpreted as a 2-digit hexadecimal number. Accept upper case letters for values from 10 to 15.

Exercise 12305
Read an integer value. Assume it is the number of a month of the year; print out the name of that month.

Exercise 12306
Given as input three integers representing a date as day, month, year, print out the number day, month and year for the following day's date.
Typical input: 28 2 1992 Typical output: Date following 28:02:1992 is 29:02:1992

Exercise 12307
Write a program which reads two integer values. If the first is less than the second, print the message up. If the second is less than the first, print the message down If the numbers are equal, print the message equal If there is an error reading the data, print a message containing the word Error and perform exit( 0 );