Thursday, 25 September 2014

INTRODUCTION TO PROGRAMMING

18:02


If statements in C++

The ability to control the flow of your program, letting it make decisions on what code to execute, is valuable to the programmer. The if statement allows you to control if a program enters a section of code or not based on whether a given condition is true or false. One of the important functions of the if statement is that it allows the program to select an action based upon the user's input. For example, by using an if statement to check a user entered password, your program can decide whether a user is allowed access to the program.

Syntax


if ( TRUE )
  Execute the next statement

if ( 5 < 10 )
  cout<<"Five is now less than ten, that's a big surprise";
 

C++ if...else statement

 
An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

Syntax:

 
if(boolean_expression)
{
   // statement(s) will execute if the boolean expression is true
}
else
{
  // statement(s) will execute if the boolean expression is false
}
 
 
 
 

Example:

 
 
#include<iostream>
using namespace std;
 
int main()
{
string answer;
cout<<"Please enter the password: ";
cin>>answer;
cin.ignore();
if (answer == 'wrox') {
cout<<"You have successfully logged in";
}
else {
cout<<"Wrong Password";
}
cin.get();
}
 

Switch statement

 
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.
 

Syntax:

 
switch(expression){
    case constant-expression  :
       statement(s);
       break; //optional
    case constant-expression  :
       statement(s);
       break; //optional
  
    // you can have any number of case statements.
    default : //Optional
       statement(s);
}
 
 
 

Example:

#include <iostream>
using namespace std;
 
int main ()
{
   // local variable declaration:
   char grade = 'D';
 
   switch(grade)
   {
   case 'A' :
      cout << "Excellent!" << endl; 
      break;
   case 'B' :
   case 'C' :
      cout << "Well done" << endl;
      break;
   case 'D' :
      cout << "You passed" << endl;
      break;
   case 'F' :
      cout << "Better try again" << endl;
      break;
   default :
      cout << "Invalid grade" << endl;
   }
   cout << "Your grade is " << grade << endl;
 
   return 0;
}
 



Written by

We are Creative Blogger Theme Wavers which provides user friendly, effective and easy to use themes. Each support has free and providing HD support screen casting.

0 comments:

Post a Comment

 

© 2013 All in One. All rights resevered. Designed by Templateism

Back To Top