- 1
How do I use if statements and where to put them?
If statements
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!
+ 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).
+ 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;
}
0
You use if statements in general if your tying to compare something such as if C == 8 then do some action.
0
Like Vlad Serbu said. If statements allow you to check if certain conditions are true. The application of if statements are endless.
0
can you guys write examples to see?
- 1
if (condition)
{
do_something();
}
else if (condition)
{
...
}
else
{
...
}
- 1
if (3>2)
{
cout << "This is true.";
}
else
{
cout << "This is false.";
}