Control statements are expressions used to control the execution and flow of the program based on the conditions provided in the statements. These structures are used to make a decision after assessing the variable. In this article, we’ll discuss control statements like the if statement, for and while loops with examples.
This control structure checks the expression provided in parenthesis is true or not. If true, the execution of the statements continues.
if (condition) statements ... ... end (endif can also be used)
The variables are Equal
It is similar to
if condition but when the test expression in
if condition fails, then statements in
else condition are executed.
if (condition) statements ... ... else statements ... ... end (endif can also be used)
The variables are Not Equal
When the first
if condition fails, we can use
elseif to supply another
if (condition) statements ... ... elseif (condition) statements ... ... else statements ... ... end (endif can also be used)
The variable is 50
It is a type of loop or sequence of statements executed repeatedly until exit condition is reached.
for var = expression body end (endfor can also be used)
Example 1 : Printing numbers from 1 to 5 :
1 2 3 4 5
Example 2 :
for loop with vectors :
10 20 30 40 50 60 70 80 90 100
Example 4 : Program to print the Fibonacci series up to 10 elements using
for loop :
1 1 2 3 5 8 13 21 34 55
while loop is another kind of loop iterated until a condition is satisfied. The testing expression is checked first before executing the body of the loop.
while (condition) body end (endwhile can also be used)
Example : Display numbers from 1 to 10 :
1 2 3 4 5 6 7 8 9 10
It is used to exit from a loop.
Example 1 : We will be making a row vector and will only modify the first 6 values using the
0 0 0 0 0 0 61 71 81 91
Example 2 :
break statement with
while loop :
1 is less then 5 2 is less then 5 3 is less then 5 4 is less then 5