Sunday, December 30, 2012

Getting started with ncurses programs

I will be explaining some interesting programs using ncurses library from this post onward. This will actually give you an interesting experience since ncurses programming is a little different from the traditional structured or object oriented programming.

ncurses is a programming library that provides an API which allows the programmer to write text-base user interfaces in a terminal-independent manner. It is a toolkit for developing GUI like applications that runs under a terminal emulator. This provides manipulation of the terminal accurately such as clearing the screen, getting a single character from the user, positioning text at a certain screen location, changing colors etc. Though ncurses is a UNIX library, it can also be ported to other platforms including DOS. 

I will explain you how to work with ncurses programs, compile and run them. Before starting just type the below code in a new text editor, compile as shown below. If you are having problems, then you have to make sure that you are having the ncurses library installed in your linux OS.

open a new turminal and type type vi ncurse1.cpp  to open a text editor.
then, type the below shown code

#include<ncurses.h>
int main()
{
initscr();
move(15,25);
printw("First Ncurses Program\n");
getch();
endwin();
return 0;
}

press Esc key and then type :wq to save the program and quit the text editor. then type the below code to compile the program

g++ -lncurses -oncurse1 ncurse1.cpp

If your program compiled correctly, you should not get any error messages. If the compiler complains about any syntax errors, then you have to fix them one by one. but of you get a message as shown in the below image, 









then, your OS may not have the ncurses library installed yet. Which means you cannot compile and run ncurses library in your existing system . But don't worry, as same as you install some software in windows platform, you can also download and install any missing software in linux via the terminal. 

How to install ncurses library in linux?

As same as you need administrative privileges in windows (or in most of the OSs) , you must be in the root directory to install or uninstall software in Linux. Note that being in root directory can be only done by a user with administrative privileges because to be in root, you must know the password that you provided during the installation of the OS. OK, let's start with it.

  1. open a new terminal ( if you don't have one opened yet)
  2. type su - and then press Enter key
  3. type your password (the one that you gave during the OS installation) and press Enter key
  4. type yum install ncurses-devel ncurses and press Enter key to install ncurses library .but make sure that you are connected to internet since the library will be automatically downloaded from the internet and install.
  5. your installation process will automatically start as shown in the below image
     6. once it asks for the conformation to download, enter y and then press Enter key as shown below


    7. once it asks for the conformation to install, enter and then press Enter key as shown below


8. If the installation is successful, then the terminal will display the completed message as shown below. then you are ready to work with ncurses programs.



to come out of the root directory, type exit and pres Enter. 
If you had problems in executing the ncurse1.cpp program earlier, I think  now you can run it smoothly. 

If you follow the earlier instructions to compile your program and run it, you will observe the below output.


to exit from the program and get back to the terminal, press any key from the keyboard.

If you are a beginner for ncurses, you may feel little odd with these codes. So, let me explain you why we used each code and how it works as a whole.
  • In order to use the libary, it is necessay to have certain types and variables defined. Therefore, the programmer must have a line in top of the program source as,
            #include<ncurses.h>
  • In linking with ncurses you need to have -lncurses in your LDFLAGS or on the terminal. This is what you mentioned -lncurses when you compile the program before mentioning the name of the program file and so.
  • inside the main method, you can see initscr()  method is called. This is done done initialize the curses library. In order to use the screen package, the routines must know about trminal characteristics and the space for curscr and stdscr must be allocated. These function initscr() does both these things 
  • Once the screen windows have been allocated, you can set them up for your program. here, what I need is to move the curser to a preferred location in the screen and print the message. move (x,y) method is called to do that task. two of those parameters say the x and y coordinates where we actually want the curser to move.
  • I think the task of printw()  method is similar to cout  that is to print something on the screen. As we have mentioned a simple message to print on screen, we have to wrap that within double quotation marks.
  • \n  at the end of the string message is similar to endl  which we need to go to a new line
  • Once you run an ncurses program, you will see the output on in the running terminal itself but in a special screen. Did you think how we are going to exit from that screen? (by pressing the close button in the right  side upper corner? ... No, since it will close the terminal also). getch() is the method that we are using for that. It says, if the user enters a key while the screen is running (get character) , then ready to exit.
  • In order to clean up after the ncurses routines, the routine endwin() is provided. It restores tty modes to what they were when initscr()  was first called and moves the cursor down to the lower-left corner. Thus, anytime after the call to initscr(), endwin() should be called before exiting. 
I'll discuss more interesting programs in ncurses in the future posts.



Friday, December 28, 2012

Building a very simple calculator program in C++ console using switch statements

Assume that I want the user to enter two numbers and an operator out of + - * and / to perform a certain calculation  in a c++ console program.

As a control structure, you may tend to use if-else blocks but you can do the same task more efficiently if you used switch statements.

you also need to check for invalid inputs and let the user to use your calculator to do any number of times until he explicitly requests to quit the program. 

To let the use do any number of calculations, you have to think of some way to iterate your task until the user quits. A loop definitely. Let's use a while loop since it's simple. We can't use a for loop this time because you don't know how many calculations your user may do.

Observe the following source code and follow the comments for clarification.

#include<iostream>
using namespace std;

int main()
{
char operator_symbol,decision;  //operator_symbol to hold the calculation symbol
                                                 //decision will hold the user's decision to continue the loop 
float num1,num2,answer=0; //num1 and num2 holds the user entered numbers 
decision='y';                         //initially, the decision is assigned as yes

       while(decision=='y')
{
        cout<<"Enter first number , Operator, second number :"; //display the order that user should 
                                                                                        //input the numbers and the operator
        cin>>num1>>operator_symbol>>num2;              //get them for variables

switch(operator_symbol)                                //switch compares this variable
{
case '+':answer=num1+num2;                        //if the operator is + , then add
break;                                                             //go to the end of switch block

case '-':answer=num1-num2;                          //if the operator is - , then substract
break;                                                             //go to the end of switch block
case '*':answer=num1*num2;                         //if the operator is * , then multiply
break;                                                              //go to the end of switch block

case '/':answer=num1/num2;                           //if the operator is / , then divide
break;                                                              //go to the end of switch block

default:cout<<"Wrong operator! Please retry"<<endl; // if user enters any other symbol
goto abc;                                                                     // go to line labeled abc
}
                cout<<"Answer= "<<answer<<endl;         //display the Answer
                abc:cout<<"Do another calculation(y/n):";//ask for confirmation
                cin>>decision;                                          //take it as the decision

                if(decision=='n')                                        //if entered n, then break the loop
                break;                   

                else                                                           //if not, continue the loop
                continue;

}

cout<<"Thank you. Good buy!"<<endl;              //before exiting, display this message
return 0;                                                                 //return an integer and end the program

}

Now see the below screenshot which shows how the program responds during run time.

















I hope it was a good practice for you to have hands on experience on switch, if-else, while loop, break, continue and goto statements all in one such program.  Just try to make the requirements hard and improve your calculator little by little.

More examples on if-else statements in C++

In my previous post I gave a clear idea about control structures and their usage in C++. In this post I thought to explain some better examples on these control structures.

our target 1:-
Let the user enter a character out of o,b,y, g and display Ammonia for o , Carbon Monoxide for b, Hydrogen for y, oxygen for g. If the user enters any other character other than the given set of characters  display a proper error message. Finally display a good buy message. Also accepts the letters that user enters both in uppercase and lowercase. e.g:- display Ammonia for both o and O.

You may decide that you must use conditional statements to achieve this simple task. Let's see which of them can  be used to give the best solution

using if-else statements

#include<iostream>
using namespace std;
int main()
{
char ch;                                                                              //declare a variable to get user input

cout<<"Input the first letter of the colour of the gas:"; //display message to let the user input
cin>>ch;                                                                             //get the user input to the ch variable

if(ch=='o' ||ch=='O')                                                          //if it is o or O 
cout<<"Ammonia"<<endl;                                              //display Ammonia

if(ch=='b' || ch=='B')                                                          //if it is b or B 
cout<<"Carbon Monoxide"<<endl;                                //display Carbon Monoxide

if(ch=='y' || ch=='Y')                                                          //if it is y or Y
cout<<"Hydrogen"<<endl;                                              //display Hydrogen

if(ch=='g' || ch=='G')                                                         //if it is g or G
cout<<"Oxygen"<<endl;                                                 //display Oxygen

else
cout<<"Invalid character entered,please try again"<<endl;  //else display error message

cout<<"Glad to be of service!"<<endl;                                   //display good buy message

return 0;
}

using if-elseif blocks

#include<iostream>
using namespace std;
int main()
{
char ch;                                                                              //declare a variable to get user input

cout<<"Input the first letter of the colour of the gas:"; //display message to let the user input
cin>>ch;                                                                             //get the user input to the ch variable

if(ch=='o' ||ch=='O')                                                          //if it is o or O 
cout<<"Ammonia"<<endl;                                              //display Ammonia

else if(ch=='b' || ch=='B')                                                  //else if it is b or B 
cout<<"Carbon Monoxide"<<endl;                                //display Carbon Monoxide

else if(ch=='y' || ch=='Y')                                                  //else if it is y or Y
cout<<"Hydrogen"<<endl;                                              //display Hydrogen

else if(ch=='g' || ch=='G')                                                 //else if it is g or G
cout<<"Oxygen"<<endl;                                                 //display Oxygen

else
cout<<"Invalid character entered,please try again"<<endl;  //else display error message

cout<<"Glad to be of service!"<<endl;                                   //display good buy message

return 0;
}

you can examine that both of the above programs work in the same way.

our target 2:-

  1. let the user enter three values for a , b and c
  2. calculate x1 and x2 using the following formulas 


x1=(-b+sqrt(pow(b,2)-4.0*a*c))/(2.0*a)
x2=(-b-sqrt(pow(b,2)-4.0*a*c))/(2.0*a)

   3. If x1 and x2 has logical errors in calculations such as divide by zero or equal to zero, display proper      error messages before calculations (before the running program shows you error messages, you handle them)

    4.Finally, display the value of a, b,c along with the values obtained for x1 and x2

First of all, you have to notice that both the formulas need functions that are available in cmath thus you need to include cmath library to the program.
Next point on how you are going to handle the logical errors. Actually when seeing the formulas you can see that two things may go wrong in calculation

  1. If the denominator becomes zero, then there would be a division by zero error ( since the answer is infinity)
  2. if the value inside the square root (in the numerator) will be a negative number, then the answer will not be a number
to handle the division by zero issue, you can clearly see that the value of a is the only thing to focus. If a is zero, then the denominator will be zero for sure. So, simply check whether the user enters a zero value for a or not.

Now we'll see how the numerator can be a value that is not a number. of course, if b^2 - 4ac results in a negative value, then the square root of it wont be a number. So, if we can check that b^2 < 4ac, then we can  track the error. 

observe the below code.



#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double a,b,c,x1,x2;

cout<<"Enter a value for a :";
cin>>a;

cout<<"Enter a value for b :";
cin>>b;

cout<<"Enter a value for c :";
cin>>c;

x1=(-b+sqrt(pow(b,2)-4.0*a*c))/(2.0*a);
x2=(-b-sqrt(pow(b,2)-4.0*a*c))/(2.0*a);

cout<<"If a= "<<a<<" ,b= "<<b<<" ,c= "<<c<<" then x1= "<<x1<<"and x2= "<<x2<<endl;

return 0;

}

note that in the above code, i have not checked for the logical errors that we have discussed above. I just wanted to show you how the program reacts when they are unhanded by the programmer. Now, we know if we enter a=10, b=5 and c=35, the program should give an error because b^2 is less than 4ac so that it wont be a number. Check the running terminal as shown below










Note that the program is giving -nan  for both x1and x2. -nan means the reslut is not a number.

Now if i enter a=0 and any values for other two, then also my program should show error results like shown below.






Here note that x2 has resulted in -inf   which means the answer is infinity since there is a division by zero.
Finally observe the output if the user enters proper inputs for a, b and c






As you have already understood we should not expect the users of a program to enter correct inputs as always thus we have to do error handling as much as possible. Do you think every user understands the real meaning of -nan and -inf ? No, they are not supposed to understand them either but it's our responsibility to display messages to users in a way that they can understand.

Now see the below code and observe how I have added a couple of code with if-else blocks to handle this simple issue.


#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double a,b,c,x1,x2;

cout<<"Enter a value for a :";
cin>>a;

cout<<"Enter a value for b :";
cin>>b;

cout<<"Enter a value for c :";
cin>>c;

if((2*a)==0)
cout<<"Error! The answer is infinite, Please Retry!"<<endl;

else if((b*b)<(4.0*a*c))
cout<<"Error! The answer is not a Number, Please Try again"<<endl;

else
{
x1=(-b+sqrt(pow(b,2)-4.0*a*c))/(2.0*a);
x2=(-b-sqrt(pow(b,2)-4.0*a*c))/(2.0*a);


cout<<"If a= "<<a<<" ,b= "<<b<<" ,c= "<<c<<" then x1= "<<x1<<"and x2= "<<x2<<endl;
}
return 0;

}
















I'll be posting you a more practical example on multiple selective structure -switch statements in my next blog.











Wednesday, December 26, 2012

Control Structures in C++

We have gone through some of the C++ programs with example code in the couple of posts before. Actually speaking, we cannot even think of programming without knowing about control structures because a program is usually not limited to a linear sequence of instructions. During its process it may split in to two parts, repeat code or take decisions. 

It's just as simple as living life. Do you think life keeps on flowing without a need to make decisions, repeat things /activities, continuing doing something or going back with memory and doing something depending on a decision we make. These are what a program definitely does to achieve some task.

For these purpose, C++ provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

With the introduction of control structures, we have to know about some new concepts. The compound statements or block. 

A block is a group of statements which are seperated by semicolons (;) like all C++ statements, but grouped together in a block enclosed in curly braces {};

e.g :- 
{
    int a;
    int b;

    return a+b;
}

most of the control structures that we will see in this post require a generic statement as part of its syntax. A statement can be either a simple statement ( a simple instruction ending with a semicolon) or a compound statement ( several instructions grouped in a block) , like the one just described. In the case that we want the statement to be a simple statement, we do not need to enclose it in braces {}. But in the case that we want the statement to be a compound statement it must be enclosed between curly braces {}. forming a block.

A list of Conditional structures in C++

  • if and else
  • Iteration structures (loops) - while, for, do-while
  • Jump statements -break, continue, goto, exit,
  • Selective structure -switch
I'll explain these conditional statements one by one with necessary code snippets. In future posts, I can explain you some meaningful programs to show the actual use of these.

if and else

if (condition)
{
   // your statement goes here
}

Where condition is the expression that is being evaluated. If this condition is true, statement is  executed. If it is false, statement is ignored and the program continues right after this conditional structure. See the below code block for clarification.

if ( marks > 100)
{
  cout<< "Invalid mark entered, please try again";
}

marks =(marks/100) *10;
cout<<"You have scored "<<marks <<" out of ten";

note that, since the above code snippet, we have only one line of code to be executed if the condition is true, so you can even forget about the curly braces that I have explicitly mentioned above to show the code block clearly. even you had the curly braces after any conditional structure, the first line of code (statement) will definitely be executed. But this will not happen if you have more than one statement to be executed after any conditional statement. See the below code.

  1. if ( marks > 100)
  2.   cout<< "Invalid mark entered";
  3.   cout<< "Please reenter the mark again";
  4. marks =(marks/100) *10;
  5. cout<<"You have scored "<<marks <<" out of ten";

in the above code, if the condition is true, only the first message will be printed on terminal but line number 3 will simply be ignored as a line to be executed if the condition is true since we have not told the program to execute both line-2 and line-3 if the condition is true. to do so, simply wrap the statements using curly braces.

if ( marks > 100)
{
  cout<< "Invalid mark entered";
  cout<< "Please reenter the mark again";
}

Now, think what if we need to do something if the condition is true we have to do something and meanwhile we have to do something else if it is false. we have two options. One is to use an if condition and mention all the statements in one block if the condition is true. Same as that, put all the rest of the code (code to be executed if the condition is false) outside the conditional code block. 

if ( marks > 100)
{
  cout<< "Invalid mark entered";
  cout<< "Please reenter the mark again";
}

marks =(marks/100) *10;
cout<<"You have scored "<<marks <<" out of ten";


But, what if you have to check the mark's validity from the if condition and then decide the scored grade of the mark to display. Your option are,

use another if condition

if ( marks > 100)
{
  cout<< "Invalid mark entered";
  cout<< "Please reenter the mark again";
}

if ( marks > 85 )
{
  cout<< "Grade A";
}

marks =(marks/100) *10;
cout<<"You have scored "<<marks <<" out of ten";

you may note some logical issues in the above code like even though the mark is invalid, the program will output the mark out of ten but for the moment ignore it because I'm just focusing on the way the code blocks work there.

use else if condition

if ( marks > 100)
{
  cout<< "Invalid mark entered";
  cout<< "Please reenter the mark again";
}

else if( marks > 85 )
{
  cout<< "Grade A";
}
  marks =(marks/100) *10;
  cout<<"You have scored "<<marks <<" out of ten";

 the if else  structures can be concatenated with the intention of verifying a range of values. The following example shows its use of telling if the value is in a range, how to make decisions and make proper output.

if ( marks > 100)
{
  cout<< "Invalid mark entered";
  cout<< "Please reenter the mark again";
}

else 
{
  if(marks > 85)
 {
   cout<< "Grade A";
 }

  if(marks > 65 && marks <= 85 )
 {
   cout<< "Grade B";
 }

  if(marks > 45 && marks <= 65 )
 {
   cout<< "Grade C";
 }

 else
 {
   cout<< "Fail";
 }
  marks =(marks/100) *10;
  cout<<"You have scored "<<marks <<" out of ten";
}

So, I think the if-else concept is clear for you now. Now, let's move to the next control structure.

Iteration structures (loops)

while loop

The format of writing a while loop is,

while(expression)
{
 statement

While loop's  functionality is simply to repeat statement while the condition set in expression is true. For an example, we are going to make a program to count numbers from one to 100. 

OK, my first option is having  variable called sum and assigning 1+2+3+4+...+100 to sum and then print the value.

And my second option is to have a variable, assign 1 to it and have a while loop to increase its value one by one meanwhile adding it to sum to get the output (sum of 1 to 100)

So, what will you prefer? I'm sure that you won't go to the first option because you wont type from 1 to hundred in the source code if you have a simpler option by using a loop. see the code below.

int number,sum;
number=1;
sum=0;


while(number<=100)

{
  sum=sum+number;
  number++;
}

cout<<"The count of 1 to 100 is "<<sum<<endl;

whatever the code written inside the while block will be executed repeatedly until the condition of while becomes false. once it becomes false, the while loop will no longer be executed.

do-while loop

do  
{
  statement
}
while (condition)

above is the format of a do-while loop. It simply says to do something until some condition is true. Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, examine the following code.

int number,sum;
number=1;
sum=0;


do

{
  sum=sum+number;
  number++;
}
 while(number<=100);

cout<<"The count of 1 to 100 is "<<sum<<endl;

Both the above shown example for while loop and do-while loop work same. In do while loops, first it executes the statements in the block and then checks for the condition but in while loops, first the condition is being checked before executing the code block.


The major difference between while loop and do while loop is while loop executes 0 to more times but do-while loop executes 1 to more times. even though the condition is false, in do-while the block executes at least once because it says "first do and then check!"


for loop


The format of writing a for loop is ,


for(initialization ; condition ; increase or decrease)
{
  statement;
}

the main function of a for loop is to repeat statement while condition remains true, like the while loop. But in addition, the for loop provides specific locations to contain an initialization statement and an increase/ decrease statement. So this loop is specially designed to perform a repetitive action with a counter which is initialized on each iteration.

you may see its format bit new since its different than while and do-while. Following step will show you how it really works.

  1. initialization is executed. Mostly it is an initial value assigned to a counter variable and this is executed only once.
  2. condition is checked. If it is true, then loop continues ( statement will be executed) else, the loop ends and statement is skipped.
  3. statement  is executed. As you already know, it can be a single statement ( if so, you don't need the curly braces to mark the block) or a block of statements (you must use the curly braces).
  4. Finally, whatever is specified in the increase/decrease field is executed and the loop gets back to step 2.
I'll show you how the above shown example of while and do-while could be achieved via the for loop.

int number,sum;
sum=0;


for(int number=1 ; number <=100 ; number ++)

{
  sum=sum+number;
}

cout<<"The count of 1 to 100 is "<<sum<<endl;


Also note that the initialization and increase fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written . Observe the below shown lines


int number=1;

for( ; number <=100 ; number ++)

Above line is just as same as shown in the example above if you are using a variable in the for loop is already declared and initialized. you can also write as below


int number=1;

for( ; number <=100 ; )

{

  sum=sum+number;
  number++;

}

Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in a for loop , like in initialization, for example. The comma operator (,) is an expression separator, it serves to separate more than one expression where only one is generally expected. Examine the below shown code where we wanted to initialize more than one variable in our loop.

for( n=0 , i=100 ; n!=i ; n++ , i--)
{
   //statments
}

Jump statements 

The break statement

Using break statement we can leave a loop even if the condition for its end is not fulfilled. It can be used to end  an infinite loop or to force it to end before its natural end. For an example, observe the below code.

//purpose :- I want to print numbers starting from 1 until i meet the first number divisible by 11.

#include<iostream>
using namespace std;

int main()
{
        int num=1;

        while(true)                            //to make the condition always true until we explicitly quit the loop
        {
                if(num/11 == 1)            //if the number is divisible by 11
                {
                 break;                         //go out of the loop
                }

                else
                {
                cout<<num<<endl;     // if not, print
                }
        num++;                               //increase num by 1
        }
        return 0;
}

Output of the running program is shown as below.













The continue statement

The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the following iteration. Note how the same example shown in break works with the continue with a little alteration.


//purpose :- I want to print all the numbers starting from 1 to 20 but not 11.

#include<iostream>
using namespace std;

int main()
{
        int num=0;

        while(num<20)                  
        {
                num++;
                if(num%11 == 0)            //if the number is divisible by 11
                {
                 continue;                       //stop the current execution of loop but go back
                }

                else
                {
                cout<<num<<endl;     // if not, print
                }
                              
        }
        return 0;
}


Since I have told the program to stop the current execution of the loop if it meet a number divisible by 11 in between 1 and 11, the program does not print 11 but print all the other numbers from 1 to 20. See the output of the program as below.



















The goto statement

goto allows to make an absolute jump to another point in the program. We should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations.

It's just a simple concept as you say to one of your friend to go to some location if she/ he wants to buy something. If you say someone to go to somewhere, you must state them 'Where to go?' as well. Which means go to needs some destination point.

The destination point is identified by a label , which is used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:)

Actually, this instruction has no concrete use in structures or object oriented programming aside from those that we see in low-level programming.


#include<iostream>
using namespace std;

int main()
{
        int num=0;

        while(num<=20)                  
        {
                if(num%11 == 0)     //if the number is divisible by 11
                {
                 goto a ;                   //do not execute any statement but execute from the label a
                }

                else
                {
                cout<<num<<endl;   // if not, print
                }
                
              a : num++;                  //the statement labeled as a
        }
        return 0;
}


















you can see that the above program gives you the same results that we got from the continue example as well.

The exit function 

exit is a function defined in the cstdlib library which is used to turminate the current program with a specific exit code. It's method signature is,

void exit (int exitcode);

the exitcode is used by some operating systems and may be used by calling programs. By convention, an exitcode of 0 means that the program finished normally and any other value means that some error or unexpected results happened.

Selective structure -switch

The syntax of the switch statement may be a bit unfamiliar to you. Its objective is to check several possible constant values for an expression. Something similar to what we did at the beginning of this section with the concatenation of several if and else if instructions. Its form is the following:
switch (expression){        case constant1:
            group of statements 1;            break;

         case constant2:            group of statements 2;            break;           .           .           .        default:
          default group of statements
}


Once you know how the switch statements work, it'll be easy for you to work with it. 

switch evaluates expression and checks if it is equivalent to constant1 , if it is so, it then executes group of statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure.


If expression was not equal to constant1 it will be checked against constant1 . If it is equal to this, it will execute group of statements 2 until a break keyword is found, and then will jump to the end of the switch selective structure.

Finally, if the value of expression did not match any of the previously specified constants (you can include as many case labels as values you want to check), the program will execute the statements included after the default:label, if it exists (since it is optional).

Note that a switch structure can be represented by if-else blocks as well. Observe the following code to see such example.



switch exampleif-else equivalent
switch (x) 
{
  case 1:
    cout << "x is 1";
    break;
  case 2:
    cout << "x is 2";
    break;
  default:
    cout << "value of x unknown";
  }
if (x == 1) 
{
  cout << "x is 1";
  }
else if (x == 2) {
  cout << "x is 2";
  }
else {
  cout << "value of x unknown";
  }




The switch statement is a bit odd within the C++ language because it uses labels instead of blocks. This forces us to put break statements after the group of statements that we want to be executed for a specific condition. Otherwise the remainder statements including those corresponding to other labels will also be executed until the end of the switch selective block or a break statement is reached.

For example, if we did not include a break statement after the first group for case one, the program will not automatically jump to the end of the switch selective block and it would continue executing the rest of statements until it reaches either a break instruction or the end of the switch selective block. This makes it unnecessary to include curly braces { } surrounding the statements for each of the cases, and it can also be useful to execute the same block of instructions for different possible values for the expression being evaluated. For example: 

switch ( number )
{
   case 1:
   case 2:
   case 3:
      cout << "number is 1, 2 or 3" ;
      break;

   default :
      cout <<"number is not 1, 2 or 3" ;

}

Also remember that switch can only be used to compare an expression against constants and therefore we cannot put variables as labels or ranges because they are not valid C++ constants.

But don't worry, you can use if-else blocks to check values that are not constants.

If you want more meaningful little programs to clarify theses control structures, please go through the next post as well.