- 1

How do I use if statements and where to put them?

If statements

26th Jan 2018, 9:31 PM
</Royal>
</Royal> - avatar
8 Respostas
+ 2
if you go back to your course and read carefully you'll know exactly how to use them and when to use 'em because it's really explained well!
27th Jan 2018, 9:05 PM
madeny
madeny - avatar
+ 1
int n; cin >> n; if (n == 3) cout << "You entered three" else cout << "You did not enter three" If statements are probably the most used statements in C++ and for good reason. They're used to check for invalid input, conflicting states, conditional input ("Do you want to continue? (y/n)"), wether a number is a multiple of another number and much much more. For example, when I tap the post button, presumably an if statement will check if the input area is empty. If it is it will warn me, if it is not it will post the comment. (and no, this app probably wasn't written in C++, I was just using it as an example).
26th Jan 2018, 10:04 PM
Vlad Serbu
Vlad Serbu - avatar
+ 1
/* You can copy and paste this code into the code playground. It will run just fine because this top section is marked as a comment The output depends on the input. If age<=0 then it will output error If 1<=age<=20 then it will output too young If 21<=age<=79 then it will output You can participate! If 80<=age<=120 then it will output too old If 121<=age then it will output Shouldn’t you be dead? Try writing your own code with if statements! */ #include <iostream> using namespace std; int main() { int age; cin >> age; if (age >= 80){ if (age > 120){ cout << "Shouldn't you be dead?" << endl; } else{ cout << "Too old." << endl; } } else if (age < 80 && age > 20){ cout << "You can participate!" << endl; } else if (age <= 20 && age >0){ cout << "Too young." << endl; } else{ cout << "Error" << endl; } return 0; }
27th Jan 2018, 6:37 PM
Parker king
Parker king - avatar
0
You use if statements in general if your tying to compare something such as if C == 8 then do some action.
26th Jan 2018, 9:43 PM
Ole113
Ole113 - avatar
0
Like Vlad Serbu said. If statements allow you to check if certain conditions are true. The application of if statements are endless.
27th Jan 2018, 2:31 AM
Parker king
Parker king - avatar
0
can you guys write examples to see?
27th Jan 2018, 12:32 PM
</Royal>
</Royal> - avatar
- 1
if (condition) { do_something(); } else if (condition) { ... } else { ... }
27th Jan 2018, 7:26 AM
Timon Paßlick
- 1
if (3>2) { cout << "This is true."; } else { cout << "This is false."; }
27th Jan 2018, 1:35 PM
Timon Paßlick