Is this valid code?
if (0 <= tower_height <= 23);
If so, how will it be executed?
If statements need to have a body like so:
if (statement)
{
// Body
}
or
if (statement)
// Body
Note that in the second case, the body is strictly one line long, while the first case allows you to use as many lines inside the curly brackets as you wish.
Your statement is incorrect too. 0 <= tower_height
and tower_height <= 23
would both be correct by themselves, but 0 <= tower_height <= 23
will result in a compilation error. If you would like to test the tower_height
variable against multiple values, you should you the and (&&) operator: 0 <= tower_height && tower_height <= 23
. This tells the program to only execute the body if tower_height
is both above or equal to 0 and below or equal to 23.
An if statement is NOT followed by a semicolon (i.e., ;
). If you wanna check whether tower_height
is greater than or equal to 0
AND less than or equal to 23
. Then you probably need to write something like
if (tower_height >= 0 && tower_height <= 23)
{
// do something
}
Notice that you must repeat tower_height
as it's regarded as a separate condition.
All the code in the body of this if statement is executed if and only if both conditions are evaluated to true.
If an if statement doesn't have opening and closing curly braces, then only a single statement (specifically the one right after the statement) is executed when the condition is evaluated to true.
For example,
if (true)
// executed when the condition is evaluated to true
printf("hello from inside of the if statement!\n");
// executed anyway
printf("hello from OUTSIDE of the if statement!\n");
I ended up using a do... while
loop. The condition I used settled on was:
(tower_height < 0 || tower_height > 23)
You should have written
if(tower_height>=0 && tower_height<=23)
{
//body
}
but if u write
if(statement);
{
//body
}
this is a logical error .
The body of if statement will run for sure irrespective of the if statement. your code can also be interpreted as:
if(statement)
{
}
//body