244
edits
No edit summary |
No edit summary |
||
| Line 233: | Line 233: | ||
Perhaps that last part was slightly untrue. | Perhaps that last part was slightly untrue. | ||
==if statements and advanced operators== | |||
A crucial element of any programming language is the ability to test whether something meets a defined condition. The most basic way of doing this in C++ is by using the '''if''' statement. Here's an example of how if and else work | |||
#include <iostream> | |||
int main() | |||
{ | |||
int a = 4; | |||
if(a == 5) | |||
{ | |||
cout << "a is 5." << endl; | |||
} | |||
else if(a == 4) | |||
{ | |||
cout << "a is 4" << endl; | |||
} | |||
else | |||
{ | |||
cout << "a does not equal 4 or 5." << endl; | |||
} | |||
return(0); | |||
} | |||
If is 5, the program will return "a is 5.", if it is 4, the program will return "a is 4". If it is neither 5 nor 4, the program will return "a does not equal 4 or 5." | |||
You can use an infinite number of '''else if''' statements, linking ifs together, but it is probably bad programming practice to use too many. | |||
Also note that if you only have one line of code following an if, if else or else statement (the line which will be executed when the condition is satisfied), you ''may'' omit the chain brackets for the statement. | |||
if(a < 10) | |||
cout << "a is less than 10." << endl; | |||
If a is less than 10, the program will return "a is less than 10." | |||
* '''==''' is used to see if two variables are equal. It will work for all data types except string, for which there are other functions dealt with later. | |||
* '''!=''' not equal to | |||
* '''<=''' less than or equal to | |||
* '''>=''' greater than or equal to | |||
* '''<''' less than | |||
* '''>''' greater than | |||
[[Category:Helpdesk]] | [[Category:Helpdesk]] | ||
edits