Martes, Oktubre 7, 2014

Other Programming Tools and Environments





A. Program Design                                                                                                                                                                                                       The activity of progressing from a specification of some required program to a description of the program itself. Most phase models of the software life cycle recognize program design as one of the phases. The input to this phase is a specification of what the program is required to do. During the phase the design decisions are made as to how the program will meet these requirements, and the output of the phase is a description of the program in some form that provides a suitable basis for subsequent implementation.

Frequently the design phase is divided into two subphases, one of coarse architectural design and one of detailed design. The architectural design produces a description of the program at a gross level; it is normally given in terms of the major components of the program and their interrelationships, the main algorithms that these components employ, and the major data structures. The detailed design then refines the architectural design to the stage where actual implementation can begin. See also program design language.


 B. Productivity Tools

  End-User Programming Productivity Tools
Andrew J. Ko, Brad A. Myers, Michael J. Coblenz, and Jeffrey Stylos
Human-Computer Interaction Institute
Carnegie Mellon University
Pittsburgh, PA 15213
ajko@cs.cmu.edu, bam@cs.cmu.edu, mcoblenz@andrew.cmu.edu, jsstylos@cs.cmu.edu
http://www.cs.cmu.edu/~marmalade


ABSTRACT
Our research focuses on developing interactive technologies
for a broad range of end-user programming activities,
including code construction, verification, debugging, and
understanding. A common goal among all of these
technologies is to identify core ideas that can be used across
a variety of domains and programmer populations.
 

INTRODUCTION
Although end-user programmers’ interests vary widely,
spanning the web, animation, documents, databases, mail,
and countless other types of information, all of these users
use programming as a means to an end [10]. Therefore, to
minimize the distractions from end users’ primary goal, it is
essential that end user programming tools are approachable,
easy to learn, and immediately helpful [1].
We are designing several technologies that satisfy these
criteria, including new interaction techniques for editing
code, new languages that help end users identify mistakes,
debugging tools that answer users’ questions about their
program’s output, and workspaces that help them
understand the answers. All of these technologies have been
directly inspired by the empirical research of a variety of
programmer populations and their difficulties [5, 6, 8, 11].
Figure 1. Barista [7], a Java editor that supports drag and
drop, auto-complete menus, and text editing in a single editor,
and embedded, in-context tools and visualizations.
 

CONSTRUCTING PROGRAMS
Syntax has long been a significant learning barrier in end-
user programming systems, largely because of the difficulty
of understanding and remembering the hidden and complex
rules encoded in language grammars [5]. We have been
working on a new class of code editors that try to help users
construct code by choosing from different options rather
than having to memorize the syntax. Barista [7], shown in
Figure 1, is a Java editor that embodies this approach. It
supports drag and drop interactions for creating and
modifying code and syntactic and semantic auto-
completion, as well as traditional text editing interaction
techniques, all in a modeless editor. Barista also allows
designers of end-user programming systems to embed tools
and information in code, as illustrated by the method header
on the bottom of Figure 1.
Although Barista is currently for Java, its underlying design
and techniques could be an alternative to conventional text
editors across the spectrum of programming languages.
 

DETECTING ERRORS
Some spreadsheet systems allow users to specify units (e.g.
5 lbs.) with their data in order to help detect unit errors in
calculations. However, most data represented in
spreadsheets is a measurement of a particular kind of object
(e.g., 5 lbs of apples), and it is often inappropriate to
perform calculations on data that represent different kinds
of objects. Slate [2], shown in Figure 2, allows users to
Figure 2. Slate [2], a spreadsheet language that allows users to
give data labels, in order to help identify incorrect input and
formulas. For example, the label “(apples, oranges)” at the
bottom right of the spreadsheet suggests an error, since
nothing can be apples and oranges simultaneously.Figure 3. The Whyline [4] which allows users to ask “Why
Did” and “Why Didn’t” questions about their program’s
output, and get answers in terms of the events related to the
behavior in question. In this situation, the user asked why Pac
did not resize, and the answer shows the execution events that
caused the “else” part of the conditional to be executed.
represent the object of measurement as a label. By
intelligently propagating labels, Slate can help users
identify incorrect input data and calculations. For example,
in the spreadsheet shown in Figure 2, the result “$179.55
(apples, oranges)” tells the user that one of the formulas is
likely to be incorrect, since nothing can be an apple and an
orange at the same time.
Labels could be used in other end-user domains, such as
animations or dynamic web pages that involve computation
on heterogeneous and semi-structured data.
Figure 4. Crystal [9], a word processor that allows users to ask
questions about the document and application state, and get
answers in terms of the user interface components that are
related to the behavior in question. In this situation, a user
asked why a word changed from “teh” to “the”, and the
answer explains that the “Replace text as you type” checkbox
is checked.
processor’s behavior. A user study demonstrated that this
helped users solve common problems about 30% faster than
the same word processor without support for questions [9].
We are currently generalizing the Whyline to more complex
and widely used languages, such as Java, in order to
identify issues of scale and assess the range of questions
that people ask about program behavior.
 

UNDERSTANDING PROGRAMS
DEBUGGING PROGRAMS

One reason debugging is the most time-consuming part of
programming is that end users must map their questions
about a program’s behavior onto debugging tools’ limited
support for analyzing code. We have been working on a
new approach called interrogative debugging, which allows
programmers to ask questions directly about their
programs’ output. Our prototype, the Whyline [4], allows
programmers to ask "Why did" and "Why didn't" questions
about their program's output in the Alice programming
environment (www.alice.org). Programmers choose a
question from an automatically generated menu, and the
tool provides an answer, as seen in Figure 3, in terms of the
runtime events that caused or prevented the desired output.
In user studies of the Whyline, users with the Whyline
spent an eighth as much time debugging the same bugs than
users without the Whyline and made 40% more progress.
In generalizing the Whyline, we have begun to apply its
ideas to traditional user interfaces. Our Crystal word
processor [9], seen in Figure 4, allows users to ask
questions such as “Why did this word change from ‘teh’ to
‘the’?” and get answers in terms of the user interface
components and state that were responsible for the word
Even though their programs tend to be small, end users still
tend to have difficulty relating code to its corresponding
behavior [5]. Furthermore, the interfaces that end users use
to navigate and understand code, mainly windows and tabs,
incur significant navigational overhead [6]. We are
currently designing a new type of workspace that helps
users both interactively and automatically collect fragments
of code and other information that is relevant to their
maintenance or debugging tasks. It will eliminate much of
the navigational overhead, while helping users to quickly
understand dependencies between different parts of their
program. 

LEARNING TERMINOLOGY
One common programming activity, even among end-user
programmers [5] is learning to use a collection of external
code in the form of libraries, toolkits, APIs, and
frameworks. Some of the difficulty in this task comes from
the fundamental vocabulary problem [3]: a particular
programming concept can be described in multiple ways
and no one word will best describe it for all programmers.
Mica, shown in Figure 5, attempts to solve this problem by
acting as a thesaurus: programmers supply a description of
the desired functionality, using their own terminology, andACKNOWLEDGMENTS
We thank our collaborators, including Htet Htet Aung,
Christopher Scaffidi, and David Weitzman. This work was
supported by the National Science Foundation, under NSF
grant IIS-0329090, and as part of the EUSES consortium
(End Users Shaping Effective Software) under NSF grant
ITR CCR-0324770. The first author was supported by an
NDSEG fellowship.
REFERENCES
1.
2.
3.
4.
Figure 5. The Mica web application. Mica includes a keyword
sidebar on the left, which is generated from Google Web API
search results shown on the right. Search result pages
containing code are marked with an icon.
Mica finds related classes and methods in the standard Java
APIs in the form of keywords (method, class and interface
names on the left in Figure 5) and regular web search
results (on the right in Figure 5). Mica determines API
keywords by analyzing the content of the Google search
result pages and comparing these to a list of all class and
method names for the standard Java API. The keywords are
ranked based on the frequency with which they appear in
the search result pages for the query and the overall
frequency with which they appear on all pages indexed by
Google. The list of keywords dynamically updates as Mica
loads and processes all of the search result pages.
We plan to expand Mica’s to aid other aspects of API use,
such as understanding high-level API concepts, finding
example code, and integrating examples into programs.
 

CONCLUSIONS

 
Our research covers a broad spectrum of programming
activities, and we anticipate that our techniques will
generalize to a variety of domains and programmer
populations. We hope that our broad focus will both inspire
new ideas for commercial programming tools and drive
innovations in end user software engineering research.
5.
6.
7.
8.
9.
10.
11.
Blackwell, A., First Steps in Programming: A
Rationale for Attention Investment Models, IEEE
Symposia on Human-Centric Computing Languages
and Environments, (2002), 2-10.
Coblenz, M. J., Ko, A. J., and Myers, B. A., Using
Objects of Measurement to Detect Spreadsheet
Errors, IEEE Symposium on Visual Languages and
Human-Centric Computing, (2005), 314-316.
Furnas, G. W., Gomez, T. K. L. L. M., and Dumais,
S. T., "The Vocabulary Problem in Human-System
Communication," in Communications of the ACM,
30, 1987, 964-971.
Ko, A. J. and Myers, B. A., Designing the Whyline:
A Debugging Interface for Asking Questions About
Program Behavior, Human Factors in Computing
Systems, (2004), 151-158.
Ko, A. J., Myers, B. A., and Aung, H., Six Learning
Barriers in End-User Programming Systems, IEEE
Symposium on Visual Languages and Human-Centric
Computing, (2004), 199-206.
Ko, A. J., Aung, H., and Myers, B. A., Eliciting
Design Requirements for Maintenance-Oriented
IDEs: A Detailed Study of Corrective and Perfective
Maintenance Tasks, International Conference on
Software Engineering, (2005), 126-135.
Ko, A. J. and Myers, B. A., Barista: An
Implementation Framework for Enabling New
Interaction Techniques and Visualizations in Code
Editors, ACM Conference on Human Factors in
Computing, (2005), to appear.
Ko, A. J. and Myers, B. A., A Framework and
Methodology for Studying the Causes of Software
Errors in Programming Systems, Journal of Visual
Languages and Computing, 16, 1-2, (2005), 41-84.
Myers, B. A., Weitzman, D. A., Ko, A. J., and Chau,
D. H., Answering Why and Why Not Questions in
User Interfaces, ACM Conference on Human Factors
in Computing Systems, (2005), to appear.
Nardi, B. A., A Small Matter of Programming:
Perspectives on End User Computing. Cambridge,
MA: The MIT Press, 1993.
Panko, R., What We Know About Spreadsheet
Errors, Journal of End User Computing, 2, (1998),
15-21.








C. Expert Advisors

The principles of MQL4-programs 
development are shown on sample of creating a simple Expert Advisor system based on the standard MACD indicator. In this Expert Advisor, we will also see examples of implementing such features as setting take profit levels with the support of trailing stop as well as the most means ensuring safe work. In our example, trading is done through opening and managing a single position.
Trading principles:
  • Long (BUY) entry – MACD indicator is below zero, goes upwards and is crossed by the Signal Line going downwards.
  • Short (SELL) entry – MACD indicator is above zero, goes downwards and is crossed by the Signal Line going upwards.

  • Long exit – by execution of the take profit limit, by execution of the trailing stop or when MACD crosses its Signal Line (MACD is above zero, goes downwards and is crossed by the Signal Line going upwards).
  • Short exit – by execution of the take profit limit, by execution of the trailing stop or when MACD crosses its Signal Line (MACD is below zero, goes upwards and is crossed by the Signal Line going downwards).
Important notice: to exclude insignificant changes of the MACD indicator (small 'hillocks' on the chart) from our analysis, we introduce an additional measure of controlling the size of the plotted 'hillocks' as follows: the indicator size should be at least 5 units of the minimum price (5*Point, which for USD/CHF = 0.0005 and for USD/JPY = 0.05).

Step 1 – Writing the Expert Advisor description
Point the mouse cursor at the Expert Advisors section of the Navigator window, press the right button of the mouse, and select "Create a new Expert" command in the appearing menu. The Initializing Wisard of the Expert Advisor will ask you for entering certain data. In the appearing window, write the name (Name) of the Expert Advisor - MACD Sample, the author (Author) - indicate your name, the link (Link) - a link to your website, in the notes (Notes) - Test example of an MACD-based Expert Advisor.

Step 2 – Creating the primary structure of the programme
Source code of the test Expert Advisor will only occupy several pages, but even such volume is often difficult to grasp, especially regarding that we are not professional programmers - otherwise, we would not need this description at all, would we? :)
To get some idea of the structure of a standard Expert Advisor, let us take a look at the description given below:
  1. Initializing variables
  2. Initial data checks
    • check the chart, number of bars on the chart
    • check the values of external variables: Lots, S/L, T/P, T/S
  3. Setting the internal variables for quick data access
  4. Checking the trading terminal – is it void? If yes, then:
    • checks: availability of funds on the account etc...
    • is it possible to take a long position (BUY)?
      • open a long position and exit
    • is it possible to take a short position (SELL)?
      • open a short position and exit
exiting the Expert Advisor...
    • Control of the positions previously opened in the cycle
      • if it is a long position
        • should it be closed?
        • should the trailing stop be reset?
      • if it is a short position
        • should it be closed?
        • should the trailing stop be reset?
    • It turns out to be quite simple, only 4 main blocks.
      Now let us try to generate pieces of code step by step for each section of the structural scheme:
      1. Initializing variables
        All variables to be used in the expert program must be defined according to the syntax of MetaQuotes Language 4 first. That is why we insert the block for initializing variables at the beginning of the program
        extern double TakeProfit = 50;
        extern double Lots = 0.1;
        extern double TrailingStop = 30;
        extern double MACDOpenLevel=3;
        extern double MACDCloseLevel=2;
        extern double MATrendPeriod=26;
        MetaQuotes Language 4 is supplemented by "external variables" term. External variables can be set from the outside without modifying the source code of the expert program. It provides additional flexibility. In our programm, the MATrendPeriod variable is defined as extern variable. We insert the definition of this variable at the beginning of the program.
        extern double MATrendPeriod=26;
      2. Initial data checks
        This part of code is usually used in any expert with minor modifications because it is a virtually standard check block:
        // initial data checks
        // it is important to make sure that the expert works with a normal
        // chart and the user did not make any mistakes setting external 
        // variables (Lots, StopLoss, TakeProfit, 
        // TrailingStop) in our case, we check TakeProfit
        // on a chart of less than 100 bars
           if(Bars<100)
             {
              Print("bars less than 100");
              return(0);  
             }
           if(TakeProfit<10)
             {
              Print("TakeProfit less than 10");
              return(0);  // check TakeProfit
             }
      3. Setting internal variables for quick access to data
        In the source code it is very often necessary to access the indicator values or handle the calculated values. To simplify the coding and speed up the access, data are put into internal variables.
        int start()
          {
           double MacdCurrent, MacdPrevious, SignalCurrent;
           double SignalPrevious, MaCurrent, MaPrevious;
           int cnt, ticket, total;
        
        // to simplify the coding and speed up access
        // data are put into internal variables
           MacdCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
           MacdPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
           SignalCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);
           SignalPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);
           MaCurrent=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,0);
           MaPrevious=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1);

        Now, instead of the monstrous notation of iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0), you can use MacdCurrent in the source code.
      4. Checking the trading terminal – is it empty? If it is, then:
        In our Expert Advisor, we use only those positions which are opened with market orders and do not handle the pending orders. However, to be on the safe side, let us introduce a check of the trading terminal for previously placed orders:
         total=OrdersTotal();
           if(total<1) 
             {
        • checks: availability of funds on the account etc...
          Before analyzing the market situation it is advisable to check the status of your account to make sure that there are free funds on it for opening a position.
                if(AccountFreeMargin()<(1000*Lots))
                  {
                   Print("We have no money. Free Margin = ", AccountFreeMargin());
                   return(0);  
                  }
        • is it possible to take a long position (BUY)?
          Condition of entry into the long position: MACD is below zero, goes upwards and is crossed by the Signal Line going downwards. This is how we describe it in MQL4 (note that we operate on the indicator values which were previously saved in the variables):
                // check for long position (BUY) possibility
                if(MacdCurrent<0 && MacdCurrent>SignalCurrent && 
                   MacdPrevious<SignalPrevious &&
                   MathAbs(MacdCurrent)>(MACDOpenLevel*Point) && 
                   MaCurrent>MaPrevious)
                  {
                   ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,
                                    "macd sample",16384,0,Green);
                   if(ticket>0)
                     {
                      if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) 
                         Print("BUY order opened : ",OrderOpenPrice());
                     }
                   else Print("Error opening BUY order : ",GetLastError()); 
                   return(0); 
                  }
          Additional control over the size of the 'hillocks' being drawn was already mentioned above. MACDOpenLevel variable is a user-defined variable which may be changed without interfering with the program text, to ensure greater flexibility. In the beginning of the programme we insert a description of this variable (as well as the description of the variable used below).
        • is it possible to take a short position (SELL)?
          Condition of entry of a short position: MACD is above zero, goes downwards and is crossed by the Signal Line going upwards. The notation is as follows:
                    // check for short position (SELL) possibility
                    if(MacdCurrent>0 && MacdCurrentSignalPrevious && 
                       MacdCurrent>(MACDOpenLevel*Point) && 
                       MaCurrent<MaPrevious)
                      {
                       ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,
                                        "macd sample",16384,0,Red);
                       if(ticket>0)
                         {
                          if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) 
                             Print("SELL order opened : ",OrderOpenPrice());
                         }
                       else Print("Error opening SELL order : ",GetLastError()); 
                       return(0); 
                      }
          
            return(0);
           }
      5. Control of the positions previously opened in the cycle
        // it is important to enter the market correctly, 
        // but it is more important to exit it correctly...   
        for(cnt=0;cnt
          {
           OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
           if(OrderType()<=OP_SELL &&   // check for opened position 
              OrderSymbol()==Symbol())  // check for symbol
             {
        "cnt" – " is a cycle variable that must be defined at the beginning of the program as follows:
         int cnt = 0; 
        • if it is a long position
          if(OrderType()==OP_BUY)   // long position is opened
            {
          
          • should it be closed?
            Condition for exiting a long position: MACD is crossed by its Signal Line, MACD being above zero, going downwards and being crossed by the Signal Line going upwards.
            if(MacdCurrent>0 && MacdCurrent<SignalPrevious &&
               MacPrevious>SignalPrevious &&
               MacdCurrent>(MACDCloseLevel*Point))
              {
               OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position
               return(0); // exit
              }
          • should the trailing stop be reset?
            We set the trailing stop only in case the position already has a profit exceeding the trailing stop level in points, and in case the new level of the stop is better than the previous.
            // check for trailing stop
            if(TrailingStop>0)  
              {                 
               if(Bid-OrderOpenPrice()>Point*TrailingStop)
                 {
                  if(OrderStopLoss()
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,
                                 OrderTakeProfit(),0,Green);
                     return(0);
                    }
                 }
              }
          We close the brace of the operator.
             }
        • if it is a short position
          else // go to short position
            {
          • should it be closed?
            Condition for exiting a short position: MACD is crossed by its Signal Line, MACD being below zero, going upwards and being crossed by the Signal Line going downwards.
            if(MacdCurrent<0 && MacdCurrent>SignalCurrent &&
               MacdPrevious<SignalPrevious &&
               MathAbs(MacdCurrent)>(MACDCloseLevel*Point))
              {
               OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position
               return(0); // exit
              }

          • should the trailing stop be reset?
            We set the trailing stop only in case the position already has a profit exceeding the trailing stop level in points, and in case the new level of the stop is better than the previous.
            // check for trailing stop
            if(TrailingStop>0)  
              {                 
               if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
                 {
                  if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0))
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,
                                 OrderTakeProfit(),0,Red);
                     return(0);
                    }
                 }
              }
          Closing all the curly bracket which remain open.
                   }
                }
             }
           return(0);
          }
So, following this step-by-step procedure, we have written our Expert Advisor...
Step 3 – Assembling the resulting code of the programme
Let's open the Expert Advisor settings (using a button or a line in the "Properties..." menu. We are offered a window in which we have to define the external settings of the working parameters:


Let's assemble all the code from the previous section:
//+------------------------------------------------------------------+ //| MACD Sample.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ extern double TakeProfit = 50; extern double Lots = 0.1; extern double TrailingStop = 30; extern double MACDOpenLevel=3; extern double MACDCloseLevel=2; extern double MATrendPeriod=26; //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int start() { double MacdCurrent, MacdPrevious, SignalCurrent; double SignalPrevious, MaCurrent, MaPrevious; int cnt, ticket, total; // initial data checks // it is important to make sure that the expert works with a normal // chart and the user did not make any mistakes setting external // variables (Lots, StopLoss, TakeProfit, // TrailingStop) in our case, we check TakeProfit // on a chart of less than 100 bars if(Bars<100) { Print("bars less than 100"); return(0); } if(TakeProfit<10) { Print("TakeProfit less than 10"); return(0); // check TakeProfit } // to simplify the coding and speed up access // data are put into internal variables MacdCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0); MacdPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1); SignalCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0); SignalPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1); MaCurrent=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,0); MaPrevious=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1); total=OrdersTotal(); if(total<1) { // no opened orders identified if(AccountFreeMargin()<(1000*Lots)) { Print("We have no money. Free Margin = ", AccountFreeMargin()); return(0); } // check for long position (BUY) possibility if(MacdCurrent<0 && MacdCurrent>SignalCurrent && MacdPrevious<SignalPrevious && MathAbs(MacdCurrent)>(MACDOpenLevel*Point) && MaCurrent>MaPrevious) { ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,"macd sample",16384,0,Green); if(ticket>0) { if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice()); } else Print("Error opening BUY order : ",GetLastError()); return(0); } // check for short position (SELL) possibility if(MacdCurrent>0 && MacdCurrent<SignalCurrent && MacdPrevious>SignalPrevious && MacdCurrent>(MACDOpenLevel*Point) && MaCurrent<MaPrevious) { ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,"macd sample",16384,0,Red); if(ticket>0) { if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice()); } else Print("Error opening SELL order : ",GetLastError()); return(0); } return(0); } // it is important to enter the market correctly, // but it is more important to exit it correctly... for(cnt=0;cnt<total;cnt++) { OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES); if(OrderType()<=OP_SELL && // check for opened position OrderSymbol()==Symbol()) // check for symbol { if(OrderType()==OP_BUY) // long position is opened { // should it be closed? if(MacdCurrent>0 && MacdCurrent<SignalCurrent && MacdPrevious>SignalPrevious && MacdCurrent>(MACDCloseLevel*Point)) { OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position return(0); // exit } // check for trailing stop if(TrailingStop>0) { if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()<Bid-Point*TrailingStop) { OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green); return(0); } } } } else // go to short position { // should it be closed? if(MacdCurrent<0 && MacdCurrent>SignalCurrent && MacdPrevious<SignalPrevious && MathAbs(MacdCurrent)>(MACDCloseLevel*Point)) { OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position return(0); // exit } // check for trailing stop if(TrailingStop>0) { if((OrderOpenPrice()-Ask)>(Point*TrailingStop)) { if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0)) { OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red); return(0); } } } } } } return(0); } // the end.


Programming Language for Information Processing

A. Sample Programming Problems


   Whenever I’m TA for a introductory CS class where students learn some programming language, I have trouble coming up with good exercises. Problems from Project Euler and the like are usually much too difficult for beginners, especially if they don’t have a strong background in mathematics.

   This page is a collection of progressively more difficult exercises that are suitable for people who just started learning. It will be extended as I come up with new exercises. Except for the GUI questions, exercises are generally algorithmic and should be solvable without learning any libraries. The difficulty of the exercises of course somewhat depends on the programming language you use. The List exercises for example are more complicated in languages like C that don’t have build-in support for lists.
I suppose they are also useful, although much easier, whenever an experienced person wants to learn a new language.

Intermediate
  1. Write a program that outputs all possibilities to put + or - or nothing between the numbers 1,2,…,9 (in this order) such that the result is 100. For example 1 + 2 + 3 - 4 + 5 + 6 + 78 + 9 = 100.
  2. Write a program that takes the duration of a year (in fractional days) for an imaginary planet as an input and produces a leap-year rule that minimizes the difference to the planet’s solar year.
  3. Implement a datastructure for graphs that allows modification (insertion, deletion). It should be possible to store values at edges and nodes. It might be easiest to use a dictionary of (node, edgelist) to do this.
  4. Write a function that generates a DOT representation of a graph.
  5. Write a program that automatically generates essays for you.
    1. Using a sample text, create a directed (multi-)graph where the words of a text are nodes and there is a directed edge between u and v if u is followed by v in your sample text. Multiple occurrences lead to multiple edges.
    2. Do a random walk on this graph: Starting from an arbitrary node choose a random successor. If no successor exists, choose another random node.
  6. Write a program that automatically converts English text to Morse code and vice versa.
  7. Write a program that finds the longest palindromic substring of a given string. Try to be as efficient as possible!
 Advanced
  1. Given two strings, write a program that efficiently finds the longest common subsequence.
  2. Given an array with numbers, write a program that efficiently answers queries of the form: “Which is the nearest larger value for the number at position i?”, where distance is the difference in array indices. For example in the array [1,4,3,2,5,7], the nearest larger value for 4 is 5. After linear time preprocessing you should be able to answer queries in constant time.
  3. Given two strings, write a program that outputs the shortest sequence of character insertions and deletions that turn one string into the other.
  4. Write a function that multiplies two matrices together. Make it as efficient as you can and compare the performance to a polished linear algebra library for your language. You might want to read about Strassen’s algorithm and the effects CPU caches have. Try out different matrix layouts and see what happens.
  5. Given a set of d-dimensional rectangular boxes, write a program that computes the volume of their union. Start with 2D and work your way up.

B. C language elements


    The C Character Set
C uses the uppercase English alphabets A to Z, the lowercase letters a to z, the digits 0 to 9, and certain special characters as building blocks to form basic program elements viz. constants, variables, operators, expressions and statements.
The special characters are listed below:
!*+\"<
#(=|{>
%)~;}/
^-[:,?
&-]'.(blank)

Most versions of the language also allow some other characters, such as @ and $, to be included within strings and comments.
In addition certain combinations of these characters, such as '\b', '\n' and '\t', are used to represent special condition such as backspace, newline and horizontal tab, respectively. These character combinations are known as escape sequences.

   Identifiers and Keywords
Identifiers are names given to various items in the program, such as variables, functions and arrays. An identifier consists of letters and digits, in any order, except that the first character must be a letter. Both upper and lowercase letters are permitted. Upper and lowercase letters are however not interchangeable (i.e., an uppercase letter is not equivalent to the corresponding lowercase letter). The underscore character (_) can also be included, and it is treated as a letter. Keywords like if, else, int, float, etc., have special meaning and they cannot be used as identifier names.
The following are examples of valid identifier names: A, ab123, velocity, stud_name, circumference, Average, TOTAL
The following names are not valid identifiers:
1st- the first character must be a letter
"Jamshedpur"- illegal characters (")
stud-name- illegal character (-)
stud name- illegal character (blank space)

Although an identifier can be arbitrarily long, most implementations recognize typically 31 characters. There are some implementations, which recognize only eight characters. The ANSI standard recognizes 31 characters. If a system recognizes only 8 characters and if you use a variable name with more than 8 characters, only the first 8 characters will be taken, the rest will be ignored. Thus, average_of_numbers and average_ will both be recognized as average_. It is therefore safer to try and use short meaningful names for your identifiers.

Exercise:
Identify which of the following are valid identifiers.
(a)stud 1(d)switch(g) Average of Numbers(j) 123-45-678
(b)1stud(e)%calc(h) Average_of_Numbers
(c)stud_1(f)_x(i) Average-of-Numbers

Data Types and Sizes

There are only few basic data types in C. These are listed in the table below:
Data typeDescriptionSizeRange
charsingle character1 byte 0 - 255
intinteger number4 bytes-2147483648 to 2147483647
floatsingle precision floating point number (number containing fraction & or an exponent)4 bytes3.4E-38 to 3.4E+38
doubledouble precision floating point number8 bytes1.7E-308 to 1.7E+308
The list of data types can be increased by using the data type qualifiers such as - short, long, and unsigned. For example, an integer quantity can be defined as long, short, signed or unsigned integer. The memory requirement of an integer data varies depending on the compilers used. The qualified basic data types and their sizes are shown in table below.
Data typeSizeRange
short int2 bytes-32768 to 32767
long int4 bytes-2147483648 to 2147483647
unsigned short int2 bytes0 to 65535
unsigned int4 bytes0 to 4294967295
unsigned long int4 bytes0 to 4294967295
long double (extended precision)8 bytes1.7E-308 to1.7E+308

Note that the qualifier unsigned can be used along with the qualifiers short and long. The unsigned int occupies the same memory space as an ordinary int but differs on the possible content of the left-most bit. In case of an ordinary int it is reserved for sign (sign bit), but all the bits in an unsigned int are used for determining the magnitude of the integer quantity.
The char type is used to represent individual characters, and occupies one byte of memory. Each character has an equivalent integer representation (since each stores internally the ASCII value for the corresponding character). So char variables or constants can be used as integer data in arithmetic expressions.
The data objects to be manipulated in a C program are classified as variables and constants. The type of all the variables to be used in the program must be declared before they can be used. The operations that can be performed on the data objects are specified by a set of operators. Expressions used in a program combine the variables, constants and operators to produce new values.

Constants

The constants in C can be classified into four categories namely integer constants, floating point constants, character constants and string constants.
A character constant is written as for example - 'A' (always enclosed in single quotes).
Examples of string constants are - "Jamshedpur", "A", etc. Note that a string constant is always enclosed within double quotes.
A normal integer constant is written as 1234.
A long int is recognized by the presence of L (uppercase or lowercase) at the end of the constant, e.g. 2748723L.
The suffix u or U signifies the int to be an unsigned one.
The UL or ul at the end indicates the int quantity is of unsigned long type
Floating point constants contain a decimal point (167.903) or an exponent (1e-2) or both. Their type is double unless suffixed. The suffix of f or F indicates float; 1 or L indicates long double.
C also supports octal and hexadecimal data. The value of an integer data can be specified in either octal or hexadecimal form. A hexadecimal constant must begin with 0x or 0X, a leading 0 indicates the octal representation. Octal and hexadecimal constants may also be followed by U to indicate unsigned or L to determine long.
The number 0x2A5 is an example of a hexadecimal number. Internally the number is represented by the following bit patterns,
0x2A5 = 0010 1010 0101 = 2 * 162 + 10 * 161 + 5 * 160 = 677
        ---- ---- ----
          2    A   5
The number 677 is the decimal equivalent of the number 0x2A5.

Example of an octal number can be 0347. To represent each digit of an octal number in the form of binary, we need maximum of three bits since the last digit in the octal number system is 7.
0347 = 011 100 111 = 3 * 82 + 4 * 81 + 7 * 80 = 231 (in decimal)
       --- --- ---
        3   4   7

In numeric constants e.g. integer or floating point constants, blanks and any non-numeric characters cannot be included. The range of these constants will be limited by the maximum and minimum bounds (usually machine dependent).
A character constant is a single character enclosed in apostrophes such as 'A'. Such a constant is internally treated as an integer e.g. 'A' corresponds to the integer 65 (also known as its ASCII value). The ASCII value of 'a' (small) is 97. Hence character constants can participate in a numeric calculation just like any other integer, moreover, they also can be used for comparing with other character constants. Some character constants are of non-printing type which can be expressed by a combination of a back-slash (\) and a character. They are known as escape sequences. Each of them represents a single character even though they are written in terms of two or more characters.
Commonly used escape sequences are listed below:
CharacterEscape SequenceASCII Value
Bell\a007
Backspace\b008
Null\0000
Newline\n010
Carriage return\r013
Vertical tab\v011
Horizontal tab\t009
Form feed\f012

Exercises:
Identify which of the following numerical values are valid constants. If a constant is valid, specify whether it is integer or real. Also, specify the base for each valid integer constant.
(a)0.7b)39,634c)16.3e18d)16.3e-18
(e)123456789f)123456789lg)0.3E+0.4h)0.3E4
(i)0412j)018ACFk)0xABCDEl)0x97e334

Which of the following are valid character constants?
(a)'a'(b)'/n'(c)'F'(d)'\0492'
(e)'x'(f)'\\'(g)'\0'(h)'\n'
(i)'\b'(j)'\x-y-'




Which of the following are valid string constants?
(a)'9:25 A.M.'
(b)"Blue, Green and Indigo"
(c)"Name:
(d)"Section 4 (Next \'d')"
(e)"1.6e-18"
(f)"JAMSHEDPUR BR 831 001"
(g)"The Station master announced, "Down Geetanjali express is running late"

Symbolic Constants

Constants which play crucial roles in a program can be made more meaningful by assigning them appropriate names to make the program more readable and easily changeable. These constants are called symbolic constants and are defined as follows.
Examples:
#define PI 3.141593
#define TRUE 1
#define PROMPT "Enter Your Name :"
PI, TRUE and PROMPT are symbolic constants, so they do not appear in the declaration. #define is a preprocessor directive like #include. The salient feature of a symbolic constant is that the value assigned to a symbolic constant cannot be changed (unlike variables) subsequently in the program.
Exercise:
Write an appropriate definition for each of the following symbolic constants, as it would appear within a C program:

ConstantText
(a)AMOUNT-75
(b)EPSILON0.00001
(c)BIGIN{

END}
(d)FIRSTNAME"Sanjay"
(e)ENDOLIN'\n'
(f)COST"Rs. 125.75"

Variable Declaration in C

In a C program all variables must be declared before they are used. A declaration determines the type of the data, and contains a list of one or more variables having the same type.
Example:
intcount, index;
charflag, text[80];
short inta,b;
unsigned intp;
doubled;

A variable can be initialized with values at the time of declaration.
Example:
intc = 5;
charreply = 'Y';
doubled = 4.64386237445675;
charstate[] = "ANDHRA PRADESH";
floateps = 1.0e-5;

Exercises:
Write appropriate declaration for each group of variables and character array (strings):
(a)Integer variables: x, y
(b)Integer variable: count

Unsigned integer variable: employee no

Double-precision variables: net sales, tax, profit
(c)Character variables: first name, last name
(d)70 element character array: message

Write appropriate declaration and assign the given initial values to each group of variables and array:
(a)Floating-point variables: x = -9.5, y = 1.0004

Integer variables: a = 734, b = 49, c = -63

Character variables: c1 = 'a', c2 = '$'
(b)Double-precision variable: d1 = 3.94 * 10-12, d2 = -9.89 * 107

Integer variable: i = 437 (octal), h = 6AFF (hexadecimal)
(c)Long integer variable: large = 123456789

Double-precision variables: d = 0.6666666

Character variable: eol = newline character
(d)One-dimensional character array: message = "OVERFLOW"






 

Lunes, Setyembre 29, 2014

Elements of Programming Language

A. Perspective of programming languages 

    
Almost thirty years ago,
a noted computer scientist (1) remarked that it was
unfortunate that real computers had to be us
ed in teaching computer science. Although
many in the audience may have viewed this as
a rather radical position at the time, it has
proven to be an insightful commentary on many
of our efforts to design and deliver courses
in the discipline. In fact, the premise probably
should be broadened to include software as
well as hardware. Actual computing systems,
hardware as well as software, often swamp
the learner in a sea of minutia in which basic concepts are at least obscured if not
completely lost. While there are
difficulties in using real system
s in courses at all levels, it
appears that some of the greatest problems ma
y be found at the introductory level. In
particular, achieving consensus in the choice of a programming language (or none at all!) for
CS1 has proven to be elusive. With
Curriculum 2001
now in the works, it is particularly
timely that experience with
this course be reviewed.
FROM FORTRAN TO JAVA AND BEYOND
In the early seventies, introductory
courses using FORTRAN were quite common.
After all, if only half in jest, it was observed that "real programmers" would use nothing
else. BASIC was also popular at that time
and was making inroads where time sharing was
available, and the presentations were directed
to more diverse audiences - perhaps not real
programmers. By the end of the decade (70's)
, however, Pascal had captured the market.
Here was a language simple, comp
act, and consistent which had
been designed especially for
education. It should be an optimum choice. Textbooks and materials using Pascal
flourished. Many instructors were drawn to Pascal at all levels, but it was particularly
popular in the introductory course. The Educational Testing Service (ETS) adopted Pascal
for its Advanced Placement Examination. In fairness, it should be noted that there were
and continue to be a number of other voices. Despite its heritage and acknowledged
simplicity, Pascal can be viewed as overly comp
lex in terms of syntax when compared with
languages such as LISP (or Scheme).
It can be argued that unlike Pascal,
Scheme has little if any syntax, and its
semantics are based on sound mathematical principles (2). It also has become apparent that
Pascal is not the
lingua francaof professional programmers.
Why should we teach something
which may be irrelevant? When
objects became important, efforts were made to update
and enhance Pascal. Unfortunately, these efforts have resulted
in more arcane systems and
have been met with a rather tepid response.
Moving the language of the introductory course to C or more likely to C++ seemed
imminently logical in the nineties. Almost immediately, a large number of introductory texts
on C and C++ appeared, and the agendas of national meetings were filled with reports on the
more or less successful implementation of C
and/or C++ in CS1. It seemed that no
respectable computer science department could ignore the tida
l wave. ETS announced that
3
the Advanced Placement Exam would eventually
use C++. There is, however, a disturbing
fact that became painfully apparent to instructors as they actually tried to present C++ and
objects in their courses. Despite its highly
publicized advantages
, C++ is not a simple
language. Also, it is now a generally accepted
as an undesirable practice to simply translate
code segments in an introductory
text, perhaps originally written in Pascal, into C++.
This lesson may not have been fully learned in
that several CS1 texts
have attempted to do
exactly this and have appeared in several flavors (3).
The pitfalls of C for beginning students
have been acknowledged for some time.
The programming style of C encourages short,
pithy code, replete with multiple levels of
indirection. Novices also find
the standard I/O facilities of
C largely impenetrable. When
using C++ at the introductory level, these problems remain, although the I/O difficulties
are somewhat alleviated, even a cursory treatment of object principles has proven to be a
formidable task. Most introductory courses using C++ are content to introduce the concept
of objects and illustrate their use, while
reserving object creation for a later course.
For schools determined to present a "pure"
view of modularization, object-oriented
programming, and good software
engineering methodology in general, the emergence of ADA
in the 1980's was very welcome. However, remains a favorite of only a relatively select
small group of schools.
The C++ craze, however, may have been short-lived. The emergence of the Internet
must be acknowledged and reflected in our courses. Recent conferences have produced an
impressive number of papers on the use of Java at the introductory level. C++ is often
represented as a better C. In that sense, Java
may be viewed as a (slightly) simpler version
of C++. While its overall utility for Internet
programming may be somewhat specious, Java
does project the aura of modern practice
and with the implication that jobs may be
available for the cognoscenti. Possibly for these reasons, courses offered using Java tend
to be very popular with students, even with those who are
not computer science majors.
The size of this audience is hard to ignore.
If presenting several introductory courses isn't
feasible, can the goals of CS 1 be met using
Java or maybe Visual Basic? Or, for that
matter, should the selection of the programming language be a prime consideration?
At Brooklyn College and other schools it is
now common to include the teaching of
some HTML and Java Scripts in the breadth first course. This illustrates that language
choices have become somewhat market and demand driven -- rather than purely based on
academic issues. Furthermore HTML is a relatively simple language to learn and use.
From a historical perspective it appears that very satisfactory courses have been
developed with a wide variety of programming
languages. The determining factor for which
way the pendulum swings in terms of a language's adoption for CS1 may be image and
marketing factors, which certainly cannot be ignored. If an introductory course is carefully
designed to meet its desired outcomes, it
may not matter how we elect to express our
algorithms. Although this may
not be easy to accept, it may
to be perfectly defensible to
use whatever language the market dictates to
ply our trade. Academic integrity need not
be compromised by pursuing this rationale.


B. Language processors


     language processor, we mean a program that processes programs written in a programming language (source language). All or part of a language processor is a language translator, which translates the program from the source language into machine code, assembly language, or some other language. The machine code can be for an actual computer or for a virtual (hypothetical) computer. If it is for a virtual computer, then a simulator for the virtual computer is needed in order to execute the translated program.

    If a language processor is a translator that produces machine or assembly code as output (in object code or executable code) then it is called a compiler. If the language processor executes the translated program (output from the translator) then it is called an interpreter.


C. Data-level Structure 

In computer science a level set data structure is designed to represent discretely sampled dynamic level sets functions.
A common use of this form of data structure is in efficient image rendering. The underlying method constructs a signed distance field that extends from the boundary, and can be used to solve the motion of the boundary in this field.


Narrow band

The narrow band level set method, introduced in 1995 by Adalsteinsson and Sethian,[2] restricted most computations to a thin band of active voxels immediately surrounding the interface, thus reducing the time complexity in three dimensions to O(n^2) for most operations. Periodic updates of the narrowband structure, to rebuild the list of active voxels, were required which entailed an O(n^3) operation in which voxels over the entire volume were accessed. The storage complexity for this narrowband scheme was still O(n^3). Differential constructions over the narrow band domain edge require careful interpolation and domain alteration schemes to stabilise the solution.[3]

Sparse field

This O(n^3) time complexity was eliminated in the approximate "sparse field" level set method introduced by Whitaker in 1998.[4] The sparse field level set method employs a set of linked lists to track the active voxels around the interface. This allows incremental extension of the active region as needed without incurring any significant overhead. While consistently O(n^2) efficient in time, O(n^3) storage space is still required by the sparse field level set method. See [5] for implementation details.

Sparse block grid

The sparse block grid method, introduced by Bridson in 2003,[6] divides the entire bounding volume of size n^3 into small cubic blocks of m^3 voxels each. A coarse grid of size (n/m
)^3 then stores pointers only to those blocks that intersect the narrow band of the level set. Block allocation and deallocation occur as the surface propagates to accommodate to the deformations. This method has a suboptimal storage complexity of O\left((nm)3 + m^3n^2\right), but retains the constant time access inherent to dense grids.

Octree

The octree level set method, introduced by Strain in 1999 [7] and refined by Losasso, Gibou and Fedkiw,[8] and more recently by Min and Gibou[9] uses a tree of nested cubes of which the leaf nodes contain signed distance values. Octree level sets currently require uniform refinement along the interface (i.e. the narrow band) in order to obtain sufficient precision. This representation is efficient in terms of storage, O(n^2), and relatively efficient in terms of access queries, O(\log\, n). An advantage of the level method on octree data structures is that one can solve the partial differential equations associated with typical free boundary problems that use the level set method. The CASL research group[10] has developed this line of work in computational materials, computational fluid dynamics, electrokinetics, image guided surgery and controls.

Run-length encoded

The run-length encoding (RLE) level set method, introduced in 2004,[11] applies the RLE scheme to compress regions away from the narrow band to just their sign representation while storing with full precision the narrow band. The sequential traversal of the narrow band is optimal and storage efficiency is further improved over the octree level set. The addition of an acceleration lookup table allows for fast O(\log r) random access, where r is the number of runs per cross section. Additional efficiency is gained by applying the RLE scheme in a dimensional recursive fashion, a technique introduced by Nielsen & Museth's similar DT-Grid.[12]

Hash Table Local Level Set

The Hash Table Local Level Set method, introduced in 2012 by Brun, Guittet and Gibou,[13] only computes the level set data in a band around the interface, as in the Narrow Band Level-Set Method, but also only stores the data in that same band. A hash table data structure is used, which provides an O(1) access to the data. However, the authors conclude that their method, while being easier to implement, performs worse than a quadtree implementation. They find that
as it is, [...] a quadtree data structure seems more adapted than the hash table data structure for level-set algorithms.
Three main reasons for worse efficiency are listed:
  1. to obtain accurate results, a rather large band is required close to the interface, which counterbalances the absence of grid nodes far from the interface;
  2. the performances are deteriorated by extrapolation procedures on the outer edges of the local grid and
  3. the width of the band restricts the time step and slows down the method.



D. Program-level Structure

The best way to learn a programming language is by writing programs. Typically, the first program beginners write is a program called "Hello World", which simply prints "Hello World" to your computer screen. Although it is very simple, it contains all the fundamental components C++ programs have:


1
2
3
4
5
6
7
// my first program in C++
#include <iostream>

int main()
{
  std::cout << "Hello World!";
}
Hello World!


Let's examine this program line by line:


Line 1: // my first program in C++
Two slash signs indicate that the rest of the line is a comment inserted by the programmer but which has no effect on the behavior of the program. Programmers use them to include short explanations or observations concerning the code or program. In this case, it is a brief introductory description of the program.

Line 2: #include <iostream>
Lines beginning with a hash sign (#) are directives read and interpreted by what is known as the preprocessor. They are special lines interpreted before the compilation of the program itself begins. In this case, the directive #include <iostream>, instructs the preprocessor to include a section of standard C++ code, known as header iostream, that allows to perform standard input and output operations, such as writing the output of this program (Hello World) to the screen.

Line 3: A blank line.
Blank lines have no effect on a program. They simply improve readability of the code.

Line 4: int main ()
This line initiates the declaration of a function. Essentially, a function is a group of code statements which are given a name: in this case, this gives the name "main" to the group of code statements that follow. Functions will be discussed in detail in a later chapter, but essentially, their definition is introduced with a succession of a type (int), a name (main) and a pair of parentheses (()), optionally including parameters.

The function named main is a special function in all C++ programs; it is the function called when the program is run. The execution of all C++ programs begins with the main function, regardless of where the function is actually located within the code.

Lines 5 and 7: { and }
The open brace ({) at line 5 indicates the beginning of main's function definition, and the closing brace (}) at line 7, indicates its end. Everything between these braces is the function's body that defines what happens when main is called. All functions use braces to indicate the beginning and end of their definitions.

Line 6: std::cout << "Hello World!";
This line is a C++ statement. A statement is an expression that can actually produce some effect. It is the meat of a program, specifying its actual behavior. Statements are executed in the same order that they appear within a function's body.

This statement has three parts: First, std::cout, which identifies the standard character output device (usually, this is the computer screen). Second, the insertion operator (<<), which indicates that what follows is inserted into std::cout. Finally, a sentence within quotes ("Hello world!"), is the content inserted into the standard output.

Notice that the statement ends with a semicolon (;). This character marks the end of the statement, just as the period ends a sentence in English. All C++ statements must end with a semicolon character. One of the most common syntax errors in C++ is forgetting to end a statement with a semicolon.




E. Control-level Structure

Control Structure
• A
control structure
is a control statement
and the statements whose execution it
controls
• Design question
– Should a control structure have multiple entries?
8-6
Selection Statements
• A
selection statement
provides the means
of choosing between two or more execution
paths in a program
• Two general categories:
– Two-way selectors
– Multiple-way selectors
I
100?
S = S +I
True
False
Print
...
4
8-7
Two-Way Selection Statements
• General form:
if
control_expression
then
clause
else
clause
• Design Issues:
– What is the form and type of the control
expression?
– How are the
then
and
else
clauses
specified?
– How should the meaning of nested selectors be
specified?
8-8
The Control Expression
• If the
then
reserved word is not used
– control expressions are specified in parentheses
• If the
then
reserved word is used
– Less need for parentheses
• In C89, arithmetic expressions were used
as control expressions
• In Ada, Java, Ruby, and C#, only
Boolean
expressions
can be used
5
8-9
Nesting Selectors
• Java example
if (sum == 0)
if (count == 0)
result = 0;
else result = 1;
• Which
if
gets the
else
?
• Java's static semantics rule:
else
matches
with the nearest
if
In Java
8-10
Nesting Selectors (continued)
•To force an alternative semantics,
compound statements may be used:
if (sum == 0) {
if (count == 0)
result = 0;
}
else result = 1;
• The above solution is used in C, C++, and
C#
6
8-11
Nesting Selectors in Perl
• Perl requires that all
then
and
else clauses
to be compound, so it does not have the
problem
if (sum == 0) {
if (count == 0) {
result = 0;
}
} else {
result = 1;
}
if (sum == 0) {
if (count == 0) {
result = 0;
}
else {
result = 1;
}
}
8-12
Using a Special Word Also Resolves the
Problem...
• In Ruby
if
sum == 0
then
if
count == 0
then
result = 0
else
result = 1
end
end
if
sum == 0
then
if
count = 0
then
result = 0
end
else
result = 1
end
if
end
就像左右括弧般配對
7
8-13
Multiple-Way Selection Statements
• Allow the selection of one of any number
of statements or statement groups
• Design Issues:
1. What is the form and type of the control expression?
2. How are the selectable segments specified?
3. Is execution flow through the structure restricted
to include just a single selectable segment?
4. How are the case values specified?
5. What is done about unrepresented expression
values?
8-14
Multiple-Way Selection: Examples
•C’s
switch
statement
switch
(expression) {
case
const_expr_1: stmt_1;
...
case
const_expr_n: stmt_n;
[
default
: stmt_n+1]
}
8
8-15
Design Choices for C’s
switch
1. Control expression and constant expressions
are some integer type
2. Selectable segments can be statement
sequences, blocks, or compound statements
3. Any number of segments can be executed in
one execution of the construct (there is no
implicit branch at the end of selectable
segments)
4. default
clause is for unrepresented values (if
there is no
default
, the whole statement does
nothing)
8-16
In C, Control May Flow More Than One
Selectable Codes...
switch
(index) {
case
1:
case
3:
odd += 1;
sumodd += index;
case
2:
case
4:
even += 1;
sumeven += index;
default
: printf(“Error in switch”);
}
9
8-17
The Ada
case
Statement
case
expression
is
when
choice list => stmt_sequence;
...
when
choice list => stmt_sequence;
[
when others
=> stmt_sequence;]
end case
;
• once a stmt_sequence execution is
completed, control is passed to the first
statement after the
case
statement
• More reliable than C’s
switch
8-18
More On The Ada
case
Statement
• choice list
can include:
– Subranges e.g.,
10..15
– Boolean OR operators. e.g.,
1..5
|
7
|
15..20
• The choice lists must be
exhaustive
– Often accomplished with
when others
clause
– This makes it more reliable
10
8-19
Multiple-Way Selection Using
else-if
• Multiple Selectors can appear as direct
extensions to two-way selectors, using
else-if
clauses, for example in Ada:
if
...
then
...
elsif
...
then
...
elsif
...
then
...
else
...
end if
8-20
Iterative Statements
• The repeated execution of a statement or
compound statement is accomplished
either by iteration
or recursion
• General design issues for iteration control
statements:
1. How is iteration controlled?
2. Where is the control mechanism in the loop?
11
8-21
Counter-Controlled Loops
• A counting iterative statement has a
loop variable
, and a means of
specifying the
initial
and
terminal
,
and
stepsize
values
• the
initial
and
terminal
, and
stepsize
specifications of a loop are called the
loop parameters
8-22
Design Issues of Counter-Controlled
Loops
1.What are the type and scope of the loop
variable?
2.What is the value of the loop variable at
loop termination?
3.Should it be legal for the loop variable or
loop parameters to be changed in the loop
body, and if so, does the change affect loop
control?
4.Should the loop parameters be evaluated
only once, or once for every iteration?
12
8-23
Iterative Statements: FORTRAN 95
DO
label var = start, finish [, stepsize]
• Stepsize can be any value but zero
• Parameters can be expressions
• Design choices:
1. Loop variable must be
INTEGER
2. Loop variable always has its
last value
3. Loop parameters are evaluated only once
4. The loop variable cannot be changed in the
loop, but the parameters can; because they are
evaluated only once, it does not affect loop
control
8-24
FORTRAN 95’s
Do
Example
a = 1
DO
10 Index = a, 10
...
a = a + 1
10 Continue
The value of
Index
after normal termination of
the loop is 11
Loop parameter can be changed in the loop,
but it does not affect loop control
value can not
be changed in
the loop
13
8-25
Iterative Statements: FORTRAN 95
• FORTRAN 95 : a second form:
[name:]
DO
variable = initial, terminal [,stepsize]
...
END DO
[name]
DO
Count = 1, 10
...
End Do
8-26
Iterative Statements: Ada
for
var
in
[
reverse
] discrete_range
loop
...
end loop
• discrete_range
is a sub-range of an
integer or enumeration type
• Scope of the loop variable is
the range of
the loop
• Loop variable is implicitly undeclared after
loop termination
14
8-27
Ada’s
for
Example
Count: Float := 1.35;
for
Count
in
1..10
loop
Sum := Sum + Count;
end loop
Count
is a floating
point number with
Initial value 1.35
Upon loop termination,
Count
is still
Float
type with the value of 1.35
Loop variable
Count
cannot be
assigned a value in the loop body
It is not accessible
in the loop body
8-28
Iterative Statements: C
for
(expr_1; expr_2; expr_3)
loop body
• The expressions can be whole statements, or even
statement sequences, with the statements
separated by commas
– The value of a multiple-statement expression is the value
of the last statement in the expression
• There is no explicit loop variable
• Everything can be changed in the loop
• The first expression is evaluated once, but the
other two are evaluated with each iteration
15
8-29
C’s
for
Example
for
(count1 = 0, count2 = 1.0;
count1 <= 10 && count2 <= 100.0;
sum = ++ count1 + count2, count2 *= 2.5);
Need not have a loop body
for
(a = 100, b = 1; a < b; a++, b *= 2);
No explicit loop variable
8-30
Iterative Statements: Examples
• C++ differs from C in two ways:
1. The control expression
can also be
Boolean
2. The initial expression can include variable
definitions (scope is from the definition to the
end of the loop body)
• Java and C#
– Differs from C++ in that the control
expression
must be
Boolean
for
(
int
count = 0; count < len; count++) {...}
16
8-31
Iterative Statements: Logically
-
Controlled Loops
• Repetition control is based on a Boolean
• Design issues:
– Pre-test or post-test?
– Should the logically controlled loop be a
special form of a counting loop or a separate
statement?
• General forms:
Pre-test
while
(ctrl_expr)
loop body
Post-test
do
loop body
while
(ctrl_expr)
8-32
Logically-Controlled Loops: Examples
• C and C++ have both pre-test and post-
test logical loop statements, but the
control expression for the post-test
version is treated just like in the pre-test
case
(
while-do
and
do-while
)
• Java is like C, except the control
expression must be Boolean (and the body
can only be entered at the beginning --
Java has no
goto
)
17
8-33
Logically-Controlled Loops: Examples
• Ada has a pretest version, but no post-test
• FORTRAN 77 and 90 have neither
• Perl has two pre-test logical loops,
while
and
until
, but no post-test logical loop
8-34
User-Located Loop Control Mechanisms
• Sometimes it is convenient for the
programmers to decide a location for loop
control (other than top or bottom of the
loop)
• Simple design for single loops (e.g.,
break
)
• Design issues for nested loops
1. Should the conditional be a part of the exit?
2. Should only one loop body be exited, or can
enclosing loops also be exited?
18
8-35
User-Located Loop Control Mechanisms
break
and
continue
• C , C++, Ruby, and C# have unconditional
unlabeled exits (
break
)
• Unconditional; for any loop or
switch
; one
level only
• Java and Perl have unconditional labeled
break
statement: control transfers to the
label
• An alternative:
continue
statement; it
skips the remainder of this iteration, but
does not exit the loop
8-36
break
and
continue
for
(row = 0; row < numRows; row++)
for
(col = 0; col < numCols; col++) {
sum += mat[row][col];
if
(sum > 1000.0) {
break
;
}
for
(x = 1; x <= 10; x++) {
if
(x == 5) {
continue
;
}
printf("%d ", x);
}
In Java
19
8-37
A Break to the Outer Loop in Java
OuterLoop:
for
(row = 0; row < numRows; row++)
for
(col = 0; col < numCols; col++) {
sum += mat[row][col];
if
(sum > 1000.0)
break
outerLoop;
}
8-38
Iterative Statements: Iteration Based on
Data Structures
• Number of elements of in a data structure control
loop iteration
• Control mechanism is a call to an
iterator
function
that returns the next element in some chosen
order, if there is one; else loop is terminated
• C's
for
can be used to build a user-defined
iterator:
for
(p=root; p!=NULL; traverse(p)){
}
20
8-39
Iterative Statements: Iteration Based on
Data Structures (continued)
• C#’s
foreach
statement iterates on the
elements of arrays and other collections:
Strings[] = strList = {“Bob”, “Carol”, “Ted”};
foreach
(Strings name in strList)
Console.WriteLine (“Name: {0}”, name);
• The notation {0} indicates the position in
the string to be displayed
8-40
Unconditional Branching
• Transfers execution control to a specified place in
the program
• Represented one of the most heated debates in
1960’s and 1970’s
• Well-known mechanism:
goto
statement
• Major concern: Readability
• Some languages do not support
goto
statement (e.g.,
Module-2 and Java)
• C# offers
goto
statement (can be used in
switch
statements)
• Loop exit statements are restricted and somewhat
camouflaged (
偽裝的
)
goto
’s
Selection Guarded Command:
Illustrated
8-44
Loop Guarded Command
Form
do
<Boolean> -> <statement>
[]
<Boolean> -> <statement>
...
[]
<Boolean> -> <statement>
od
• Semantics: for each iteration
– Evaluate all Boolean expressions
– If more than one are true, choose one non-
deterministically; then start loop again
– If none are true, exit loop
23
8-45
Loop Guarded Command: Illustrated
8-46
Guarded Commands: Rationale
• Connection between control statements
and program verification is intimate (
親近的
)
• Verification is impossible with
goto
statements
• Verification is possible with only selection
and logical pretest loops
• Verification is relatively simple with only
guarded commands
24
8-47
Conclusion
• Variety of statement-level structures
• Choice of control statements beyond
selection and logical pretest loops is a
trade-off between language size and
writability
• Functional and logic programming
languages are quite different control
structures