C++: Introduction to Switch constructs

Author: Ronald S. Holland
at
Total Application Works




To contact us



HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

© 2002 - 2016 All Rights Reserved Total Application Works


    Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)
    <html>
    <head>
    <title>C++: Switch Contructs </title>
    </head>
    <body>
    <a href="http://sumtotalz.com/TotalAppsWorks/CPP/CPP_switch_Construct.html">
    Switch construct </a>
    </table>
    </body>
    </html>
    Source code


Table of Contents

    Read Me First

    The CPP_Switch.zip file contains the following files:

    1. Switch.cpp - this file contains the main method code and is the entry point when the program is loaded into memory,
    2. Switch.dsp - Microsoft Developer Studio Project File.
    3. Switch.dsw - Microsoft Developer Studio Workspace File. Right click on this file and select Microsoft selector.
    4. Switch2.cpp - this file contains the main method code and is the entry point when the program is loaded into memory.
    5. Switch2.dsp - Microsoft Developer Studio Project File.
    6. Switch2.dsw - Microsoft Developer Studio Workspace File. Right click on this file and select Microsoft selector.
    7. CPP_switch_Construct.html - is the tutorial that describes how to build the Switch program

    Introduction

    This tutorial assumes that you have some prior programming experience. It is not intended to be a comprehensive discussion on c# or programming. As we ease into c#, we will briefly discuss the if control structure. c# as a programming language is widespread and can be found on nearly all computers. In the section on control structures, we will briefly describe control structures.

    What is c++?

    C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs and originally named C with Classes. It was originally developed as an enhancement to the C language. It was renamed C++ in 1983. In addition, one of the enhancements C++ introduced to the C language was object-oriented programming (OOP). As we ease into C++ programming, you'll learn The following list outlines the tutorials we will use to introduce C++. In the rest of this tutorial will describe:
    • What makes up a Program
    • How programs are used to solve Tasks
    • Exactly what is a C++ Program to a computer
    • Exactly what are program commands
    • What makes up a function
    • How do you get access to those prewritten/built-in functions

    Programs

    A program is a set of instructions used to solve a task. More specifically, these instructions tell a computer what to do. These set of instructions are like a recipe used to make a cake; a set of computer instructions are used to make a program. To make/create a program, we do the following:

    1. Source code is created when we enter a sequence of commands into a text editor, like notepad.
    2. When we process the raw source/code with a compiler, it results in object code.
    3. Once a program is in an object code format, a link editor processes the object code to form an executable program. These steps are outlined in the following table.

       
      
          +---------------------+
          |   text editor       | Step 1: Open an Text Editor 
          +-----------+---------+
                      |
                      V
          +---------------------+
          |   source code       | Step 2: Enter raw source into Text Editor
          +-----------+---------+
                      |
                      V
          +-----------+---------+
          |      compiler       | Step 3: compiler processes file created 
          +-----------+---------+         by Text Editor that contains 
                      |                   source code
                      V
          +-----------+---------+
          |      Link Editor    | Step 4: Object code created by compiler
          +-----------+---------+         is processed by Link Editor
                      |
                      V
          +-----------+---------+
          | executable program  | Step 5: Result of link editor
          +---------------------+
       
      Figure 1: Steps taken to create an executable program


      • Note: The steps shown above are typically combined in IDEs e.g., MicroSoft's 3rd-generation C++ language. a list of free IDEs follows.

        1- Eclipse CDT (C/C++ Development Tooling)
        2- Dev-C++ 5 (currently beta)
        3- Code::Blocks - The open source, cross platform, free C, C++ and Fortran IDE.
        4- NetBeans IDE - C and C++ Development
        5- Microsoft Visual Studio Express
        6- CodeLite - A Free, open source, cross platform C,C++,PHP and Node.js IDE
        7- Borland C++ - Borland C++ 5.5 + Sp1,Sp2.exe Application (.EXE)
        8- Turbo C - TurboC++ for Windows 7_v3.7.7.7major_release.zip Archive (.ZIP)
        15 Essential Compilers and IDEs for C/C++ Programmers)
        Figure 2: List of IDEs


    Control Structures

    Bohm and Jacopini demonstrated, in their Structured program theorem, that all programs could be written using just three control structures.

    • sequence structure
        Consider the following example:

        
        int a = 8 , b ;
        b = (5 + 2) * a  ;
        cout << b << endl ;
        
        Figure 3: Squence of statements structure
        If a code snippet consists of the above three statements, then the statements will execute in the order/sequence that they are listed. This is also known as an ordered execution of statements.
    • selection structure
        In a selection statement, one of a number of statements is executed depending on the state of the program. Consider the following example:

        
        int a, b = 0;
        
        cout << "Enter a number less than 10 and greater than 0." << endl ;
        cin >> a ;
        
        if( a > 5 )
           b = (5 + 2) * a  ;
        
        cout << "The value of b is " <<  b << endl ;
        
        Figure 4: selection structure
    • repetition structure
        A repetition structure is used when a set of instructions need to be executed more than once.

        
        int b = 0;
        
        for( int ii = 0 ; ii < 10 ; ii++ ) {
           b = (5 + 2) * ii  ;
           cout << "The value of b is " <<  b << endl ;
        }
        
        Figure 5: repetition structure
    Control Structures or constructs are described further in the next section.

    Control Structures or constructs

    What are Control Structures or constructs? The Control Structures constructs used in programming are:
    1. if - single selection structure
        This structure is used to determine whether a condition is true or false. If the condition evaluates to true, then some action is taken.
        
        if( condition is true ) {
           statement_1
           statement_2
           statement_3
           ...
           statement_n
        }
        
        Figure 6: if - single selection structure


    2. if/else - double selection structure
        This structure is used to determine whether a condition is true or false. If the condition evaluates to true, then some action is taken; otherwise, a different action is taken.
        
        if( condition is true ) {
           statement_1
           statement_2
           statement_3
           ...
           statement_n
        }
        else {
           statements
        }
        
        Figure 7: if/else - double selection structure


    3. switch - multiple selection structure
        This structure allows selection among multiple sections of code, depending on the value of an integral expression. It operates much like a nested if construct.
        
        switch( expression ) {
           case 1;
              do something ;
           case 2;
              do something ;
           case 3;
              do something ;
           ...
        
           default;
              do something ;
        }
        
        Figure 8: switch - multiple selection structure


    4. while
        In this construct, the condition is a boolean statement that is checked after the final } braces of the while statement executes. If the condition is true then the while statement executes again. If the condition is false, the statements inside the while construct do not execute again, due to the code branching out of the construct.
        while( condition  is true ) {
           statement_1
           statement_2
           statement_3
           ...
           statement_n
        }
        
        Figure 9: while loop structure


    5. do/while
        The do-while loop is similar to the while loop, except that the test condition occurs at the end of the loop. This construct guarantees that the body of the loop always executes at least one time. The format of the do-while loop is shown below.
        do {
           statement_1
           statement_2
           statement_3
           ...
           statement_n
        }
        while( condition is true )
        
        Figure 10: do-while loop structure


    6. for
        Executes the statements and loop-expression repeatedly until test becomes false. After the first pass, the loop counter is updated and then the test-condition is checked to determine whether it is true or false.
        for( initialization ; test ; update ) {
           statement_1
           statement_2
           statement_3
           ...
           statement_n
        }
        
        Figure 11: for loop structure


    For the remainder of this tutorial, we will describe the if contruct.

    The if selection construct

    How do we use the if selection construct? In the real world, we often use the if selection construct, during the day. A teacher must decide at the end of the semester who gets a passing grade. What criteria is used? The criteria used is: if a student's grade is greater than or equal to 60 they enter a passing grade.

    Flowchart
    
                   _
                  ( )               
                   |
                   -          +--------------+
                  /g\  true   |   Email      |
                 />= \________|              |
                 \60 /        |   'passed'   |
                  \ /         +--------------+
                   -                |
        false -->  |                |
                   |<---------------+
                   V
                   -
                  ( ) 
    
    
    
    
     
    
           Decision symbol    Processing symbol
                   +                  +
                   |                  |
                   V                  V
                   -           +--------------+
                  / \          |              |
                 /   \         |              |
                 \   /         |              |
                  \ /          +--------------+
                   -                 
    
    
     The Decision symbol is used when a decision 
         needs to be made or evaluated
    
     The Processing symbol is used when processing 
         a sequence of needs to be made
      
    Pseudocode
              if grade is greater than or equal to 60 
                 email "passed" to the student
    
    Figure 12: if construct

    Without a conditional statement such as if, programs would run practically same way every time. The if statements allow the flow of a program to be altered.

    The if/else selection structure

    In this section, we descibe the The if/else selection structure, in terms of the following:

    1. Pseudocode
    2. The conditional operator ? :, and
    3. nested ifs


    Pseudocode
     
    
       if a student's grade is greater than or equal to 60
           print "passed"
       else
           print "failed" 
    
    
    
      
       
                        _
                       ( )               
                        |
    +---------+         ^          +--------------+
    | print   | false  /g\ true    |   print      |
    |         |<----- />= \________|              |
    | "failed"|       \60 /        |   'passed'   |
    +---------+        \ /         +--------------+
         |              v                |
         |              |                |
         +------------->|<---------------+
                        V
                        _
                       ( ) 
                        -
    
    
      
       
              if (grade >= 60) 
                 cout << "Passed" << endl;
              else 
                 cout << "Failed" << endl;
      
    conditional operator ? :
       
    cout <<  (grade >= 60 ? "Passed" : "Failed" ) << endl;
    
       --- or  ----
    
    cout <<  grade >= 60 ? cout << "Passed\n" : cout << "Failed\n"  ;
      
    nested ifs
       
              if (grade >= 90) 
                 cout << "A" << endl;
              else if (grade >= 80) 
                 cout << "B" << endl;
              else if (grade >= 70) 
                 cout << "C" << endl;
              else if (grade >= 60) 
                 cout << "D" << endl;
              else  
                 cout << "F" << endl;
    
     
    Figure 13: nested if/else selection structure


    An example of a The if selection construct program will be depicted in the next section.

    The if selection construct program

    In the following table, we show the code for an if selection construct program.

     
    /** **************************************************************************
     * This program averages 4 test scores. The If_Construct.cpp:
     *  1- Obtains four numbers from the user;
     *  2- Calculates the average of those four numbers;
     *  3- Prints the average to the screen.
     ***************************************************************************/
    
    
    using System ;
    
    /** ***************************************************
     * _tmain() method defines the C# entry point for the 
     *  console application that is used when the program is 
     *  loaded into memory. 
     *
     ******************************************************/
       public static void main( String args[] )  {
    	int Score1, Score2, Score3, Score4 ;
    	double average;
    
    
    	for ( int ii = 0 ; ii < 4 ; ii++ 0  ) {
               Console.WriteLine( "Enter a test score and they will be averaged: " ) ;
    	   score + "ii+1" = Console.ReadLine() ;
    	}
    
    	average = (Score1 + Score2 + Score3 + Score4) / 4.0;
    
    	cout.precision(1);
    	cout.setf(ios::showpoint | ios::fixed);
    	Console.WriteLine( "Your average is " + average + "\n" ) ;
    	if (average == 100)
    	   Console.WriteLine( "Congratulations! You've achieved a perfect score!\n" ) ;
    
    	return 0;
    }
    
     
    Figure 14: Single selection structure

    The if/else nested selection construct program

    In this section, we will show the nested if in the table below.

     
    /** **************************************************************************
     * This program averages 4 test scores using a nested if construct. This 
     * program does the following:
     *  1- Obtains four numbers from the user;
     *  2- Calculates the average of those four numbers;
     *  3- Prints the average to the screen.
     *  4- Prints the grade to the screen.
     ***************************************************************************/
    
    
    /** ***************************************************
     * main() method defines the C# entry point for the 
     *  console application that is used when the program is 
     *  loaded into memory. 
     *
     ******************************************************/
       public static void main( String args[] )  {
    	int Score1, Score2, Score3, Score4 ;
    	float average;
    
    	cout << "Enter 4 test scores and they will be averaged: ";
    	cin >> Score1 >> Score2 >> Score3 >> Score4 ;
    
    	average = (Score1 + Score2 + Score3 + Score4) / 4.0;
    
    	cout.precision(1);
    	cout.setf(ios::showpoint | ios::fixed);
    
    	if (average == 100)
               cout << "Congratulations! You've achieved a perfect score!\n";
    	else if (average >= 90) {
               cout << "Your average is " << average << "\n" << endl;
               cout << "Your grade is "A" \n" << endl;
    	}
    	else if (average >= 80) {
               cout << "Your average is " << average << "\n" << endl;
               cout << "Your grade is "B" \n" << endl;
    	}
    	else if (average >= 70) {
               cout << "Your average is " << average << "\n" << endl;
               cout << "Your grade is "C" \n" << endl;
    	}
    	else if (average >= 60) {
               cout << "Your average is " << average << "\n" << endl;
               cout << "Your grade is "D" \n" << endl;
    	}
    	else if (average < 60) {
               cout << "Your average is " << average << endl;
               cout << "Your grade is \"F\" \n" << endl;
    	}
    
    	system("Pause") ;
    
    	return 0;
    }
    
     
    Figure 15: nested if/else selection structure

    The switch statement is unlike the if-statement. It requires that each case be constant. For example:

     
    switch (expression) {
       case value1:
          statements;
       break;
       case value2:
          statements;
       break;
       default:
          statements;
       break;
    }
     
    Figure 16: switch structure
    • where value1 and value2 are typically int values.
    • The value specified on a case must be a constant of type int or must be able to be promoted to int (in other words a byte, short, int, or char).
    • The value of the case statement must either be a expression that is able to be evaluated to a constant
      e.g., 3 + 2.
    • hint: The case statements should be arranged in desending order of probability of occuring.
    This constraint allows various optimizations in the lower-level intermediate representation. Switch speeds up certain parts of a program.

    The problem with switch statements is essentially that of duplication. Often you find the same switch statement scattered around a program in different places. If you add a new clause to the switch, you have to find all these switch statements and change them.

    Calculate the number of days in a month

    Suppose you want to calculate the number of days in a month using a nested if and a switch construct>.

     
    
    
    #include <iostream>
    #include <ctime>
    
    using namespace std;
    
    using std::cout;
    using std::cin;
    
       int month, numDays, year, day ;
    
       int main( )  {
         
             // current date/time based on current system
          time_t now = time(0);
    
          tm *ltm = localtime(&now);
    
          month = 1 + ltm->tm_mon ;
          year = ltm->tm_year ;
          day = 1 + ltm->tm_mday ;
    
       
    
          if( month == 1 || month == 3 || month == 5 || month == 7 ||
             month == 8 || month == 10 || month == 12 )  
        
             numDays = 31;
          else if( month == 4 || month == 6 || month == 9 || month == 11  )   
        
             numDays = 30;
    
          else if( month == 2 ) {
      
             if( ((year % 4 == 0) && !(year % 100 == 0))
                || (year % 400 == 0) )
    
                 numDays = 29;
             else
                numDays = 28;
          }
    
          cout<<"The current month is "  ;
    
          if (month ==1)
             cout<<"January";
          else if (month==2)
             cout<< "February";
          else if (month==3)
             cout<<"March";
          else if (month==4)
             cout<<"April";
          else if (month==5)
             cout<<"May";
          else if (month==6)
                 cout<<"June";
          else if (month==7)
             cout<<"July";
          else if (month==8)
             cout<<"August";
          else if (month==9)
             cout<<"September";
          else if (month==10)
             cout<<"October";
          else if (month==11)
             cout<<"November";
          else if (month==12)
             cout<<"December";
     
     
    
    #include <iostream>
    #include <ctime>
    
    using namespace std;
    
    using std::cout;
    using std::cin;
    
       int month, numDays, year, day ;
    
       int main( )  {
         
             // current date/time based on current system
          time_t now = time(0);
    
          tm *ltm = localtime(&now);
    
          month = 1 + ltm->tm_mon ;
          year = ltm->tm_year ;
          day = 1 + ltm->tm_mday ;
    
          switch (month) {
             case 1:
             case 3:
             case 5:
             case 7:
             case 8:
             case 10:
             case 12:
                numDays = 31;
             break;
    
             case 4:
             case 6:
             case 9:
             case 11:
                numDays = 30;
             break;
    
             case 2:
                if ( ((year % 4 == 0) && !(year % 100 == 0))
                   || (year % 400 == 0) )
                    numDays = 29;
                else
                   numDays = 28;
             break;
          } /*............. end of switch construct  */
          
    	  cout<<"The current month is ";
       
          switch (month) {
             case 1:
                cout<<"January";
             break;
             case 2:
                cout<< "February";
             break;
             case 3:
                cout<<"March";
             break;
             case 4:
                cout<<"April";
             case 5:
                cout<<"May";
             break;
             case 6:
                cout<<"June";
             break;
             case 7:
                cout<<"July";
             break;
             case 8:
                cout<<"August";
             break;
             case 9:
                cout<<"September";
             break;
             case 10:
                cout<<"October";
             break;
             case 11:
                cout<<"November";
             break;
             case 12:
                cout<<"December";
             break;
    	  }
           
          cout << "\nToday is day " << day  ; 
    	  
         cin.get() ; 
       }  /*............. end of main method  */
    
    
     
    Figure 17: if and switch construct example

    • where ltm->tm_mon will return a zero for the month of January.

    c++ data types



    Data types in C++
    Data Type Memory (ByteS) Minimum Value

    Maximum Value

    Bool 1 Logical Value T/F Logical Value T/F
    Char 1 -128 127
    Unsigned Char 1 0 255
    Short 2 -32768 32767
    Unsigned Short 2 0 65535
    int 2 -32768 32767
    unsigned int 2 0 65535
    Long 4 -2147483648 2147483647
    unsigned long 4 0 4294967295
    float 4 10-38 1038
    double 8 10-308 10308
    long double 10 10-4932 104932
    Figure 18: data types

    Definitions

    abstract data type

    AFXWIN

      This is a header for the Microsoft Foundation Classes C++ library. It must be included in all MFC applications.

    Ancestor

      An ancestor or forebear is a parent or (recursively) the parent of an ancestor (i.e., a grandparent, great-grandparent, great-great-grandparent, and so forth). Ancestor is "any person/class from whom one/class is descended. In law the person from whom an estate/class has been inherited."

    CFrameWnd

      The CFrameWnd class encapsulates the functionality of a Windows single document interface (SDI) frame window. A frame window is a window that frames an application.

    CWinApp

      The CWinApp class is the base class from which you derive a Windows application object. An application object provides member functions for initializing your application (and each instance of it) and for running the application.

    CStatic

      The CStatic class provides the functionality of a Windows static control. A static control is a control used to display text, to draw frames or lines separating other controls, or to display icons. A static control doesn't accept user input, but it can notify its parent of stylus taps if it's created with SS_NOTIFY style.

    DNA (Deoxyribonucleic acid)

      is a molecule that carries most of the genetic instructions used in the development, functioning and reproduction of all known living organisms and many viruses.

    event handling

    Holland's OOP Programming Design Model

        
                +--------------+
                |      Data    |<----+  
                +-------+------+     | 
                        ^            |
                        |----------->+
                        V            ^
                +-------+------+     |
                |   Top-down   |     | 
                |  Structured  |<----+
                |  programming |     |
                |  on Classes  |     | (step-wise)
                |  and methods |     | (refinement)
                +--------------+     | (as needed or as the) 
                        |            | (application ages)
                        +------------+ 
       
        

    IDE (Integrated development environment)

      is a software application that provides comprehensive facilities that allows you to develop software An IDE usually consists of a source code editor, build automation tools and a debugger.

    inheritance

      is the ability to create a class that derives properties from one or more base classes.

    initinstance

      Override InitInstance to initialize each new instance of your application running under Windows. Typically, you override InitInstance to construct your main window object and set the CWinThread::m_pMainWnd data member to point to that window.

    m_pMainWnd

      Holds a pointer to the applicationís main window.

    SS_CENTER

      Designates a simple rectangle and displays the given text centered in the rectangle. The text is formatted before it is displayed. Words that would extend past the end of a line are automatically wrapped to the beginning of the next centered line.

    Template

      is a unique class or pattern that can be used to build other software code.

    WS_BORDER

      Creates a window that has a border.

    WS_CHILD

      Creates a child window. Cannot be used with the WS_POPUP style.

    WS_VISIBLE

      Creates a window that is initially visible.






HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#


To contact us

© 2002 - 2016 All Rights Reserved Total Application Works