CyberiaPC.com Main Page




Learning C++

Setting Conditional Statements

Conditional statements play a very important role in any application.  As described in the VB Tutorial, If statements allow a program to actually make decisions based on user input.  This in turn makes the program more productive and increases its overall level of interactivity with the user.

The good news is that it is extremely simple to set up If statements.  They might look confusing at first, however, as long as you follow the logic line by line it will all become clear.

Here is the general syntax for a basic If statement:

     if (condition)
     {
          do this
     }

Very simple, right?  Now here is a sample If statement:

     if (Password == 10)
     {
          cout << "Accepted!" << endl;
     }

Now the following complete program will add an else statement and an else if statement.  Else if statements define a different condition for the same expression.  If the initial If statement is false then the compiler will check the Else if statement if available.  An Else statement does not define a condition.  It is invoked only when none of the previous conditions in the If block are true.

     #include<iostream.h>
     
     
     void main()
     {
     
     int Password=0;

          cout << "Enter Password" << endl;
          cin >> Password;


          if (Password == 10)
          {
               cout << "Accepted!" << endl;
          }
          else if (Password == 20)
          {
              cout << "You are using the Old Password!" << endl;
          }
          else
          {
               cout << "Password Not Recognized!" << endl;
          }
          
     }

If either 10 or 20 is entered for the Password variable, then the user gets a specified message.  If the user enters anything else, then the message in the else block is invoked.

One final note, if any of the statements above (If, Else If, Else) contains only one line of code (as is the case with the above example) then he curly braces ({,}) are not required.

If..Else pitfalls, exercises and sample code available in C++ CoderCheck it out!

{Go Back To C++ Lessons Page}