Flow of Control in C++
Programs to only store data but also manipulate data in terms of rearranging and modifying data.
To perform their manipulative tasks, programs need tools for performing repetitive actions and for decision making.
C++ provide such tools by providing control statements that control the flow a program.
1. If/Else Statement
These statements follow the underlying syntax in C++
if(expression) { statements }
if statement test a condition with the help of test expression.
If the expression evaluates to true, following statement or block is executed.
Otherwise (if the expression evaluates to false) the statements are ignored.
Example,
if (var < 10) { cout << "variable is less than 10"; }
If the value of the variable var is less than 10, the above statement will be printed, else it will be ignored.
Now we will see the syntax of if/else statements
if(expression) statement1; else statement2;
If the expression evaluated to true, than statement1 is executed.
Otherwise statement2 is executed in this case.
2. The for loop
See the syntax followed by for loop below
for (initialization expression(s); test-expression; update expression(s)) body-of-the-loop;
Let's see this with an example
#include <iostream> using namespace std; int main() { int i; for(i = 1; i <= 10; i++) cout<<i<<endl; return 0; }
The above program prints first 10 natural numbers.
The variable 'i' is initialized with value 1 (initialization expression).
As long as the value of 'i' is less than or equal to 10 (test expression) the loop prints the value of 'i' on a separate line.
And at the end of each expression the value of 'i' is incremented by 1 (update expression)
3. The while loop
First let's start this section by seeing the syntax of the while loop.
while (expression) body-of-the-loop;
The loop body iterates while the expression is true.
When the expression becomes false, the program control passes to the line after the loop body code.
The best way to understand any concept is with examples. Let's see an example of this
#include <iostream> using namespace std; //factorial int main() { int i,num,fact = 1; cout<<"Enter a number: "; cin>>num; i = num; while(num) { fact *= num; num--; } cout<<"The factorial of "<<i<<" is "<<fact; return 0; }
As long as the num is true (non-zero) the loop-body iterates i.e. fact is multiplied with num and the result is stored back in fact followed by decrementing num.
There can be many variations of the loop statements and jump statements, like nested loops and do-while loops.
This is a basic covered article which is a good place to start, and will write an advanced topics article soon.