Sunday, July 31, 2011

Conditional Statements in C++

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgO6AYHJH2f5ZPUjr2MfbypO36qxwd3tJRGm12t4Qh3zdnxSFj-j2SK4QyuGQLcG1EclRZ9EVNSKlAes7Xz29Jd9De_dA-l6GTd7KKY7khrrWcMVvJje95CldTBOwe66x9fggc_FygkIf6U/s400/IfElse.bmp


There are techniques you can use to combine conditional statements when one of them cannot fully implement the desired behavior.
We will continue with our traffic light analogy.
 
Nesting Conditions
A condition can be created inside of another to write a more effective statement. This is referred to as nesting conditions. Almost any condition can be part of another and multiple conditions can be included inside of others.
As we have learned, different conditional statements are applied in specific circumstances. In some situations, they are interchangeable or one can be applied just like another, which becomes a matter of choice. Statements can be combined to render a better result with each playing an appropriate role.
To continue with our ergonomic program, imagine that you would really like the user to sit down and your program would continue only once she answers that she is sitting down, you can use the do…while statement to wait for the user to sit down; but as the do…while is checking the condition, you can insert an if statement to enforce your request. Here is an example of how you can do it:
#include <iostream>
using namespace std;

int main()
{
 char SittingDown;
 
 do {
  cout << "Are you sitting down now(y/n)? ";
  cin >> SittingDown;
  
  if( SittingDown != 'y' )
   cout << "\nCould you please sit down for the next exercise?\n";
 }
 while( !(SittingDown == 'y') );
 
 cout << "\nWonderful!!!\n";
 return 0;
}
Here is an example of running the program:
Are you sitting down now(y/n)? n
Could you please sit down for the next exercise?

Are you sitting down now(y/n)? n
Could you please sit down for the next exercise?

Are you sitting down now(y/n)? y

Wonderful!!!

Press any key to continue...
Continue Reading.....
via [functionx]

0 comments:

Post a Comment