Scilab Control statements and Loops
Control statements from scilab decides which statements can be
executed based on condition provided. Loops from scilab decides how many times
statements can be executed.There are many control statements and loops are available in scilab
for ex. if…else, if…elseif…elseif…else,for , while, select etc.
1) If …..else statement:
in if…else
statement logical condition like less than, greater than, equal to etc is given in if statement as well as else part
of it. The condition in if part is true then statements written in if part will
be executed otherwise statements from else part will be executed.
Syntax for if…else:
if
condition
//statement
else
//statement
end
Program:
x=input ("Enter age");
if (x>18)
disp("You are
allowed ");
else
disp("You are not
allowed")
end
2) If…elseif…..elseif…else statement:
If we have multiple conditions to check
then we can use if…elseif…elseif…..else scilab statement.
Syntax for
if…elseif...elseif..else:
if
condition
//statement
elseif condition
//statement
elseif condition
// statement
else
// statement
end
Program:
a=55
if(a>70)
disp("Distinction")
elseif(a<70 & a>60)
disp("first class")
elseif(a>=40 & a<60)
disp("second class")
else
disp("failed")
end
Output:
3) Select case statement:
If you want to choose one case out of
many then select case statement can be used. It is similar like lookup table.
Syntax for select:
select variable,
case value 1 then statement 1;
case value 2 then statement 2;
case value 3 then statement 3;
…….
case value n then
statement n;
end
Program:
x=input("enter
day from week");
select x
case 1 then disp("Sunday");
case 2 then disp("Monday");
case 3 then disp("Tuesday");
case 4 then disp("Wednesday");
case 5 then disp("Thursday");
case 6 then disp("Friday");
case 7 then disp("Saturday");
end
Output:
4) For loop:
for loop is used to execute
statements written in the body of loop recursively till meeting final condition
of loop. In for loop initial value, final value and increment needs to be
specified. If increment value is not specified, then 1 will be taken as default
value. You can use if…else, select , while inside for loop.
Syntax for for loop:
for
variable name=initial value: increment: final value
// statements
end
Program:
for i=0:10
if(i<5)
disp("less
than five");
else
disp("greater
than five")
end
end
Output:
5) While loop:
While loop will execute till condition
becomes true. Once condition is true loop will be terminated.
Syntax for while:
While
(condition)
//statements
end
Program:
c=input("enter number");
while(c<10)
disp(c);
c=c+1;
end
Output: