In: Computer Science
4. Rewrite the following pseudocode segment using a loop structure in the specified languages:
k = (j + 13) / 27
loop:
if k > 10
then goto out
k = k + 1
i = 3 * k - 1
goto
loop
out: . . .
a. C++
b. Python
c. Ruby
Assume all variables are integer type. Discuss the relative merits of the use of these languages for this particular code.
Answer:
a. c++
for (k = ((j + 13) / 27) +1); k <= 10; k++)
{
i = 3 * k – 1;
}
In these languages syntax of loops are very efficient for the users. The for loop contains three parts here:
1) Initialization: It is the first field of for loop. Here, a variable is initialized with an initial value.
2) Condition: Here a Boolean expression is used which tells when the loop will terminate.
3) Updation: This field contains increment or decrement in the value of a variable which is responsible for execution of the loop.
b. Python:
In python for loop iterates over a list. Here a method named range() is defined also with the help of which we can define initial and final range for a loop.
temp= range((((j+13)/27)+1), 11)
for k in temp
i = 3 * k - 1
temp is a variable which is used to hold a list of all values from initial value to final.
c. Ruby:
The range in Ruby’s for loop is defined by:
1 … 8, means loop will execute 1 to 7
1 .. 8, means loop will execute 1 to 8
Do is optional in the for loop of Ruby.
for k in (((j + 13) / 27)+1) .. 10 do
i = 3 * k – 1
end
Best writability:
In C++ for loop is most flexible, and for loop in C++can be used for most complexes looping which makes it writable. The ability to place assignment statements and increment/decrement statements inside the loop provides the programmer a shortcut in writing operations which makes the for loop most writable.
In python’s for loop there is no closure reserved word is used (like end for), But it is not flexible as it iterates over the list.In ruby end closure reserved word is used which makes it hard to write.
Hence, C, C++, Java, or C# has the best writability.
Best readability:
Due to complexity of for loop in C, as assignment, increment/decrement statements are placed inside a loop, readability of for loop damaged.
The for loop in python makes it ambiguous as there is no symbol exist to indicate end of the loop.The Readability of the for loop in Ruby has nearly the same readability but in Ruby end reserve word is used to indicate end of the loop which can makes it ambiguous as user will confuse in taking decision that it is ending of for loop or for anything else.
Readability is more important than writability for a best programming language. But Ruby’s for loop has the best combination of both.
Please give thumbsup or do comment in case of any queries. Thanks.