In this C++ blog post I am going to look at For loops, If / Else and Else If statements.
For Loops

The for loop layout is made up of three parts:
for (initialisation; conditional; iteration) { CODE-TO-CARRY_OUT }
- Initialisation Statement
Carried out before the first loop is run and initialises the variables used in the for loop. In my example I am using an integer variable called i and initialising it to the value 0.
- Conditional Expression
The conditional expression is checked on each iteration of the loop. If the expression is true then the loop continues. If the expression is false the loop stops.
- Iteration Statement
At the end of each loop is the iteration statement, which is how C++ moves the loop on to the next iteration. This runs at the end of the loop iteration.
An error in the conditional expression (e.g. setting it to i<-5;) or in the iteration statement (e.g. setting it to i–) could cause an infinite loop.
On each iteration of the loop C++ runs the code in between the curly braces.
for (int i=0; i<5; i++){ CODE-TO-CARRY-OUT }
If / Else Statements

If, Else If and Else use boolean logic to check if a statement is true or false. If the statement is true then the code following the statement is run, if the statement is false then the code is not run.
if (STATEMENT){ CODE TO RUN IF STATEMENT TRUE }
Rather than having multiple if statements, else if statements can be used instead.
if (STATEMENT 1){ CODE TO RUN IF STATEMENT 1 TRUE } else if (STATEMENT 2){ CODE TO RUN IF STATEMENT 2 TRUE }
When using if and else if statements I recommend having an else statement at the end to catch conditions that have not been programmed for.
if (STATEMENT 1){ CODE TO RUN IF STATEMENT 1 TRUE } else if (STATEMENT 2){ CODE TO RUN IF STATEMENT 2 TRUE } else { THIS CODE WILL RUN IF STATEMENT 1 and STATEMENT 2 are false }
For example, in the below code the user is asked to enter Y or N. An OR gate (||) has been used so that capital and lower case versions of Y or N will result in either statement 1 or statement 2 being true. However, what if the user enters an A, B, c, d etc… or a symbol? This would be captured by the else statement and return a line telling the user that the program has not understood what was pressed.
#include <iostream> using namespace std; int main() { cout<<"Choose Y or N"<<endl; char response = 'y'; cin >> response; if (response == 'y' ||response == 'Y') { cout<<"You pressed Y"<<endl; } else if (response == 'n' ||response == 'N') { cout<<"You Pressed N"<<endl; } else { cout<<"I am unsure what you pressed"<<endl; } }
If, Else and Else If statements are good however C++ also has a nicer way of dealing with conditional statements could switch statements which I am hoping to look at with my next blog post.
One thought on “Learning C++: For Loops, If, Else If and Else Statements”
Comments are closed.