The problem that you seem to have with this code is understanding the pathway of the if / else construction and the way to define it. There is a "formal" way to define it, but I think that first time it is easier with an example: So here goes:
#include <iostream>
int main()
{
int x=10; // Define x to be 10.
if (x>2) // This is obviously True
{
std::cout<<" This statement is called"<<std::endl;
std::cout<<" This is also called"<<std::endl;
}
else
{
std::cout<<" ****** I am NOT printed " <<std::endl;
x=20002; // this does not get done
std::cout<<" ***** I am ALSO NOT printed "<<std::endl;
}
}
I have given a complete program, you can run and see that only the first part is done, but not the second.
If you see there are two pair of brackets { }
. After an if statement, or an else, or many other C++ statements, e.g. for(...), a pair of brackets can be written, and this defines the scope of the branch or statement.
In the case above, if you change x to be say 1. Then recompile and run, you will set that the statements after the else are carried out but not any of the statements in the first { }. You can add extra statements to either section but only one will be carried out.
There are two additional points, firstly, IF you write many C++ statements, e.g. if etc, AND do not follow …