Programming 101: The “if”,”else”,”else if” statements
Here’s something that I thought I might as well start doing while I blog about programming.
Here’s a crash course to programming as presented by me!
Our first topic is one of the most fundamental aspects when it comes to doing anything complex with programming. The if, else if, and else statements. These allow for your to control the flow of your program based on your set parameters.
The layout of these is as follows:
//If this is true, do this
else if (boolean statement)
//If the if is false but the else if is true, do this
//If the above are both untrue, do this
A boolean statement is something that is either true or false. It can only be one of these two things. An example of a boolean statement in this context is (x == 2). This will be true if the variable x is equal to 2 but false if x is not equal to 2. This is a fairly general example and I’ll go more into these boolean statements in the future.
To use this style of control flow, you must have at least an “if” statement. “else if” and “else” statements are not needed to use an “if” statement but the an “if” is needed for them. You don’t need an “else” if you have an “else if” or visa versa.
As an example of what you can do with an “if” statement, we can take my “flashLight” “rotation” code that I have mentioned in my “Ghost Stories dev log”:
//The following code is the creation of TheChronocider.
int rot = 0;
//The rotation of the light is based on the cursor's position relative to the player
float posX = width/2 - mouseX;
float posY = height/2 - mouseY;
float angle = atan(posY/posX);
if(mouseX > width/2)
{
if(mouseY < height/2)
{
if(angle >= -PI/2 && angle <= -3*PI/8)
{
rot = 0;
}
else if(angle > -3*PI/8 && angle <= -PI/8)
{
rot = 1;
}
else
{
rot = 2;
}
}
else
{
if(angle <= PI/8 && angle >= 0)
{
rot = 2;
}
else if(angle > PI/8 && angle <= PI/4)
{
rot = 3;
}
else
{
rot = 4;
}
}
}
else
{
if(mouseY < height/2)
{
if(angle <= PI/8 && angle >= 0)
{
rot = 6;
}
else if(angle > PI/8 && angle <= PI/4)
{
rot = 7;
}
else
{
rot = 0;
}
}
else
{
if(angle >= -PI/2 && angle <= -3*PI/8)
{
rot = 4;
}
else if(angle > -3*PI/8 && angle <= -PI/8)
{
rot = 5;
}
else
{
rot = 6;
}
}
}
This is a great example of fairly basic use of the if, else, and else if, statements. Here I’ve used all 3 of the statements in sequence. This code is fairly basic in the grand scheme of this and yet it is responsible for one of the most important aspects of the game that I am making.
Understanding the basics of programming is important to creating a bigger project. If you can understand the complex parts but are stuck with the basics then you’re not going to create much.
Either way, I hope this has helped with your understanding of the fundamentals of programming. Feel free to message me with questions about this and other aspects. Happy programming!