0% found this document useful (0 votes)
77 views7 pages

Functions and Loops: Programming. It Is The Most Popular Way of Programming Since It Is Quite

Loops and functions are important concepts in programming that allow tasks to be repeated and modularized. Loops include for, while, and if-then-else loops and allow repetitive tasks to be performed quickly by computers. Functions allow a program to be broken down into smaller, reusable parts. Together loops and functions allow complex problems to be broken into simpler subproblems. Common loop types like while, for, and if-else are demonstrated along with functions in Scilab.

Uploaded by

Li Re
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views7 pages

Functions and Loops: Programming. It Is The Most Popular Way of Programming Since It Is Quite

Loops and functions are important concepts in programming that allow tasks to be repeated and modularized. Loops include for, while, and if-then-else loops and allow repetitive tasks to be performed quickly by computers. Functions allow a program to be broken down into smaller, reusable parts. Together loops and functions allow complex problems to be broken into simpler subproblems. Common loop types like while, for, and if-else are demonstrated along with functions in Scilab.

Uploaded by

Li Re
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

CHAPTER 6

Functions and Loops
6.1  Introduction
When a particular numerical task needs to be “repeated” over different
data points, digital computers become a useful tool since they can perform
this action with greater speeds than humans. Loops perform exactly this
task. Using a condition to check the start and termination rules, users can
perform repetitive parts of a process as desired. Different programming
languages and environments have different rules for defining loops.
Scilab provides a simple way to define and run loops. In addition to
loops, functions also define an important part of modern programming
architecture. A big program may require a set of instructions to be
called at different times. Hence, this set of instructions can be defined
as a subprogram, which can be requested to perform the computation
at a desired time. In this way, a complicated task can be divided into
many small parts. This architecture of programming is called modular
programming. It is the most popular way of programming since it is quite
logical, good at visualizing the problem, and easy to debug. The most
popular way of defining these small sets of instructions is to define them as
functions. Together, functions and loops break a numerical computation
problem into a series of simpler problems that can be accessed as
required. In this chapter, we will discuss both of these concepts in detail.
Chapter 6 Functions and Loops

6.2  Loops
Loops form an essential part of an algorithm since they perform the
tasks that computers perform best: doing repetitive actions in a very fast
manner. Loops can come in many flavors such as for loop, which repeats
certain tasks over a list of variable values; while loop, which checks a
logical condition before executing a certain task; and if-then-else loop,
which checks a condition and directs the flow of an algorithm. The loop
you choose depends on the problem at hand.
A variety of functions and their usage are described in the following
sections. Judging their usage critically becomes supremely important because
the looping part of an algorithm consumes most of the execution time.

6.2.1  while
while loop defines a logical condition and, until it is satisfied, it runs a
block of code. The syntax for while loop is the following:

1  while condition
2  BODY
3  endwhile

Here, the keyword while initiates the execution of a while loop.


The condition is a logical condition whose answer can be 'true' (1)
or 'false' (0). The BODY encompasses the string of commands that is
executed until the condition holds true, as shown in Listing 6-1.

Listing 6-1.  while.sce

1  i = 1
2  while i<20
3      disp(i);
4      i = i∗2;
5   end

146
Chapter 6 Functions and Loops

The result is shown as follows:

1  −−>exec('/Users/sandeepnagar/.../while.sce', −1)
2  1.
3  2.
4  4.
5  8.
6  16

The code while.sce first initializes the variable i to the numerical


value 1. It then checks the condition i < 20. This is true at the first step
when i = 1. Consequently, it enters the loop and executes the command
disp(i). (The numerical value 1 is printed on the terminal.) Then the next
line is executed ( i = i * 2 ), which makes the new value of i = 2. At the end
of the loop, the control is further taken by the condition statement ( i < 20).
Until this holds true, the loop runs and, hence, 1, 2, 4, 8, 16 are printed.
When i = 16 and the statement i = i * 2 is executed, the new value of i
becomes 32. Now the condition is not satisfied and the loop is terminated.

6.2.2  Infinite Loops


Some loops can run infinitely so they are called infinite loops. Try the code
while.sce by initializing i = 0 instead of i = 1. In this case, the value of i will
always be 0 inside the loop and the condition i < 20 will always be true.
Hence, the code will run forever if it is not interrupted. Infinite loops can
be interrupted by the Ctrl+C key combination on an an ASCII keyboard.
The onus of avoiding infinite loops lies with the user. Scilab will simply
execute the statements mindlessly without showing a warning or error
message. Technically, infinite loops are not programming errors as they
are syntactically correct. In fact, infinite loops can be used if you need
to generate an infinite stream of data or if you need to execute a Scilab
program infinitely. For example, suppose a Scilab program reports the
status of a remote wind turbine. This code needs to run infinitely unless

147
Chapter 6 Functions and Loops

interrupted. In another scenario, suppose an application requires a stream


of random numbers. In this case, a Scilab code can be written to generate
an infinite sequence of random numbers.

6.2.3  for
for loop is used to perform computation on a list of known values. The
syntax of for loop is the following:

1  for variable = vector


2    BODY
3  end

The keyword for declares the starting of the loop where a variable
takes the values stored in a vector. Then a body of code (represented by
BODY) is executed. The keyword end declares the end of for loop. This is
explained in Listing 6-2.

Listing 6-2.  for.sce

1  for i = 1:10
2      square_root = sqrt(i);
3      disp(square_root)
4  end
5
6  disp("Program f inished")

Executing for1.m yields:

 1  −−−>exec('/Users/sandeepnag.../for.sce', −1)
 2  1.
 3  1.4142136
 4  1.7320508
 5  2.

148
Chapter 6 Functions and Loops

 6  2.236068
 7  2.4494897
 8  2.6457513
 9  2.8284271
10  3.
11  3.1622777
12  Program f inished

The for statement creates a vector of numerals from 1 to 10 and stores


it in a variable named i. Each member of this vector is fed to the body
of the loop. A variable named square_root stores the square root of the
value stored in the array. It is then printed on a Scilab terminal using the
command disp(square_root). When these two commands are finished,
the next member of the vector is picked and the same is repeated. This
is continued until the last member of the vector is stored in the variable
named i ( i = 10).

6.2.4  if-elseif-else
In situations where a number of conditions needs to be checked at
different points of time, if-elseif-else loop works well. The syntax for
this loop is given by the following:

1  if condition1
2  BODY1
3  elseif condition2
4  BODY2
5  else
6  BODY3
7  endif

149
Chapter 6 Functions and Loops

At line 1, a condition is defined. If this condition is satisfied, then


line 2 is executed or else line 3 is executed. Hence, BODY1 and BODY2 are
the blocks of codes that are executed by checking for different set of
conditions, and BODY3 set of codes is executed in the case when none of the
condition is executed. (See Listing 6-3.)

Listing 6-3.  ifelse.sce

1  i = rand(1,1);
2  if i>0.5 then
3  disp(i);
4  disp("True");
5  else
6  disp(i);
7  disp("False");
8  end

Running the code yields the following:

1  −−−>exec('/Users/sandeepnagar/.../ ifelse.sce', −1)


2  0.5376230
3  True
4  −−−>exec('/Users/sandeepnagar/.../ifelse.sce', −1)
5  0.1199926
6  False
7  −−−>exec('/Users/sandeepnagar/.../ifelse.sce', −1)
8  0.2256303
9  False

Whenever the value of a random number is more than 0.5, True is


printed; False is printed otherwise. (See Listing 6-4.)

150
Chapter 6 Functions and Loops

Listing 6-4.  ifelseif.sce

 1  i = rand(1,1);
 2  if i>0.5 then
 3  disp(i);
 4  disp("Value is larger then 0.5");
 5  elseif i>0.3 then
 6  disp(i);
 7  disp("value is larger than 0.5 and 0.3");
 8  else
 9  disp(i)
10  disp("value is smaller than 0.5")
11  end

When executing the code ifelseif.sce, we obtain the following


results on a Scilab terminal:

 1  −3−>exec('/Users/sandeepnagar/.../ifelseif.sce', −1)
 2  0.0485566
 3  value is smaller than 0.5
 4  −3−>exec('/Users/sandeepnagar/.../ifelseif.sce', −1)
 5  0.6723950
 6  Value is larger then 0.5
 7  −3−>exec('/Users/sandeepnagar/.../ifelseif.sce', −1)
 8  0.2017173
 9  value is smaller than 0.5
10  −3−>exec('/Users/sandeepnagar/.../ifelseif.sce', −1)
11  0.3911574
12  value is larger than 0.5 and
13  0.3

151

You might also like