|
If-Then-Else
|
|
Now we will look into how to get our programs to compare values. A conditional statement checks to see if the conditions you are looking for are met or not, if they are they will execute a certain block of code, if not they will keep on. Here is an example:
|
#include <iostream>
using namespace std;
int main(){
int a;
int b;
cout << "Enter a value for a: ";
cin >> a;
cout << "Enter a value for b: ";
cin >> b;
if (a > b){
cout << a << "Is greater than" << b;
} else if(a < b){
cout << a << "Is less than" << b;
} else {
cout << a << "Is equal to" << b;
}
}
|
|
Here we see what is known as an if-then-else statemnt. I basically reads "If a is greater than b execute this code" if it is not greater it will move on, if it is true it will execute what ever you place in between its curly brackets and continue ignoring any line that begins with else after it. If it is false, the program will check the next condition "else if(a < b){" which basically reads "If the condition above is false and a is less than b execute this code". Finally, if that one proves false as well the program will go to the final "else" which has no conditions so will always be executed if the above conditions were false. Here are a list of the condition you can chck for:
|
== : equality, must use two equal signs
< : less than
> : greater than
<=: less than or equal to
>= : greater than or equal to
!= : not equal
|
|
You can also check for more than one condition with a single if by using && (for and) and || (for or). For example:
|
if( a == 1 && b != 2) // will return true if a has a value of 1 and b does not have a value of 2
if( a == 1 || b != 2) // will return true if a has a value of 1 or if b does not equal 2
|
|
Switch Case
|
|
The switch case works much like a lot of if-then-else statements put together. It takes one value and compares it against many others. Here is an examle:
|
#include <iostream>
using namespace std;
int main(){
int a;
cout << "What time of day is it?\n";
cout << "1) Morning\n";
cout << "2) Afternoon\n";
cout << "3) Evening\n";
cout << "Enter a choice: ";
cin >> a;
switch (a){
case 1:
cout << "Good Morning!";
break;
case 2:
cout << "Good Afternoon!";
break;
case 3:
cout << "Good Evening!";
break;
default:
cout << "Not a valid entry...";
break;
}
}
|
|
Notice how after each case, there is a colon not a semicolon. The last command in each case must be "break;" if not it will continue to execute any code following it. "break;" can be used to break out of any conditional statement or loop. "default" is included incase the user eneters an invalid entry, when ever the variable doesnt match any case, the default block is executed.
|
|
|