Proposing a new hybrid controlled loop

12
International Journal of xxxxxx Vol. x, No. x, xxxxx, 20xx Proposing a new hybrid controlled loop George Tsaramirsis 1,* , Salam Al-jammoor 2 , Seyed M. Buhari 1 1 Faculty of Computing and Information Technology, King Abdulaziz University, Jeddah, Saudi Arabia 2 Computer science department, School of basic education, Suleimania University, Suleimania, Kurdistan, Iraq * Corresponding Author: [email protected] Abstract Counter controlled and condition controlled are main categories of iterative statements, with “for”, “while” and “do while” loops dominating the field. While there are clear distinctions between them, it is not uncommon for a programmer to practically convert a condition controlled loop to do counter controlled task or vice versa. For instance, there is a “while loop” that will be iterated a number of times or a “for loop” with an additional condition next to the counter checker. This paper proposes a new loop that will be both counter and condition controlled. The loop will include an in-built predefined counter and it will be able to iterate a user defined number of time, prior to checking the user defined condition. A detailed explanation and a C++ implementation of the proposed loop are included in this paper. Keywords: iterative statements, loop, hybrid control loop 1. Introduction The repeated execution of a statement or compound statement is achieved either by iteration or recursion. Most iteration statements fall under the category of counter controlled, condition controlled or collection controlled loops, depending on what mechanism they use to terminate the repetition. Members of the first category depend on a counter that is usually part of the definition of the loop in order to terminate it. Condition controlled loops maintain the iteration while the condition is satisfied. The condition is usually part of the syntax of the loop and the body includes the code that will make it false and cause the end of the loop. The last category includes a collection of 1

Transcript of Proposing a new hybrid controlled loop

International Journal of xxxxxxVol. x, No. x, xxxxx, 20xx

Proposing a new hybrid controlled loop

George Tsaramirsis1,*, Salam Al-jammoor2, Seyed M. Buhari1

1 Faculty of Computing and Information Technology, King Abdulaziz University,Jeddah, Saudi Arabia

2 Computer science department, School of basic education, SuleimaniaUniversity, Suleimania, Kurdistan, Iraq

* Corresponding Author: [email protected]

AbstractCounter controlled and condition controlled are main categories of iterative

statements, with “for”, “while” and “do while” loops dominating the field. While thereare clear distinctions between them, it is not uncommon for a programmer topractically convert a condition controlled loop to do counter controlled task or viceversa. For instance, there is a “while loop” that will be iterated a number of times or a“for loop” with an additional condition next to the counter checker. This paperproposes a new loop that will be both counter and condition controlled. The loop willinclude an in-built predefined counter and it will be able to iterate a user definednumber of time, prior to checking the user defined condition. A detailed explanationand a C++ implementation of the proposed loop are included in this paper.

Keywords: iterative statements, loop, hybrid control loop

1. Introduction

The repeated execution of a statement or compound statementis achieved either by iteration or recursion. Most iterationstatements fall under the category of counter controlled,condition controlled or collection controlled loops,depending on what mechanism they use to terminate therepetition. Members of the first category depend on acounter that is usually part of the definition of the loopin order to terminate it. Condition controlled loopsmaintain the iteration while the condition is satisfied. Thecondition is usually part of the syntax of the loop and thebody includes the code that will make it false and cause theend of the loop. The last category includes a collection of

1

International Journal of xxxxxxVol. x, No. x, xxxxx, 20xx

data that the loop goes through all of them or through thosethat satisfy a certain condition. Most languages support both condition based and counter

controlled loops with “while” and “for” loops leading thescene as they are supported by the most popular languages(C, Java. C++) [1]. However, it is not uncommon for aprogrammer to practically convert a condition controlledloop to counter or vice versa. Consider a “while loop” withan in-build counter added by the programmer in the body ofthe loop, that will be terminated after it is executed anumber of times or a “for loop” with an additional conditionnext to the counter checker. The following code illustratesexamples for both cases. int i = 0;while (i < 10){ // do something i++;}for (int i = 1; i <= 10; i++) // do something

Additionally, the do while loop, executes the code in thebody of the loop one time prior of checking the condition.

This paper is proposing a new loop that is a hybrid betweenfor, while and do while loops offering all their capabilitiesin one loop. The proposed loop has one or two arguments and aninbuilt counter. The first argument is how many times the loopshould iterate its body prior of checking the condition, whilethe second argument is the condition if any. The three proposedsyntaxes are:

The first will iterate X times and then stop. The second williterate X times and then check the condition. The last willcheck the condition before execute the code in its body.

While the ideas presented in this paper are simple and easyto implement, they can simplify the iteration statements andmake them easier for new programmers to learn.

2

International Journal of xxxxxxVol. x, No. x, xxxxx, 20xx

The next section of this paper presents a brief summary onhow most programming languages are dealing with iterations.Section three, presents the proposed loop in detail and itincludes an implementation in C++ to serve as proof of concept.Section four, discuss the advantages of the proposed syntaxesand finally section five presents the conclusions of thispaper.

2. Iteration Statements in Programming LanguagesDifferent programming languages support repetition of

instructions using various techniques. One of the oldestmechanisms used for instruction repetition is the go-tocommand. The go-to is presented in a number of languagessuch as ADA, C, Fortran, Basic and Algol 60 that wereunconditionally transferring control to another part of thecode. In languages such as Basic and Fortran, the go-torequires the number of lines in the source code that will beexecuted next while languages such as ADA and C transfercontrol to the code that follow pre-defined labels. Theprogrammer can place labels anywhere in the source code.Other languages such as Algol 60, allow the go-to totransfer control to both lines of the source code andlabels. GOTOs can be useful features, “eliminate duplicatecode” [2] and result in “faster and smaller code”.[3]However, “In practice, use of gotos tends to violatestructured programming principles” [2]. Böhm proved that itis possible to solve any computational problem without theuse of go-to [4]. “Methodical decomposition, refinement, andselection of control structures automatically leads to goto-free programs in most cases” [2] and in fact languages suchas Java use control statements instead “go-to” statements.Another way to achieve repetition is the use of iterative

control statements. Such statements are known as loops.Loops repeat fragments of code and depending on themechanism that they use to stop, are categorized as countercontrolled, condition controlled and collection controlledloops. Counter controlled loops use a variable with a numeric

value as a counter in order to keep track of how many timeshas been executed. This counter is usually part of thesyntax of the loop. Once the counter research a user definedvalue the loop stops. In some languages such as ADA, FORTRAN77 and 90 the value of the counter can’t be changed from thebody of the loop because they are evaluated only once at thebeginning of the loop. On the other hand languages like C,C++, Java and C# allow the counter to be changed from insidethe body as it is evaluated after each iteration. [5] The

3

International Journal of xxxxxxVol. x, No. x, xxxxx, 20xx

syntax of counter controlled loops for incrementing from oneto ten is described below in a number of languages:

Ada:for i in 1 .. 10 loop -- do somethingend loop;

Bash:for i in 1 2 3 4 5 6 7 8 9 10do # do somethingdone

C, C++, C#, Java, JavaScript, Perl, PHP:for (int i = 1; i <= 10; i++) // do something

Even if the syntax between the above languages looks the samethere are some differences. The main point is that somelanguages such as Java, has Boolean condition while C/C++allows expressions as condition.

FORTRAN:do i = 1, 10, 1 // do somethingend do

In the above code, the “i” is initialized to 1 and themaximum that will reach is 10 and the step is 1. So it willstart from 1 and increment by 1 until it reaches 10.

Lua:for i = 1, 10 do -- do somethingend

Pascal:for I := 1 to 10 do (*do something*);

4

International Journal of xxxxxxVol. x, No. x, xxxxx, 20xx

Python:for i in range(1, 10): # do something

The above will give the values from 1 to 9 but not 10.

Smalltalk:1 to: 10 do: [ :i | "do something" ]

Another famous category is condition controlled loops.Condition controlled loops also known as logical controlledloops, iterate while a user defined condition is true. Thiscondition is defined as part of the syntax of the loop. Thequestion that is raised is whether the loop is executed firstand then the condition is checked (pre-test) or if thecondition is checked first and if it is satisfied the code inthe body is executed (post-test). Most of the programminglanguages that support iterative control statement support pre-test but not all support post-test. For example Ada does notsupport post-test [5]. The syntax of pre-test and post-testloops (if available), for incrementing from one to ten, whilesatisfying a condition, is described below in a number oflanguages:

Ada:begin while i < 10 loop -- do something i := i + 1; end loop;

Ada first tests the condition and then executes. There areways to achieve post-test loop in Ada but there is no defaultways for doing it.

Bash:i=0while [ $i -lt 10 ]; do # do something i=$((i + 1))done

5

International Journal of xxxxxxVol. x, No. x, xxxxx, 20xx

Like Ada, Bash also has no post-test controlled loop. C, C++, C#, Java, JavaScript, Perl, PHP:int i = 0;while (i < 10){ // do something i++;}

The above code will first test the condition and thenexecute. An alternative known as “do while” is the post-testversion. int i = 0;do { // do something} while (i < 10);

FORTRAN:integer :: i = 0do while (i < 10) i = i + 1end doFortran, and Lua have no post-test controlled loops. Lua:i = 0while i < 10 do i = i + 1end

Pascal:Var i: integer;begin i := 0; while i < 10 do begin (*do something*);

i := i + 1 end;

6

International Journal of xxxxxxVol. x, No. x, xxxxx, 20xx

The above code will first test the condition and thenexecute. A post-test version of the loop is shown below. repeat (*do something*); i := i + 1;until i = 10;

Python:i = 0 while i < 10:

# do something. i += 1 Python and SmalTalk have no post-test loop by default.

SmallTalk:i := 0.[ i < 10 ] whileTrue: # do something. i := i + 1 ].

In this section we have shown an example of iterating a loop10 times, using a counter or a condition, in a number ofprogramming languages. The purpose of this was to have abenchmark for our loop. The proposed loop will be discussed insome detail in the following section.

3. The Proposed LoopThe proposed loop attempts to combine the “for”, “while”

and “do while” loops as they appear in C++ with a newsimpler syntax. The key idea behind the loop is that most oftimes we use simple iterations [7]. The proposed loop hasthree syntaxes.

loop(number){ // do something }This will execute the body a number of times without checkingany condition.

loop(condition){ // do something }The second syntax include pre-test of a condition like C++’swhile loop.

7

International Journal of xxxxxxVol. x, No. x, xxxxx, 20xx

loop(number,condition){ // do something }Finally, the loop is able to run a pre-defined number of

times prior of testing the condition. The parameters of theloop can be modified from the body of the loop. The loopincludes two reserved keywords. “loopCount” and “loopStep”.The first holds the current value of an inbuilt counter. Thesecond holds the step that will make the loop to incrementor decrement. The loop can restart at any time by settingthe loop Counter to 0 or any other starting value in thebody of the loop. Early exit is supported using the break;statement like C++. A possible implementation of theproposed loop is presented in the following section.

4. ImplementationThe aim of this paper is to propose a new simpler syntax.

The proposed loop is currently implemented in C++ based onthe language’s pre-processor and tested online at [6]. Thisis to serve as a proof of concept and we would be honored tosee our syntax included in other languages. The code belowdefines three syntaxes of the loop function. The first_loop(X), will iterate from X to 1. The appropriate loopfunction is chosen based on the number of arguments passed.The loop(X) with one argument syntax, can accept an integeror a Boolean as parameter. If the argument is an integer, itwill iterate from 0 until X-1. If the argument is a Booleanthen the counter will increment from zero to the max valuethat an integer can take and it will be depended on theBoolean condition to be false in order to terminate theloop. The last syntax takes two arguments, an integer X anda Boolean expression con, and it will first iterate fromzero to X without checking any condition and then startchecking the condition. If both the counter evaluation andcondition are false then the loop will terminate.

8

International Journal of xxxxxxVol. x, No. x, xxxxx, 20xx

The code above can be included in any C++ code. The loop canbe used in the main function like any other loop.

int main(){ loop(10)

// loopCount is an inbuilt variable cout <<loopCount;

return 0;}The aim of this section is to illustrate a possible

implementation of the proposed loop in order to offer abetter understanding to the readers.

5. DiscussionThe new loop is a hybrid approach that combines the counter

controlled loops with the condition controlled loops. In theproposed loop the syntax for executing 10 times, startingfrom 1 and with step 1, is: loop(10){ // do something }

As it can be seen the syntax is simpler than all the loopsdiscussed in section 2, and there is no need to differentiatebetween logical or counter controlled loop as this is hiddenwithin the loop. It is worth to be noted that most of the timewe use loops for simple things. Let’s assume that we want touse a condition instead of a number. The code will change to:loop(loopCount<10){ // do something }

The above is simpler than a while loop because there is noneed to define any counters.

9

International Journal of xxxxxxVol. x, No. x, xxxxx, 20xx

Let’s consider another example where there is a need todecrement two steps at a time, from 10 to 2 and print the valueof the counter. _loop(10) { loopStep=-2; cout << loopCount;}

Modifying the loopStep and loopCounter parameters allow theprogrammers to express complex expressions. The code of the proposed post-test loop is:Loop(10,loopCounter<10){// do something}

The above code is similar to the “do while” loop of C++ withthe difference that the code will first iterate 10 times andthen it will start checking the condition, while in “do while”loop, it runs only one time prior of testing the condition.This is the main contribution of this work

The computational complexity of loop function with one or twoparameters is discussed here. Presence of a single parameter,which is counter based, causes the loop to be executed aspecified number of times, denoted as N. Thus, the complexityis O(N). For a loop function with single parameter, which iscondition based, the evaluation is based on the condition. Forthe dual parameter loop function, the computation complexityis:

O(Counter) + O(Condition) = O(N) + ???Considering that O(Condition) has an upper bound of O(N), the

total computational complexity of the dual parameter loopfunction is still O(N). This proves that the upper bound andscalability of the loop function is mainly restricted by theCounter-based parameter.

6. Conclusions and Future WorkThe aim of this paper was to propose a new syntax of a loop

that combines the counter controlled loops with thecondition controlled loops and makes it easier forprogramming simple iterations. The motivation comes bycombining C++ “for”, “while” and “do while” loops. The loophas three possible syntaxes. a) loop(int), b)loop(condition), c) loop(int, condition). The first williterate a number of times without testing any conditions.The second will conduct a pre-test and if it is satisfied it

10

International Journal of xxxxxxVol. x, No. x, xxxxx, 20xx

will iterate once before checking the condition again. Thelast will iterate a user defined number of times withouttesting any conditions and then start testing the condition.The loop can be modified to express more complex statements,by modifying two inbuilt variables. The loopCount holds thecurrent value of the counter and the loopStep holds the stepvalue. However, a current limitation is that these areabsent in the case of loop(condition). Early exit issupported using the C++ break command. The paper alsoprovides a C++ implementation of the loop, to be used asproof of concept. In the future we will improve the syntax by including the

loop(int A, int B) syntax that will iterate from A to B andthe loop(-Number) syntax that will replace the_loop(Number). Additionally, we hope to offerimplementations of the proposed loop in more programminglanguages and receive more feedback about the usability ofthe proposed syntax. This will allow us to improve further

7. References[1] Programming Language Popularity. www.LangPop.com. Last accessed

(02/02/2013)[2] Redmond Wa, Code Complete: A practical Handbook of Software Construction,

Microsoft Press (1993) http://www.stevemcconnell.com/ccgoto.htm[3] Knuth, Donald E., Structured Programming with go to Statements, ACM

Computing Surveys, December (1974), 6(4):261-301[4] Böhm, Jacopini, Flow diagrams, turing machines and languages with only two

formation rules, Comm. ACM, May (1966), 9(5):366-371[5] Seyed Mohamed Buhari. Principles of programming languages. A paradigm

approach. Tata McGraw-Hill Education, New Delhi (2010)[6] Codepad http://codepad.org/[7] E Larson, Program Analysis Too Loopy? Set the Loops Aside, 11th IEEE

International Working Conference on Source Code Analysis and Manipulation(SCAM), September 25-26 (2011), pp.15 - 24

AuthorsSeyed M. Buhari

Seyed Buhari is an Assistant Professor in the Information TechnologyDepartment, King Abdulaziz University, Jeddah, Saudi Arabia. Hereceived his B.E. degree in Computer Engineering from Madurai KamarajUniversity, India, in 1996, and M.E. degree in Computer Science andEngineering from Bharathiar University, India, in 1998. He hasobtained his Ph.D in Information Technology from MultimediaUniversity, Malaysia. From 2006 to 2012, he was with University

Brunei Darussalam, Brunei Darussalam. From 2000 to 2006, he was with Information andComputer Science Department, King Fahd University of Petroleum and Minerals, SaudiArabia. His current research interests are in the areas of cognitive radio networks,grid computing, IPv6 performance testing and high performance computing.

George Tsaramirsis

11

International Journal of xxxxxxVol. x, No. x, xxxxx, 20xx

George Tsaramirsis is an Assistant Professor in the InformationTechnology Department, King Abdulaziz University, Jeddah, SaudiArabia. George is currently supervising one PhD candidate at CityUniversity London. George’s recent work experience included workingfor Accenture UK, as well as smaller IT companies in London, UK. Dr.George received his PhD from King's College London, University ofLondon, UK. George's current research interests lie within Softwareengineering and its applications.

Salam Al-jammoor

Salam Al-jammoor is an assistant lecturer in the university ofsulaymaniyah, Iraq. Salam has more than 7 years experience teachingundergraduate students in the university. He is specializing inJava, operating systems and networking. His current researchinterests are optical networks and programming.

12