Your Federal Quarterly Tax Payments are due April 15th Get Help Now >>

if–else with multiple possibilities by asafwewe


if–else with multiple possibilities

More Info
									                Assignment TWO remarks                                                                           This lecture
    The assignment deadline is 19:30:00 on Thu 13 March 2008. This is                     The control statements switch and case.
    next week.
    Remember if the program does not compile it gets ZERO marks.
                                                                                          The use of typedef.

    The initial set-up gives you a file with a name of the form                            struct and an example from <ctime>.
    cs08xyz a2.cpp with cs08xyz replaced by your actual login id..
                                                                                          Examples of creating your own class.
    This is the file that you send by email.
    To submit attach the C++ file to an email to                                           Reserved words.                                                               The classes vector and string.
    Submission should not be regarged as complete until you get an
    acknowledgement by email. You should read the acknowledgement
    in case errors are reported which may lead to ZERO marks.

                                                                          – p. 1/24                                                                             – p. 2/24

         if–else with multiple possibilities                                                            The switch statement
When there are multiple possibilities to handle an if–else construction               The switch statement makes the previous example a bit neater.
can be messy as in                                                                    void explain_grade(char c)
void explain_grade2(char c)                                                           {
{                                                                                       switch(c)
  if(c==’A’)cout << "70--100" << endl;                                                  {
    else if(c==’B’)cout << "60---69" << endl;                                             case ’A’: cout << "70--100" << endl;   break;
      else if(c==’C’)cout << "50---59" << endl;                                           case ’B’: cout << "60---69" << endl;   break;
        else if(c==’D’)cout << "40---49" << endl;                                         case ’C’: cout << "50---59" << endl;   break;
          else if(c==’E’)cout << "35---39" << endl;                                       case ’D’: cout << "40---49" << endl;   break;
            else if(c==’F’)cout << " 0---34" << endl;                                     case ’E’: cout << "35---39" << endl;   break;
              else cout << "Invalid letter" << endl;                                      case ’F’: cout << " 0---34" << endl;   break;
}                                                                                         default: cout << "Invalid letter" <<   endl;

                                                                                      The program jumps to the case letter which agrees with c. The following
                                                                                      break statement is needed so that the statement ends at that point.

                                                                          – p. 3/24                                                                             – p. 4/24
                 The typedef command                                                            struct and composite types
The typedef command is a way of giving another name (usually shorter               You can have several related quantities as part of one type declared using
and easier to understand) for a type. As examples,                                 struct, which C++ inherits from C, and using class which leads to
typedef double(*func_type)(double);               // defines func_type             object orientated programming. For example, with the header <ctime>
typedef unsigned int uint;                        // defines uint                  you can have the following.
typedef unsigned char uchar;                      // defines uchar                 #include <ctime>
                                                                                   // .. other lines
In the assignment you have one of the following for method.                          time_t p;
                                                                                     struct tm s;
typedef   double(*method)(double, double, int, func_type);                           time(&p);
typedef   double(*method)(double, double, func_type, int);                           s=*gmtime(&p);
typedef   double(*method)(func_type, double, double, int);                           cout << "sizeof(tm)=" << sizeof(tm) << endl;
                                                                                     cout << s.tm_year << " " << s.tm_mon << " " << s.tm_mday << " ";
typedef   double(*method)(func_type, int, double, double);                           cout << s.tm_hour << " " << s.tm_min << " " << s.tm_sec << endl;
typedef   double(*method)(int, func_type, double, double);
typedef   double(*method)(int, double, double, func_type);

                                                                       – p. 5/24                                                                                – p. 6/24

                       The struct            tm                                                Limitations with 32-bit numbers
The type contains the following.                                                   As previously mentioned, on our PCs and int type requires 4 bytes which
struct tm {                                                                        is 32-bits. This causes problems when large numbers are computed as
    int tm_sec;          //   seconds                                              int overflow is possible.
    int tm_min;          //   minutes                                              Type time t similarly needs 32-bits and this limits the time range. This
                                                                                   can be investigated with the following statements
    int tm_hour;         //   hours
                                                                                     time_t p;
    int tm_mday;         //   day of the month (1--31)                               p=0;
    int tm_mon;          //   month (0--11)                                          cout << ctime(&p);
    int tm_year;         //   year (since 1900)                                      p=INT_MAX;
                                                                                     cout << ctime(&p);
    int tm_wday;         //   day of the week (0--6, 0=Sun)
                                                                                   which generates
    int tm_yday;         //   day in the year (0--365)
                                                                                   Thu Jan 1 01:00:00 1970
    int tm_isdst;        //   daylight saving time                                 Tue Jan 19 03:14:07 2038
};                                                                                 Only 68 years can be represented. 64-bit representations of the time
Specific implementations may have additional entries.                               gives a much greater range.

                                                                       – p. 7/24                                                                                – p. 8/24
               Creating your own struct                                                         Creating your own class – examples
Related to the assignment you create a struct which collects together a                The following are examples. string is mentioned later.
function pointer and the range on which it is defined by having.                        class student{
                                                                                                                                 class foit_student : student{
typedef double(*func_type)(double);                                                                                              public:
                                                                                          string id;
                                                                                                                                    int ms0311;
                                                                                          string login;
struct myfun{                                                                                                                       int ma0329;
                                                                                          string l_name;
                                                                                          string f_name;                            int ma0371;
   double a;                                                                                                                        int ma0990;
                                                                                          string dob;
   double b;                                                                           };                                        };
   func_type f;
};                                                                                     With classes you can also add member functions and operators.
You can then have functions where the type myfun is used as in
double mid_point_rule(struct myfun g, int n);

                                                                           – p. 9/24                                                                                    – p. 10/24

               The size of composite types                                                                  Reserved words in C++
In the previous example, student has 5 members. foit student                           Avoid the following names for your variables, arrays and functions.
inherit the 5 members of student and have the 4 members indicated. With                Reserved words in both C and C++.
  cout << "sizeof(student)=" << sizeof(student) << endl;                               auto     const      double   float     int        short     struct    unsigned
  cout << "sizeof(foit_student)=" << sizeof(foit_student) << endl;                     break    continue   else     for       long       signed    switch    void
                                                                                       case     default    enum     goto      register   sizeof    typedef   volatile
which generates                                                                        char     do         extern   if        return     static    union     while
sizeof(student)=20                                                                     Reserved words in C++ only.
sizeof(foit_student)=36                                                                asm           dynamic_cast    namespace     reinterpret_cast     try
                                                                                       bool          explicit        new           static_cast          typeid
Each of the 5 items in student needs 4 bytes.
                                                                                       catch         false           operator      template             typename
Each of the 4 int items in foit student needs 4 bytes.                                 class         friend          private       this                 using
                                                                                       const_cast    inline          public        throw                virtual
                                                                                       delete        mutable         protected     true                 wchar_t
                                                                                       Additional reserved words in C++.
                                                                                       and        bitand   compl     not_eq      or_eq    xor_eq
                                                                                       and_eq     bitor    not       or          xor

                                                                          – p. 11/24                                                                                    – p. 12/24
     Example: using reserved words in the wrong place                                                             The classes vector and string
This will not compile because of the use of the reserved words class and do in the wrong
                                                                                                        We consider now briefly how you can make use of two classes known as
#include <iostream>
                                                                                                        vector and string which are part of standard C++.
using namespace std;                                                                                    The header statements needed.

int main()                                                                                              #include <vector>              // .. to use vectors
  char class[]="MA1234";
                                                                                                        #include <string>              // .. to use strings
  for(int do=1; do<=3; do++)cout << class << endl;
  cout << endl;                                                                                         #include <cstring>             // .. to use functions involving
  return 0;
                                                                                                                                       // .. C-style strings
The error messages include
                                                                                                        The vector type is like arrays with extra features.
... error C2236: unexpected ’class’ ’$S25’
... error C2143: syntax error : missing ’;’ before ’do’                                                 The string type is like the C-style strings with extra features. (C-style
Renaming class and do to valid names will correct the errors.                                           strings are null terminated character arrays.)

                                                                                           – p. 13/24                                                                                  – p. 14/24

 Creating and using vectors — a small example                                                                      The declaration of vector types
Consider the following statements which uses a vector.                                                  In the example we had
  int n=20;
                                                                                                          int n=20;                           // .. const is not needed
  vector<double> v(n);
                                                                                                          vector<double> v(n);
  // .. set the entries of v                                                                            This declares the vector with name v of type double with n entries. When
  int i;
                                                                                                        this syntax is used all n entries are set to 0.
  for(i=0; i<n; i++)v[i]=i+1;
                                                                                                        The syntax of the vector declaration in general can be any of the following.
  // compute the mean                                                                                     vector <data-type> vector_name;        // for an empty vector
  double sumv=0;                                                                                          vector <data-type> vector_name(n);     // size n, all entries are 0
  for(i=0; i<n; i++) sumv=sumv+v[i];                                                                      vector <data-type> vector_name(n,val); // size n, all entries=val
  double meanv=sumv/n;                                                                                  Here data-type can be any existing type such as double, int, char or
// .. more lines
                                                                                                        indeed any user defined type.
To do the same with an array the only change needed would be to have
  const int n=20;
  double v[n];

                                                                                           – p. 15/24                                                                                  – p. 16/24
   The declaration of vector types continued                                                                    Extra features with vectors
As an example of declaring vectors we can have the following.                            Various operators such as = have been set-up to have meaning for the type vector. We can
                                                                                         have the following.
  vector<double> x, y(10), z(100, 3.14);                                                 #include <iostream>                              x=y;
                                                                                         #include <vector>                                cout << "after: "
  vector<int> v, w(1000, -1);
                                                                                         #include <cmath>                                       << x.size() << endl;
  vector<char> c(20, ’a’);                                                               using namespace std;                             print(x);
Here x is declared but is empty. It can be re-sized later in the program.                                                                 return 0;
                                                                                         void print(vector<double> x);                 }
y has 10 double entries with all entries set to 0.
z has 100 double entries with all entries set to 3.14.                                   int main()                                               void print(vector<double> x)
                                                                                         {                                                        {
Similar comments apply to the empty vector v, the vector w which has                       int i, m=3;                                              unsigned int i;
1000 int entries all set to -1 and the vector c which contains the                         vector<double> x, y(m);                                  for(i=0; i<x.size(); i++)
                                                                                           for(i=0; i<m; i++)                                         cout << i << ": "
20 character entries all set to the character ’a’.                                           y[i]=exp(0.5*i);                                              << x[i] << endl;
                                                                                           cout << "before: "                                     }
                                                                                                << x.size() << endl;

                                                                            – p. 17/24                                                                                                                            – p. 18/24

  Extra features with vectors – output from the program                                              Some of the vector member functions
The program just given creates the following.                                            In the following suppose that v is a vector (of any type). The following are some of the
                                                                                         operators and functions available with vectors.
before: 0
                                                                                          =                       In a statement v1=v2; the vector v1 becomes a copy of v2.
after: 3                                                                                  v.resize(137)           Changes the size of v to 137. Existing entries in positions 0, 1, · · · , 136 are kept.
0: 1                                                                                      v.size()                Gives the size of v.

1: 1.64872                                                                                v.front(), v.back()     Respectively give the first entry, i.e. v[0], and the last entry.
                                                                                          v.begin(), v.end()      Iterators. Can be used with a function sort() from <algorithm>.
2: 2.71828
                                                                                          v[i]                    Gives the index i entry. There is no checking done to see if i is in range.
Observe that with the type vector you can have                                                   Gives the index i entry if i is in range and otherwise ‘throw an exception’ which can be
                                                                                                                  detected so that a program can finish properly instead of crashing.
  vector<double> x, y(m);
                                                                                          v.pop_back()            Removes the last entry of the vector. The size decreases by 1.
  // ..statements
                                                                                          v.push_back(q)          Increases the size of v by 1 with q put as the new last entry.
  x=y;                                                                                    v.clear()               Deletes all the entries of v. The size becomes 0.

You cannot do this with arrays.                                                           v.capacity()            Gives the size of an internal array concerned with the space already available to store all
                                                                                                                  the entries.
Also observe that since a vector knows its size we do not need to pass
                                                                                          v.reserve(n)            This indicates that space for n entries is required. Using this may increase the efficiency of
the size as an argument to the function print().                                                                  a program.

                                                                            – p. 19/24                                                                                                                            – p. 20/24
                 C-strings and character arrays                                                                                      Declaring and using string variables
In C++ you can use both C-style strings, which C++ inherits from the C-language, and the                                    As has already been stated quantities of type string are classes and this particular class
class called string which has been designed as an “easier” alternative in many situations                                   has been set-up so that several operators such as = and + have meaning and there are
for processing text.                                                                                                        many member functions. We consider some of these here.
You will still need C-style strings if you use command line parameters and in naming files for                               The following commands declare and assign variables s1, s2, s3, s4 and full_address.
reading and writing. Consider the following.
#include <iostream>
                                                                                                                            #include <iostream>                                           string s3,s4;
#include <fstream>
                                                                                                                            #include <string>                                             s3="UB8 3PH";
#include <string>
                                                                                                                            using namespace std;                                          s4.assign("U.K.");
using namespace std;
                                                                                                                                                                                          string full_address=
int main(int argc, char *argv[])
                                                                                                                            int main()                                                           s1+", "+s2+","+s3+", "+s4;
                                                                                                                            {                                                             cout << full_address << endl;
  string cs="bearings.dat";
                                                                                                                              string s1("Brunel University");                             return 0;
                                                                                                                              string s2="Uxbridge, Middlesex";                        }
  ifstream inp(cs.c_str());   // .. c_str() returns a C-style string
  // .. statements
                                                                                                                            This creates the following output.
  return 0;
                                                                                                                            Brunel University, Uxbridge, Middlesex, UB8 3PH, U.K.

                                                                                                               – p. 21/24                                                                                                                            – p. 22/24

           Some member functions and operators                                                                                    Some member functions and operators continued
In the following s, s1 and s2, are string variables. Some of the member functions                                            s.assign()          Use as, e.g.

correspond to those for the vector class.                                                                                                        s2.assign(s1, 3, 4);
                                                                                                                                                 In this version of assign() the variable s2 obtains the length 4 and involves the 4 characters
 s.size()                               Use as, e.g. int m=s.size(); as with vectors.
                                                                                                                                                 s1[3], s1[4], s1[5] and s1[6]. assign() can hence extract sub-strings from strings.
 s.clear(), s.resize(), s.capacity(),   All as in the case of vectors.
                                                                                                                             s.find()            Use as, e.g.
                                                                                                                                                 int i1=s.find(s1), i2=s.find(s2, 4);
 s[i]                                   s[i] gets the ith character of the string. If the length is m then index                                 Here i1 is the position of string s1 in s starting from the start of the string and i2 is the position
                                        values 0, 1, · · · , m-1 are valid.                                                                      of string s2 in s starting from s[4]. If the search fails then the return value is a large integer as                                Gives the index i entry if i is in range and otherwise ‘throws an excep-                                 specified by the value string::npos. You need to check if the return value is this to determine
                                        tion’.                                                                                                   whether or not the search has succeeded or failed.
 s.c str()                              Use as, e.g.                                                                         s.replace()         Use as, e.g.
                                        char cs[1024]; strcpy(cs,s1.c str());                                                                    s.replace(k, m, s1); s.replace(k, m, "New", 3);
                                        strcpy() is part of <cstring>. The character array needs to be large                                     In the first case this replaces the m characters s[k], · · · , s[k+m-1] by the characters of s1. In the
                                        enough to store all the entries.                                                                         second case this replaces the m characters s[k], · · · , s[k+m-1] by the 3 characters the C-style
 ==                                     Use as s1==s2. If s1 and s2 are the same this evaluates to true.                                         string "New".

 <, <=, >, >=,                          Use as, e.g. s1<s2. This is true if s1 is in some “approximate” alphabet-           Using just the above you can quite easily write programs which do some routine editing
                                        ical sense less than s2.                                                            operations on text files.

                                                                                                               – p. 23/24                                                                                                                            – p. 24/24

To top