Sunday, October 26, 2014

Stuck on if and else statement - help would be appreciated.

Greetings Lyndsee.


It's a bit difficult to know where to start, because your code seems very wrong and I'm not certain exactly what it's supposed to do.


So here's a quick tutorial on "if" statements in general.


The code inside the parenthesis that follow the "if" or "else if" (the round brackets) must be an expression that evaluates to either true or false. The code inside the following braces (curly brackets) will be executed if the expression is true. Code inside braces following an "else" will be executed if the expression is false.


Some examples.



if( x == 0)
{
// Code here will be executed if x is equal to zero.
}

if(number < 10)
{
// Code in here will be executed if number is less than 10.
}
else
{
// Code in here will be executed if number is not less than 10.
}


if(letters == "Hello")
{
// Code here will be executed if the string letters is "Hello".
}
else if(letters == "Goodbye")
{
// Code here will be executed if letters is "Goodbye".
}
else
{
// Code here will be executed if letters is neither "Hello" nor "Goodbye".
}

Sometimes, the expression can be a single variable, provided that variable is of type bool (a variable that contains the value of true or false, named after the mathematician George Boole).



// Define a boolean variable.
bool lessThanTen = (number < 10);

// Use it in an "if".
if(lessThanTen)
{
// Code here will be executed if number is less than 10.
}

If the code to go inside the braces is just a single line, then the braces can be left out.



if(number < 10)
DoSomething(); // This single line will be executed if number is less than 10.
else
DoSomethingElse(); // This single line will be executed if number is not less than 10.



Does that help?


No comments:

Post a Comment