Reference Link: Spoken Tutorial - Scilab Iteration
To understand and implement iteration in Scilab, specifically focusing on for loops and while loops for repetitive tasks.
1. For Loop:
The for loop is used to repeat a block of code for a specific number of times.
The loop iterates over a sequence of numbers or an array.
Syntax:
for variable = start_value : step_value : end_value
// statements to be executed
end
Example:
for i = 1 : 2 : 10
disp(i)
end
This loop starts at 1, increments by 2, and runs until 10.
2. While Loop:
The while loop repeats as long as the condition is true.
Syntax:
while condition
// statements to be executed
end
Example:
i = 1;
while i <= 5
disp(i)
i = i + 1;
end
This loop continues as long as i is less than or equal to 5.
3. Break and Continue:
break: Exits the loop immediately.
continue: Skips the current iteration and moves to the next one.
Example with break and continue:
for i = 1 : 5
if i == 3 then
continue; // skip 3
end
if i == 4 then
break; // stop loop when i is 4
end
disp(i)
end
4. Nested Loops:
Scilab allows nesting of loops, i.e., placing one loop inside another.
Example:
for i = 1 : 3
for j = 1 : 2
disp([i, j])
end
end
This loops through all combinations of i and j values.
Initialize a variable to store the sum (e.g., sum = 0).
Use a for or while loop to iterate through numbers (e.g., from 1 to N).
For each iteration, add the current number to the sum.
After the loop ends, display the sum.
Code Example:
sum = 0;
for i = 1 : 5
sum = sum + i;
end
disp(sum)
This will sum the numbers 1 to 5.
For Loops and While Loops are essential for performing repetitive tasks in Scilab.
Understanding break, continue, and nested loops helps in more complex iteration-based tasks.
Scilab makes it easy to perform various types of iterations and loop control mechanisms for efficient programming.