
\documentclass[11pt]{article}
%\usepackage{mydraft}

\usepackage{TRmydraft}
\usepackage{wmff}
\usepackage{graphicx}
%\usepackage{graphalgb}

\pagestyle{myheadings}
\markright{}

\begin{document}

\reptitle{{\bf Object Oriented Programming}}
\author{Jos\'e M. Garrido}

\date{December, 2016}

\subtitle{{\bf Using OOSimL}}
\subsubtitle{An Overview - Part 2}
%\subsubtitle{Technical Report TR-CSIS-OOPsimL (Part 2)}

\authoraffil{Department of Computer Science} 
 
%
%\halftitlepage
%
\titlepage

\mdraft
%\maketitle
%\newpage
%\tableofcontents
%\newpage


%\include{ch04} % Functions
\section{Function Implementation}

A program is normally decomposed into classes, and classes are divided into methods or functions. 

As mentioned previously, data\index{data} declared within a function is known only to that function---the scope of the data is {\em local\/}\index{local data} to the function. The data in a function has a limited lifetime, it only exists during execution of the function. 

The name of the function is used when it is called or invoked by some other function. The relevant documentation of the function is described in the {\bf description} paragraph, which ends with a star-slash (*/). The OOSimL statements for defining a function are:

%\newpage

\vspace{0.1in}
%\begin{quote}
{\tt %\small 
\begin{algorithm}
{\bf description}
\ \ \ . . .
\ \ */
{\bf function} $\langle${\em function\_name} $\rangle$ {\bf is}
\ \ {\bf constants}
\ \ \ \ . . .
\ \ {\bf variables}
\ \ \ \ . . .
\ \ {\bf object references}
\ \ \ \ . . .
\ \ {\bf begin}
\ \ \ \ . . . [instructions]
{\bf endfun} $\langle${\em function\_name} $\rangle$ 
\end{algorithm}
%\end{quote}
}
\vspace{0.1in}


The data declarations are divided into constant declarations, variable declarations, and object declarations. This is similar to the data declarations that appear in the class. These declarations define local data\index{data} in the function and are optional. The instructions\index{instructions} of the function appear between the keywords {\bf begin} and {\bf endfun}. The following OOSimL code shows a simple function for displaying a text message on the screen. 


\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
description
   This function displays a message 
   on the screen. */
function show_message is
begin
   display "Computing data" 
endfun show_message 
\end{verbatim}
%\end{quote}
}
%\vspace{0.1in}

\section{Function Calls}

A function starts executing when it is called by another function. A function {\em call\/}\index{call} is also known as {\em method invocation}\index{method invocation}. The function that calls another function is known as the calling function; the second function is known as the called function. When a function calls or invokes another function, the flow of control is altered and the second function starts execution. When the called function completes execution, the flow of control is transferred back (returned) to the calling function. This function continues execution from the point after it called the second function. 

After completion, the called function may or may not return a value to the calling function. From the data transfer point of view, there are three general categories of functions:

\begin{enumerate}
  \item
   {\em Simple functions\/} are functions that do not return any value when they are invoked. The previous example, function {\em show\_message}, is a simple (or void) function because it does not return any value to the function that invoked it.
  \item
   {\em Value-returning\/}\index{value-returning} functions that return a single value after completion.
  \item 
   Functions with {\em parameters\/}\index{parameters} are functions that require one or more data items as input values when invoked.
\end{enumerate}

Functions that combine the last two categories ---functions that return a value and that have parameters are also grouped in two categories, according to their purpose:

\begin{itemize}

\item
Functions that return the value of an attribute of the object and do not change the value of any attribute(s) of the object. These are known as {\em accessor\/}\index{accessor} functions. 

\item
Functions that change the state of the object in some way by altering the value of one or more attributes in the object. Normally, these functions do not return any value. These are known as {\em mutator\/} functions\index{mutator}.

\end{itemize}

%\hspace{0.3in}

Good programming practice recommends defining the functions in a class as being either accessor or mutator.

\subsection{Calling Simple Functions}

Simple functions do not return a value to the calling function. An example of this kind of function is {\em show\_message}, discussed previously. There is no data transfer to or from the function. In OOSimL, the statement that calls or invokes a simple function that is referenced by an object reference variable is:

\vspace{0.1in}
%\begin{quote}
{\tt %\small
\begin{algorithm}
{\bf call} $\langle${\em function\_name} $\rangle${\bf of} $\langle${\em object\_reference} $\rangle$ 
\end{algorithm}
%\end{quote}
}
\vspace{0.1in}


In the following example, function {\em show\_message\/} that belongs to an object referenced by {\em carobj\/}, is invoked from function {\em main}, the call statement is:

\vspace{0.1in}
%\begin{quote}
{\tt \footnotesize
\begin{algorithm}
{\bf call} show\_message{\bf of} carobj
\end{algorithm}
%\end{quote}
}
\vspace{0.1in}

Figure~\ref{fig:funcall} shows the calling function and the called function, {\em show\_message}. After completing its execution, the called function returns the flow of control to the calling function. 


\begin{figure}[h]
\vspace{.1in}
\centereps{3.5in}{1.804in}{figs/funcall.png}
\caption{The calling and called functions}
\label{fig:funcall}
%\vskip\baselineskip
\vspace{0.1in}
\end{figure}

%\section{Data in Function Calls}

Data can be transferred\index{data transfer} between the calling and the called function. This data transfer may occur from the calling function to the called function, from the called function to the calling function, or in both directions. 


%\newpage

\subsection{Value-Returning Functions}

Value-returning functions transfer data from the called function to the calling function. In these functions, a single value is calculated or assigned to a variable and is returned to the calling function. 

The called function is defined with a type, which is the type of the return value. The function {\em return type\/}\index{return type} may be a simple type or a class. After the execution of the called function completes, control is returned to the calling function with a single value. The OOSimL statements that define the form of a value-returning function are:

\vspace{0.1in}
%\begin{quote}
{\tt %\small
\begin{algorithm}
{\bf description}
\ \ . . .
\ */
{\bf function} $\langle${\em function\_name} $\rangle${\bf of type} $\langle${\em return\_type} $\rangle$ {\bf is}
\ \ . . .
\ \ {\bf return} $\langle${\em return\_value} $\rangle$ 
{\bf endfun} $\langle${\em function\_name} $\rangle$
\end{algorithm}
%\end{quote}
}
\vspace{0.1in}

The value in the return statement can be any valid expression, following the {\bf return}\index{return} keyword. The expression can include constants, variables, object references, or a combination of these. 


The following example defines a function, {\em get\_name} that returns the value of the attribute {\em emp\_name} of an object of class Employee. This value is returned to the calling function. In the header of the function, the type of the value returned is indicated as {\bf string}. The code for this function definition is:

\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
  description
    This function returns the name of the employee object.
    */
  function get_name return type string is
  begin
      return name 
  endfun get_name
\end{verbatim}
}
\vspace{0.1in}

%\subsubsection{Invoking Value-Returning Functions}

The value-returning function can be called and the value returned can be used in several ways:

\begin{itemize}
 \item
 Call the function in a simple assignment statement
 \item
 Call the function in an assignment with an arithmetic expression
 \item
 Call the function in a more complete {\em call\/} statement
\end{itemize}

The value returned by the called function is used by the calling function by assigning this returned value to another variable. The following example shows a function calling function {\em get\_salary\/}. The calling function assigns the value returned to variable {\em sal}. There are several ways to write this code and the statements are:

\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
set sal = call get_salary 
call get_salary value to sal
set sal = get_salary()
\end{verbatim}
}
\vspace{0.1in}

The value returned can be used in an assignment with an arithmetic expression after calling a function. For example, after calling function {\em get\_salary\/}, the value returned is assigned to variable {\em sal}. This variable is then used in an arithmetic expression that multiplies {\em sal\/} by variable {\em percent\/}. The value that results from evaluating this expression is assigned to variable {\em upd\_sal\/}. This assignment statement is:

%\vspace{0.2in}
\begin{quote}
\tt %\footnotesize
\begin{verbatim}
set upd_sal = sal * percent 
\end{verbatim}
\end{quote}
\rm %\normalsize 
%\vspace{0.1in}
 
%\vfill

\subsection{Function Calls with Arguments}

The called function can receive data values when called from another function. The functions definition for functions to be called should include data definitions known as {\em parameter\/}\index{parameters} {\em declarations}. These parameter definitions are similar to local data declarations and have local scope and persistence. The called function may return a value, although it is not recommended to define the called function for this.

%\subsubsection{Calling Functions with Parameters}

The data values sent to the called function by calling function are known as {\em arguments\/}\index{arguments} and can be actual values (constants) or names of data items. When there are two or more argument values in the function call, the argument list consists of the data items separated by commas. The argument list should appear after the keyword {\bf using} in the {\bf call} statement. The OOSimL {\bf call} statement for a function call with arguments is:

\vspace{0.1in}
%\begin{quote}
{\tt %\small 
\begin{algorithm}
{\bf call} $\langle${\em function\_name} $\rangle${\bf of} $\langle${\em object\_ref} $\rangle$
\ \ \ \ \ \ \ {\bf using} $\langle${\em argument\_list} $\rangle$ 
\end{algorithm}
%\end{quote}
}
%\rm %\normalsize
\vspace{0.1in}

The following example is a call to function {\em cal\_area\/} that belongs to an object referenced by {\em myobj}. The function calculates and displays the area of a triangle given two arguments {\em x\/} and {\em y}. This {\bf call} statement is:

\vspace{0.1in}
\begin{quote}
{\tt %\footnotesize
\begin{verbatim}
  call cal_area of myobj using x, y 
\end{verbatim}
}
\end{quote}
\vspace{0.1in}

%\subsubsection{Declaration of Parameters}

The declaration of parameters\index{parameters} in a function defines for every parameter a type and a parameter name. The general structure of a function with parameter declaration is:

\vspace{0.1in}
%\begin{quote}
{\tt %\footnotesize
\begin{algorithm}
{\bf description}
\ \ . . .
\ */
{\bf function} $\langle${\em function\_name} $\rangle$ 
{\bf parameters} $\langle${\em parameter\_list} $\rangle$ 
{\bf is}
\ \ . . .
 
{\bf endfun} $\langle${\em function\_name} $\rangle$ 
\end{algorithm}
%\end{quote}
}
\vspace{0.1in}

In the following example, function {\em cal\_area} computes the area of a triangle given the base and altitude. The code for the function in OOSimL is:

\vspace{0.1in}
\begin{quote}
{\tt %\small 
\begin{verbatim}
description
  This function calculates the area of
   A triangle given the base b and the height h
   it then prints the result on the screen.
  */
function cal_area 
parameters b of type float, 
           h of type float
is
variables
   define area of type float   // local variable
begin
   set area = b * h * 0.5 
   display "Area of triangle is: ", area 
   return                      // empty return
endfun cal_area
\end{verbatim}
}
\end{quote}
\vspace{0.1in}


In the example, function {\em cal\_area\/} declares the parameters {\em b\/} and  {\em h}. The parameters are used as placeholders for the corresponding argument values transferred from the calling function. Figure~\ref{fig:fparam} illustrates the call of function {\em cal\_area\/} with argument values from the calling function. 

\vspace{.1in}
\begin{figure}[h]
%\centereps{2.15in}{3.378in}{figs/fparam.png}
\centering
\includegraphics[width=2.0in]{figs/fparam.eps}
\caption{Using arguments in a function call}
\label{fig:fparam}
%\vskip\baselineskip
\end{figure}
\vspace{0.1in}

\section{Constructors}

One or more {\em constructors\/}\index{constructor} functions, also known as {\em initializer\/}\index{initializer} functions, will normally appear in a class definition. These are special functions that are called when creating objects of the enclosing class. The main purpose of an initializer function is to set the object created to an appropriate initial state. The attributes of the corresponding object are assigned to some initial values.

In the following example, class {\em Employee\/} include the attribute declaration and the definition of the initializer function.

%\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
class Employee is
  private
  variables                   
      define salary of type double
      define age of type integer
      define name of type string
      define sal_increase of type double  
  object references
      define employ_date of class EmpDate   
  public    
  description
    This is the constructor, it initializes an Employee 
    object on creation.    */
  function initializer 
  parameters iname of type string, 
             isalary of type double, 
             iage of type integer
  is
  begin
    set salary = isalary
    set age = iage
    set name = iname
    set sal_increase = 0.0
    set employ_date = null
  endfun initializer 
  . . . [other functions in the class]
  endclass Employee
\end{verbatim}
%\end{quote}
}
\vspace{0.1in}

It is recommended to define at least a default initializer function. When no initializer function appears in the class definition, the default values are (zero and empty) assigned to the attributes. 

In class {\em Employee} the default values for the {\em sal\_increase\/} attribute is set to 0.0. 

An initializer function can set the value of the attributes to the values given when called. These values are given as arguments in the statement that creates the object. The general statement to create an object with given values for one or more attributes is:

\vspace{0.1in}
%\begin{quote}
{\tt %\small 
\begin{algorithm}
{\bf create} $\langle${\em object\_ref\_name} $\rangle${\bf of class} $\langle${\em class\_name} $\rangle$
\ \ \ {\bf using} $\langle${\em argument\_list} $\rangle$
\end{algorithm}
%\end{quote}
}
\vspace{0.1in}

The following example uses an object reference {\em emp\_obj\/} of class {\em Employee} to create an object with initial values of {\tt "John Doe"} for {\em name},  {\tt 35876.00} for {\em salary}, and {\tt 45} for {\em age}.

\vspace{0.1in}
\begin{quote}
{\tt \small 
\begin{verbatim}
 create emp_obj of class Employee 
                        using "John Doe", 35876.00, 45
\end{verbatim}
}
\end{quote}
\vspace{0.1in}

{\em Overloading\/}\index{overloading} is the programming facility of defining two or more functions with the same name. This facility of the programming language allows any function in a class to be overloaded. These functions are defined with the same name, but with a different number of and types of parameters. In this way, there is more than one way to initialize an object of the class. 


%\newpage

\section{Complete Sample Program}

\label{sectcomprog}
The following example is a complete program that consists of two classes: class {\em Employeem\/} and class {\em Comp\_salary\/}. The definition of class {\em Employee} is as follows:

\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
description
  This program computes the salary increase for an employee;
  if his/her salary is greater than $45,000 the salary 
  increase  is 4.5%, otherwise the salary increase is 5%.
  This is the class for employees. The main attributes are
    salary, age, and name.  */
class Employeem is
  private
  variables                    // variable data declarations
      define salary of type float
      define age of type integer
      define obj_name of type string
      define salincrease of type float   // salary increase
  public
  description
    This is the constructor, it initializes an object on 
    creation.     */
  function initializer 
  parameters iname of type string, 
             isalary of type float, 
             iage of type integer 
  is
  begin
    set salary = isalary 
    set age = iage 
    set obj_name = iname 
  endfun initializer 
  \end{verbatim}
%\end{quote}
}
 
\newpage
 
{\tt \small 
\begin{verbatim} 
  description
    This funtion gets the salary of the employee object. */
  function get_salary return type float is
    begin
      return salary 
  endfun get_salary 
  //
  description
    This function returns the name of the employee object. */
  function get_name return type string is
    begin
      return obj_name 
  endfun get_name
  // 
  description
      This function computes the salary increase and 
      updates the salary of an employee.       */
  function sal_increase is
    constants   // constant data declarations  
      define percent1 = 0.045 of type float 
      define percent2 = 0.050 of type float 
    begin                // body of function starts here
      if salary > 45000.00 then
         set salincrease = salary * percent1 
      else
         set salincrease = salary * percent2 
      endif 
      add salincrease to salary    // update salary
  endfun sal_increase
  //
  description
     This function returns the salary increase for 
     the object. */
  function get_increase return type float is
   begin
     return salincrease
  endfun get_increase
endclass Employeem 
\end{verbatim}
%\end{quote}
}
\vspace{0.1in}

The other class, {\em Comp\_salary\/}, includes function {\em main\/} that starts and controls the execution of the entire program. The following code is the implementation of class {\em Comp\_salary}.


%\vspace{0.1in}
\newpage

%\begin{quote}
{\tt \small 
\begin{verbatim}
description
  This program computes the salary increase for an employee;
  if his/her salary is greater than $45,000 the salary 
  increase is 4.5%, otherwise the salary increase is 5%. 
  This class creates and manipulates the objects of 
  class Employeem. */
class Comp_salary is
  public
  description
      This is the main function of the application.
      */
  function main is
    variables
      define increase of type float
      define salary of type float
      define age of type integer
      define empname of type string
    object references
      define emp_obj of class Employeem
    begin
      display "Enter salary: " 
      read salary 
      display "Enter age: " 
      read age 
      display "Enter employee name: " 
      read empname 
      create emp_obj of class Employeem using 
                            empname, salary, age 
      call sal_increase of emp_obj
      set increase = call get_increase of emp_obj 
      set salary = get_salary() of emp_obj // updated salary
      display "Employee name: ", empname 
      display "increase: ", increase, " new salary: ", salary 
   endfun main 
endclass Comp_salary
\end{verbatim}
%\end{quote}
}
\vspace{0.1in}


\section{Static Features}

Functions or attributes in a class may not be associated with any object of the class. These features are known as {\em static\/}\index{static} features and do not belong to an object, although they are defined in a class. To access these features, the class name followed by a dot and then the name of the feature is used. The following example invokes method {\em cos\/} of class {\em Math}: 

\vspace{0.1in}
%\begin{quote}
{\tt \small
\begin{verbatim}
set angle = Math.cos(x) * delta
\end{verbatim}
}
%\end{quote}
\vspace{0.1in}


To define a static function, the keyword {\bf static} is written before the name of the function. The following example is the header for the definition of method {\em compute\_h}:

\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
static function compute_h is
. . .
endfun compute_h
\end{verbatim}
}
%\end{quote}
\vspace{0.1in}

In a similar manner, the declaration of a static\index{static} attribute is written with the keyword {\bf static} before the variable declaration. These variables should normally be private and should be accessed by (public) accessor functions. When the program executes, for every declaration of a static variable, there is only one copy of its value shared by all objects of the class. Often, static variables are also known as class variables, and static methods as class methods.

The following example declares a static variable named {\em count\_pins} and initializes it to value 20.

\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
static count_pins = 20 of type integer
\end{verbatim}
}
%\end{quote}
\vspace{0.1in}

%\include{ch05} % Design and Prog Structures

\section{Design Notations}

Designing a solution to a problem involves design of an algorithm, which will be as general as possible to solve a family or group of similar problems. To describe an algorithm, several notations are used, such as informal English, flowcharts, and pseudo-code.

An algorithm can be described at several levels of abstraction. Starting from a very high-level and general level of description of a preliminary design, to a much lower-level that has more detailed description of the design.


A notation is a more informal and higher level than a programming language. It is set of rules used for the informal description of an algorithm. Two widely-used design notations are:

\begin{itemize}
 \item Flowcharts
 \item Pseudo-code
\end{itemize}

\subsection{Flowcharts}

Flowcharts\index{flowcharts} consist of a set of symbol blocks connected by arrows. A flowchart is a visual representation for describing a sequence of design or action steps of the solution to a problem. The arrows that connect the blocks show the order in which the action steps are to be carried out. The arrows also show the flow of data.

Several simple flowchart blocks are shown in Figure~\ref{fig:ksymbols}. A flowchart always begins with a {\em start} symbol\index{start symbol}, which  has an arrow pointing from it. A flowchart ends with a {\em stop} symbol\index{stop symbol}, which has one arrow pointing to it. 

\vspace{0.1in}
\begin{figure}[h]
\centereps{3.5in}{2.47in}{figs/ksymbols.png}
\caption{Simple flowchart symbols}
\label{fig:ksymbols}
%\vskip\baselineskip
\end{figure}
\vspace{0.1in}


The {\em process} symbol or {\em transformation} symbol is the most common and general symbol; it represents a design step. The symbol is shown as a rectangular box and represents any computation or sequence of computations carried out on some data. There is one arrow pointing to it and one arrow point from it. 

Another flowchart symbol has the shape of a vertical diamond, and it represents a selection of alternate paths in the sequence of design steps. This symbol is also shown in Figure~\ref{fig:ksymbols}. This symbol is known as a decision block or a conditional block because the sequence of instructions can take one of two directions in the flowchart.

The flowchart symbol for a data input\index{input} or output\index{output} operation is shown in Figure~\ref{fig:inout}. There is one arrow pointing into the block and one arrow pointing out from the block.

\vspace{.1in}
\begin{figure}[h]
\centereps{1.75in}{2.0in}{figs/inout1.png}
\caption{Flowchart data input/output symbol}
\label{fig:inout}
%\vskip\baselineskip
\end{figure}
\vspace{0.1in}


For larger or more complex algorithms, flowcharts are used for the high-level description of the algorithms.

\vspace{.1in}
\begin{figure}
\centereps{1.15in}{2.682in}{figs/ksequence.png}
\caption{A simple flowchart}
\label{fig:kseq}
%\vskip\baselineskip
\end{figure}
\vspace{0.1in}


A simple flowchart with several basic symbols is shown in Figure~\ref{fig:kseq}.  

%\newpage

\subsection{Pseudo-code}

Pseudo-code\index{pseudo-code} is a notation that uses English description for describing the algorithm that defines a problem solution. It can be used to describe relatively large and complex algorithms. Pseudo-code is much easier to understand and use than any programming language. It is relatively easy to convert the pseudo-code description of an algorithm to a high-level programming language. 

%\newpage

%\vfill

\section{Algorithmic Structures}

There are four design structures with which any algorithm can be described. These can be used with flowcharts and with pseudo-code notations. The basic design structures are:

\begin{itemize}
\item
  {\em Sequence}\index{sequence}, any task can be broken down into a sequence of steps. 
\item
  {\em Selection}\index{selection}, part of the algorithm takes a decision and select one of several alternate paths of flow of actions. This structure is also known as alternation or conditional branch.
  \item
{\em Repetition}\index{repetition}, this part pf the algorithm has a set of steps that are to be executed zero, one, or more times.  This structure is also known as looping. 
\item
  {\em Input-output}\index{input-output}, the values of variables are read from an input device (such as the keyword) or the values of the variables (results) are written to an output device (such as the screen)
\end{itemize}

%\vfill

\subsection{Sequence}

Figure~\ref{fig:kseq} illustrates the sequence structure. A simple sequence of flowchart blocks is shown. The sequence structure is the most common and basic structure used in algorithmic design. 

%\vfill

\subsection{Selection}

With the selection structure, one of several alternate paths will be followed based on the evaluation of a condition. Figure~\ref{fig:ksel} illustrates the selection structure\index{selection structure}. In the figure, the actions in {\em Action step1} are executed when the condition is true. The instructions in {\em Action step2} are executed when the condition is false. 

\vspace{.1in}
\begin{figure}[h]
\centereps{1.8in}{1.958in}{figs/ksel.png}
\caption{Selection structure in flowchart form}
\label{fig:ksel}
%\vskip\baselineskip
\end{figure}
\vspace{0.1in}


A flowchart example of the selection structure is shown in Figure~\ref{fig:kselex}. The condition of the selection structure is $X > 0$ and when this condition evaluates to true, the block with the action {\tt increment j} will execute. Otherwise, the block with the action {\tt decrement j} is executed.

\vspace{0.1in}
\begin{figure}[h]
\centereps{1.8in}{1.958in}{figs/kselx.png}
\caption{An example of the selection structure}
\label{fig:kselex}
%\vskip\baselineskip
\end{figure}
\vspace{0.1in}


A variation of the selection structure has multiple alternate paths, each one depends on the value of a variable. This structure is known as the {\em case\/}\index{case} construct.  Figure~\ref{fig:case} illustrates this construct. 


\vspace{.1in}
\begin{figure}[h]
\centereps{2.85in}{2.137in}{figs/case.png}
\caption{The {\em case\/} construct}
\label{fig:case}
%\vskip\baselineskip
\end{figure}
\vspace{0.1in}


\subsection{Repetition}

The repetition structure\index{repetition} will cause a set of action steps to be repeated several times. Figure~\ref{fig:kwhile} shows this structure. The execution of the actions in {\em Action step1\/} are repeated while the condition is true. This structure is also known as the {\em while loop}\index{while loop}.




\begin{figure}[h]
%\vspace{.2in}
\centereps{2.0in}{2.264in}{figs/kwhile.png}
\caption{Repetition structure in flowchart form}
\label{fig:kwhile}
%\vskip\baselineskip
%\vspace{0.1in}
\end{figure}

A variation of the repetition structure is shown in Figure~\ref{fig:krep}. The actions in {\em Action step1\/} are repeated until the condition becomes true. This structure is also known as the {\em repeat-until\/}\index{repeat-until}  loop.

\begin{figure}[h]
%\vspace{.2in}
\centereps{2.0in}{2.275in}{figs/krep.png}
\caption{Repeat-until loop of the repetition structure}
\label{fig:krep}
%\vskip\baselineskip
%\vspace{0.1in}
\end{figure}

\section{Programming Statements}

Programming languages are used to implement the solution that has been designed; this includes the data descriptions and the algorithm.  A programming language has language {\em statements\/}\index{statements} that are used for data declarations and for writing the instructions. 

This section mainly deals with simple OOSimL statements, such as the assignment and I/O statements. 

\subsection{Assignment and Arithmetic Expressions}

The most used statement is the {\em assignment\/}\index{assignment} statement and is used to assign a value to a variable. The statement is written with the keyword {\bf set}. This variable must be written on the left-hand side of the equal sign, which is the assignment operator.

The value to assign can be directly copied from another variable, from a constant value, or from the value that results after evaluating an expression. 

In the following example, the constant value 1435.5 is assigned to variable {\em h} and the value 100 to variable {\em j}.
\vspace{0.1in}
\begin{quote}
{\tt \small 
\begin{algorithm}
variables
\ \ {\bf float} h
\ \ {\bf float} p
\ \ {\bf float} q
\ \ {\bf integer} j
begin
\ \ . . .
\ \ {\bf set} h = 1435.5
\ \ {\bf set} j = 100
\ \ {\bf set} p = q + 14.5 * h


\end{algorithm}
}

\end{quote}
\vspace{0.1in}

The third assignment statement in the example, variable {\em p\/} is assigned the result of evaluating the expression, $q + 14.5 * h$. 

\subsection{Simple Numeric Computing}

Arithmetic expressions are normally used in an assignment statement. For example add 5 to the value of variable $j$, subtract the value of variable $h$ from variable $p$, the assignment statements with the simple arithmetic expressions are:

\vspace{0.1in}
\begin{quote}
{\tt \small 
\begin{algorithm}
\ \ {\bf set} j = j + 5 
\ \ {\bf set} p = p - h
\end{algorithm}
}
\end{quote}
\vspace{0.1in}

In the example, in the first assignment, the new value of $j$ is assigned by adding 5 to the previous value of $j$. In the second assignment, the new value of variable $p$ is assigned the value that results after subtract the value of $h$ from the previous value of $p$.

The OOSimL language provides the {\bf add} and the {\bf subtract} statements that are equivalent to the assignments of in the example. The following two statements show the same computation.

\vspace{0.1in}
\begin{quote}
{\tt \small
\begin{algorithm}
\ \ {\bf add} 5 to j
\ \ {\bf subtract} h from p
\end{algorithm}
}
\end{quote}
\vspace{0.1in}

To add or subtract 1, the language provides the {\bf increment} and the {\bf decrement} statement. For example, {\tt increment j}, adds the constant 1 to the value of variable $j$. {\tt decrement k} subtracts the constant value 1 from the value of variable $k$.


%\subsection{More Advanced Arithmetic Expressions}

The arithmetic\index{arithmetic} expression\index{expressions} used in the assignment statements discussed previously were very simple; only basic arithmetic operations appeared in the expressions. These are addition, subtraction, multiplication, and division. 

To carry out more complex calculations, the language class library provides various numerical functions. Most of these functions are static, so to use a particular function of the {\em Math\/} library class, the name of the class must appear followed by a dot and then the name of the particular function invoked. Class {\em Math\/} is part of the class library supplied with the Java compiler. This class provides several mathematical functions, such as square root, exponentiation, trigonometric. 


For example, consider the value of the expression $\cos{x} + y$ assigned to variable $z$ and \,$\sqrt{t}$ - p%\, assigned to variable {\em y}. 

The expression in the assignment statement use the mathematical functions {\em cos\/} and {\em sqrt\/} in class {\tt Math}. The OOSimL statements are:

\vspace{0.1in}
\begin{quote}
{\tt \small 
\begin{algorithm}
\ \ {\bf set} z = Math.cos(x) + y
\ \ {\bf set} y = Math.sqrt(t) - p
\end{algorithm}
}
\end{quote}
\vspace{0.1in}

The value of the mathematical expression $b^2$ assigned to variable {\em area\/}, is coded as:

\vspace{0.1in}
\begin{quote}
{\tt \small
\begin{algorithm}
\ \ {\bf set} area = Math.pow(b, 2)
\end{algorithm}
}
\end{quote}
\vspace{0.1in}

\subsection{Console I/O}

The programming language OOSimL provides two basic statements for console input/output. The input statement reads a value of a variable from the input device (e.g., the keyboard). This statement is written with the keywords {\bf read}, for input\index{input} of a single variable. The output statement can be used for the output of a list of variables and literals, it is written with the keyword {\bf display}. The general form of the input statement is:

\vspace{0.2in}
\begin{quote}
\tt %\footnotesize
\begin{algorithm}
\ \ {\bf read} $\langle${\em variable\_name} $\rangle$ 
\end{algorithm}
\end{quote}
\rm %\normalsize
\vspace{0.2in}

The following example uses the {\bf read} statement to read a value of variable {\em h}:

\vspace{0.2in}
\begin{quote}
\tt %\footnotesize
\begin{algorithm}
\ \ {\bf read} h
\end{algorithm}
\end{quote}
\rm %\normalsize
\vspace{0.2in}

The input statement implies an assignment statement for the variable {\em h}, because the variable changes its value to the new value that is read from the input device.

The output\index{output} statement writes the value of one or more variables to the output device. The variable does not change their values. The general form of the output statement is:

\vspace{0.1in}
\begin{quote}
{\tt \small 
\begin{algorithm}
\ \ {\bf display} $\langle${\em data\_list} $\rangle$ 
\end{algorithm}
}
\end{quote}
\vspace{0.1in}

With the output statement, a list of data items can be displayed on the console. The following example displays on the console: a string literal, followed by the value of variable {\em h\/}, followed by another string literal, and followed by the value of variable {\em q\/}.

\vspace{0.1in}
\begin{quote}
{\tt \small 
\begin{algorithm}
\ \ {\bf display} "value of h: ", h, " value of q: ", q
\end{algorithm}
}
\end{quote}  
\vspace{0.1in}


\section{Computing Area and Circumference}

This problem computes the area and circumference of a circle, given its radius.
The high-level algorithm description in informal pseudo-code notation is:

\begin{enumerate}
\item
Read the value of the radius of a circle, from the input device.
\item
Compute the area of the circle.
\item
Compute the circumference of the circle.
\item
Print or display the value of the area of the circle to the output device.
\item
Print or display the value of the circumference of the circle to the output device.
\end{enumerate}

A more detailed algorithm description follows:

\begin{enumerate}
\item
Read the value of the radius {\em r\/} of a circle, from the input device.
\item
Establish the constant $\pi$ with value 3.14159.
\item
Compute the area of the circle, $area = \pi \times r ^2$.
\item
Compute the circumference of the circle $cir = 2 \times \pi \times r$.
\item
Print or display the value of {\em area\/} of the circle to the output device.
\item
Print or display the value of {\em cir\/} of the circle to the output device.
\end{enumerate}

The following OOSimL program implements the data description and the algorithm for calculating the area of a circle. The example has a single class that includes function {\em main\/}. This class calls a function, {\em pow\/} of the library class, {\em Math\/}. 


\vspace{0.1in}
%\begin{quote}
{\tt \small
\begin{verbatim}
description
   This class computes the area and circumference of
   A circle, given its radius. This value is read 
   using console I/O.
   */
class Circle_comp is
 public
 function main is
    // data descriptions
 constants
    define PI = 3.14159 of type double
 variables  
    define r of type float
    define area of type double
    define cir of type double
 begin
    // instructions starts here
    display "enter value of radius: "
    read r
    // compute area of circle
    set area = PI * Math.pow(r, 2)
    // compute circumference of circle
    set cir = 2.0 * PI * r
    // now print the results
    display "Area of circle is: ", area
    display "Circumference of circle is: ", cir
 endfun main
endclass Circle_comp
\end{verbatim}
}
%\end{quote}
\vspace{0.1in}

After compiling the program is executed and produces the following results on the console:

\vspace{0.1in}
%\begin{quote}
{\tt \small
\begin{verbatim}
Enter value of radius: 2.75
Area of circle is: 23.758274375
Circumference of circle is: 17.278745
\end{verbatim}
}


%\include{ch06} % Selection

\section{Selection Structure}

The selection\index{selection} design structure is also known as alternation\index{alternation}, because alternate paths are considered based on a condition. 

\subsection{Flowchart of Selection Structure}

The selection structure provides the capability for decision-making. Because the selection design structure\index{design structure} is better understood using a flowchart, Figure~\ref{fig:gsel} is repeated here. The figure shows two possible paths for the execution flow. The condition is evaluated, and one of the paths is selected. If the condition is true, then the left path is selected and {\em Action step1\/} is performed. If the condition is false, the other path is selected and {\em Action step2\/} is performed. 

%\vspace{.1in}
\begin{figure}[h]
\centereps{2.0in}{1.958in}{figs/ksel.png}
\caption{Flowchart of the Selection structure}
\label{fig:gsel}
%\vskip\baselineskip
\end{figure}
%\vspace{0.1in}


\subsection{IF Statement}

The selection structure is written with an {\bf if} statement\index{if statement}, also known as an if-then-else statement. This statement includes three sections: the condition, the then-section, and the else-section. The else-section is optional. Several keywords are used in this statement: {\bf if}, {\bf then}, {\bf else}, and {\bf endif}. The general form of the {\bf if\/} statement is:

%\newpage

\vspace{0.08in}
%\begin{quote}
{\tt %\small
\begin{algorithm}
{\bf if} $\langle${\em condition} $\rangle$ 
\ {\bf then}
\ \ \ $\langle${\em first sequence of statements} $\rangle$
\ {\bf else}
\ \ \ $\langle${\em alternate sequence of statements} $\rangle$
{\bf endif}
\end{algorithm}
}
%\end{quote}
\vspace{0.1in}

The {\bf if} statement that corresponds to the selection structure in Figure~\ref{fig:gsel} is:

\vspace{0.1in}
%\begin{quote}
{\tt \small
\begin{algorithm}
{\bf if} condition is true 
\ {\bf then}
\ \ \ perform instructions in Action step1
\ {\bf else}
\ \ \ perform instructions in Action step2
{\bf endif}
\end{algorithm}
}
%\end{quote}
\vspace{0.1in}


When the {\bf if} statement executes, the condition is evaluated and only one of the two alternatives will be carried out: the one with the statements in {\em Action step1\/} or the one with the statements in {\em Action step2}. 

\subsection{Boolean Expressions}

Boolean expressions are written to form conditions. A condition\index{condition} consists of an expression that evaluates to a truth-value, {\bf true} or {\bf false}. 

A simple Boolean expression can be formed with the values of two data items and a relational operator. The following list of relational operators can appear in a Boolean expression:

\begin{itemize}
\item
 Less than, $<$
\item
 Less or equal to, $<=$
\item
 Greater than, $>$
\item
 Greater or equal to, $>=$
\item
 Equal, ==
\item
 Not equal, !=

\end{itemize}

Examples of simple conditions are: 

\vspace{0.1in}
\begin{quote}
{\tt %\footnotesize
\begin{algorithm}
\ \ height > 23.75 
\ \ a <= b 
\ \ p == q
\end{algorithm}
}
\end{quote}
\vspace{0.1in}

OOSimL supports not only conditions with the syntax in the previous example, but also provides additional keywords can be used for the relational operators. For example, the previous Boolean expressions can also be written as:

\vspace{0.1in}
\begin{quote}
{\tt %\footnotesize
\begin{algorithm}
\ \ height {\bf greater than} 23.75
\ \ a {\bf less or equal to} b 
\ \ p {\bf equal to} q
\end{algorithm}
}
\end{quote}
\vspace{0.1in}

\subsection{Example of Selection}

In this example, the condition to be evaluated is: $p \leq q$, and a decision is taken on how to update variable $p$. Figure~\ref{fig:kselx} shows the flowchart for part of the algorithm that includes this selection structure.

\vspace{.1in}
\begin{figure}[h]
\centereps{2.5in}{2.911in}{figs/kselx.png}
\caption{Example of selection structure}
\label{fig:kselx}
%\vskip\baselineskip
\end{figure}
\vspace{.1in}

The OOSimL code for this example is:

\vspace{0.1in}
%\begin{quote}
{\tt \small
\begin{algorithm}
\ {\bf if} p <= q 
\ {\bf then}
\ \ \ {\bf set} p = q * x + 24.5
\ {\bf else}
\ \ \ {\bf set} p = q
\ \ \ {\bf set} q = 12.75
\ {\bf endif}
\end{algorithm}
}
%\end{quote}
\vspace{0.1in}


\section{Example Program}

This example computes the gross pay, taxes, and net pay of employees, given the hours worked and the hourly rate.

\subsection{High-level Design}

The overall description of the data and algorithm is shown in Figure~\ref{fig:payemp}. The flow of control in the selection structure depends on the condition: {\em gpay\/} {\bf greater than} {\em TAXB}. 

The high-level description of algorithm in pseudo-code follows:
\begin{enumerate}
\item
Read values of employee name, employee number, hours worked, and hourly rate.
\item
Compute gross pay: hours worked $\times$ hourly rate
\item
if gross pay $>$ tax bracket then 

   Compute tax amount:
      (gross pay $-$ tax bracket) $\times$ tax rate
      
   Compute net pay: gross pay $-$ tax amount
   
else compute net pay $=$ gross pay
\item
  Display employee name, tax amount, net pay
\end{enumerate}

\newpage

\begin{figure}[ht]
%\vspace{.1in}
\centereps{2.75in}{4.579in}{figs/payemp.png}
\caption{General problem description}
\label{fig:payemp}
%\vskip\baselineskip
%\vspace{0.1in}
\end{figure}


\subsection{Implementation}

The implementation of the employee payment problem consists of two classes: {\em PayEmployee\/} and {\em Comp\_pay}. The most interesting part of the solution for this problem includes the selection statement and is found in function {\em compute\_pay\/} of class {\em PayEmployee}. 


%\newpage

\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
description
  This program computes the amount to pay an employee weekly
  after deducting taxes.
  The gross pay is computed from the number of hours worked
  by the employee, and the hourly rate.
  The income tax is computed as 14.75% of the amount earned 
  that exceeds the tax bracket, $110.00
  This is the class for employees. The main attributes are
    emp_number, name, hours worked, and hourly rate.
  */
class PayEmployee is
  private
  constants

      define TAXR = 0.1475 of type float   // tax rate
      define TAXB = 110.00 of type float   // tax bracket
  variables                   
      define emp_name of type string
      define emp_number of type string
      define hours of type integer         // hours worked
      define hr of type float              // hourly rate
      define gpay of type float            // gross pay
      define tax of type float             // taxes
      define npay of type float            // net pay
  public
    //
  description
    This is the constructor, it initializes an object 
    on creation.    */
  function initializer 
  parameters iname of type string, 
             inumb of type string, 
             ihours of type integer,
             ihr of type float
  is
  begin
    set emp_number = inumb
    set hr = ihr 
    set hours = ihours 
    set emp_name = iname 
  endfun initializer 
  //
  description
    This funtion gets the tax amount paid by the 
    employee object.    */
  function get_tax return type float is
    begin
      return tax  
  endfun get_tax 
  //
  description
    This function returns the name of the employee object.
    */
  function get_name return type string is
    begin
      return emp_name 
  endfun get_name 
  //
  description
      This function computes the gross pay, the taxes, 
      and the net pay of an employee. 
      */
  function compute_pay is
    begin                    
      // compute gross pay
      set gpay = hours * hr
      //
      // compute tax and net pay
      if gpay > TAXB then
         set tax = (gpay - TAXB) * TAXR
         set npay = gpay - tax   // net pay  
      else
         set npay = gpay  
      endif 
  endfun compute_pay
  //
  description
     This function returns the net pay for the 
     PayEmployee object.     */
  function get_npay return type float is
   begin
     return npay
  endfun get_npay
endclass PayEmployee 
//
\end{verbatim}
%\end{quote}
}
\vspace{0.1in}

The following class, {\em Comp\_pay} includes the function {\em main}, which creates and manipulates objects of class {\em PayEmployee}.

\vspace{0.1in}
%\begin{quote}
{\tt \small 
\begin{verbatim}
description
  This program computes the gross pay, tax amount, 
  and net pay an employee;
  */
class Comp_pay is
  public

  description
      This is the main function of the application.
      */
  function main is
    variables
      define net_pay of type float
      define taxes of type float
      define empname of type string
      define empnum of type string
      define hours of type integer
      define hrate of type float
    object references
      define emp_obj of class PayEmployee
    begin

      display "Enter employee name: " 
      read empname 
      display "Enter employee number: " 
      read empnum 
      display "Enter hours worked: " 
      read hours 
      display "Enter hourly rate: "
      read hrate
      create emp_obj of class PayEmployee using empname, 
             empnum, hours, hrate 
      call compute_pay of emp_obj
      set net_pay = call get_npay of emp_obj 
      set taxes = get_tax() of emp_obj // get tax amount paid
      display "Employee name: ", empname, " Net pay: ", 
             net_pay, " Tax amount: ", taxes 
   endfun main 
endclass Comp_pay
\end{verbatim}
}
\vspace{0.1in}

\section{If Statement with Multiple Paths}

The {\bf if} statement with multiple paths is used to implement decisions involving more than two alternatives. The additional {\bf elseif} clause is used to expand the number of alternatives. The general form of the {\em if\/} statement with $k$ alternatives is:

\vspace{0.1in}
%\begin{quote}
{\tt %\small
\begin{algorithm}
{\bf if} $\langle${\em condition} $\rangle$ 
\ {\bf then}
\ \ \ $\langle${\em sequence1 of statements} $\rangle$
\ {\bf elseif} $\langle${\em condition2} $\rangle$
\ {\bf then}
\ \ \ $\langle${\em sequence2 of statements} $\rangle$
\ {\bf elseif} $\langle${\em condition3} $\rangle$
\ {\bf then}
\ \ \ $\langle${\em sequence3 of statements} $\rangle$

\ \ \ . . .
\ {\bf else}
\ \ \ $\langle${\em sequencek of statements} $\rangle$
{\bf endif}
\end{algorithm}
}
%\end{quote}
\vspace{0.1in}
  
The conditions in a multiple-path {\bf if} statement are evaluated from top to bottom until one of the conditions evaluates to true. The following example applies the {\bf if} statement with four paths. 

\vspace{0.1in}
%\begin{quote}
{\tt \small
\begin{verbatim}
if height > 6.30 
then increment group1
elseif height > 6.15
then increment group2
elseif height > 5.85
then increment group3
elseif height > 5.60
then increment group4
else increment group5
endif 
\end{verbatim}
}
%\end{quote}
\vspace{0.1in}



%\newpage

\section{Using Logical Operators}

With the logical operators, complex Boolean expressions can be constructed. The logical operators are: {\bf and}, {\bf or}, and {\bf not}. These logical operators help to construct complex (or compound) conditions from simpler conditions.
The general form of a complex conditions\index{compound condition} using the {\bf or} operator and two simple conditions, {\em cond1\/} and {\em cond2}, is:

\vspace{0.1in}
{\tt  
\begin{algorithm}
\ \ cond1{\bf and} cond2


\ \ cond1{\bf or} cond2
\ \ {\bf not} cond1

\end{algorithm}
}
\vspace{0.1in}


The following example includes the {\bf and} logical operator:

\vspace{0.1in}
{\tt  
\begin{algorithm}
\ {\bf if} x >= y {\bf and} p == q
\ {\bf then} 
\ \ \ $\langle${\em statements\_1} $\rangle$
\ {\bf else}
\ \ \ $\langle${\em statements\_2} $\rangle$
\ {\bf endif}
\end{algorithm}
\rm
\vspace{0.1in}


The condition can also be written in the following manner:

\vspace{0.1in}
{\tt
\begin{algorithm}
\ {\bf if} x{\bf greater or equal to} y{\bf and} p{\bf is equal to} q
\ \ \dots
\end{algorithm}
}
\vspace{0.1in}

The following example applies the {\bf not} operator:

\vspace{0.1in}
{\tt
\begin{algorithm}
\ {\bf not} (p > q)
\end{algorithm}
}
\vspace{0.1in}


\section{The Case Statement}

The case structure\index{case structure} is a simplified version of the selection structure with multiple paths. The {\bf case} statement evaluates the value of a single variable or simple expression of type {\bf integer} or of type {\bf character} and selects the appropriate path. The case statement also  supports compound statements, that is, multiple statements instead of a single statement in one or more of the selection options. The general form of this statement is:

\vspace{0.1in}
{\tt
\begin{algorithm}
{\bf case} $\langle${\em selector\_variable} $\rangle$ {\bf of}
 \ {\bf value} {\em variable\_value} : $\langle${\em statements} $\rangle$
 \ \ \dots
{\bf endcase}
\end{algorithm}
}
\vspace{0.1in}

In the following example, the temperature status of a boiler is monitored and the temperature status is stored in variable {\em temp\_status}. The following case statement first evaluates the temperature status in variable {\em temp\_status\/} and then assigns an appropriate string literal to variable {\em mess}, finally this variable is displayed on the console.

The example assumes that the variables involved have an appropriate declaration, such as:

\vspace{0.1in}
{\tt
\begin{algorithm}
{\bf variables}
\ \ {\bf define} temp\_status{\bf of type}{\bf character}
\ \ {\bf define} mess{\bf of type}{\bf string} 
\ \ \dots 
\ \ {\bf case} temp\_status {\bf of}
\ \ \ \ {\bf value} 'E': mess = "Extremely dangerous"
\ \ \ \ {\bf value} 'D': mess = "Dangerous"
\ \ \ \ {\bf value} 'H': mess = "High"
\ \ \ \ {\bf value} 'N': mess = "Normal" 
\ \ \ \ {\bf value} 'B': mess = "Below normal"
\ \ {\bf endcase}
\ \ . . .
display "Temperature status: ", mess
\end{algorithm}
}
\vspace{0.1in}


The default option of the {\bf case} statement can also be used by writing the keywords {\bf default} or {\bf otherwise} in the last case of the selector variable. For example, the previous example can be enhanced by including the default option in the case statement:

\vspace{0.1in}
{\tt
\begin{algorithm}
\ \ {\bf case} temp\_status {\bf of}
\ \ \ \ {\bf value} 'E': mess = "Extremely dangerous"
\ \ \ \ {\bf value} 'D': mess = "Dangerous"
\ \ \ \ {\bf value} 'H': mess = "High"
\ \ \ \ {\bf value} 'N': mess = "Normal" 
\ \ \ \ {\bf value} 'B': mess = "Below normal"

\ \ \ \ {\bf otherwise} 
\ \ \ \ \ \ \ mess = "Temp rising"
\ \ {\bf endcase}
\ \ \ . . .
\ \ \ display "Temperature status: ", mess
\end{algorithm}
}
%\vspace{0.1in}
%\include{ch07} % Repetition

\section{The While Loop Structure}

The {\em while\/} loop\index{while loop} structure consists of a block of code and a condition. The condition is first evaluated -- if the condition is true the code within the block is then executed. This repeats until the condition evaluates to false. The while-loop structure checks the condition before the block of code is executed

%\vfill

\subsection{While-Loop Flowchart}

A flowchart with the {\em while\/} loop structure is shown in Figure~\ref{fig:kgwhiles}. The block of code consists of a sequence of actions. 

The actions in the code block are performed while the condition is true. After the actions are performed, the condition is again evaluated, and the actions are again performed if the condition is still true. This continues until the condition changes to false, at which point the loop terminates. 

\begin{figure}[h]
\vspace{.1in}
\centereps{2.5in}{2.83in}{figs/kwhiles.eps}
\caption{A flowchart of the while-loop}
\label{fig:kgwhiles}
%\vskip\baselineskip
\vspace{0.1in}
\end{figure}

The condition is tested first, and then the block of code is performed. If this condition is initially false, the actions in the code block are not performed.

The number of times that the loop is performed is normally a finite integer value. A well-defined loop will eventually terminate. The condition is sometimes called the {\em loop condition}\index{loop condition}, and it determines when the loop terminates. A non-terminating loop is defined in special cases and will repeat the actions forever.

A counter\index{counter} variable has the purpose of storing the number of times (iterations\index{iterations})  that the actions are repeated. The counter variable is of type integer and is incremented (or decremented) on each repetition. The counter variable must be initialized to a given value.  

\subsection{The While Statement}

The {\bf while} statement\index{while statement} includes the condition (a Boolean expression), the statements in the code block, and the keywords {\bf while}, {\bf do}, and {\bf endwhile}. The code block is placed after the {\bf do} keyword and before the {\bf endwhile} keyword. The following lines of code show the general form of the while-loop statement that corresponds to the portion of flowchart shown in Figure~\ref{fig:kgwhiles}.

\vspace{0.1in}
%\begin{quote}
{\tt %\small 
\begin{algorithm}
\ {\bf while} $\langle${\em condition} $\rangle$ {\bf do}
\ \ \ $\langle$ {\em statements in code block} $\rangle$
\ {\bf endwhile}
\end{algorithm}
}
%\end{quote}
\vspace{0.1in}

In the following example, a {\bf while} statement appears with a counter variable, {\em j}. This counter variable is used to control the number of times the repeat group will be performed.

%\vfill

\vspace{0.1in}
%\begin{quote}
{\tt \small
\begin{verbatim}
constants
  define MAX_NUM = 15 of type integer   // maximum number
                              // of times through the loop
variables
  define j of type integer    // loop counter
  define sum of type float
  ... 
begin
  set j = 1   // initial value
  while j <= MAX_NUM do
     set sum = sum + 12.5
     increment j
  endwhile
  display "Value of sum: ", sum
  ...
\end{verbatim}
}
%\end{quote}
\vspace{0.1in}

\section{Employee Pay Problem with Repetition}

This problem uses repetition to compute the gross pay and net pay to a given number of employees, {\em num}, which is read from the console. The processing for each employee has been discussed previously. 

In the flowchart, the actions performed to compute gross and net pay for every employee is included in the code block and placed in a while loop. In the program, the {\bf while} statement is used. The condition compares the loop counter, {\em j\/} with the given number of employees read, {\em num}. The condition for the repetition (loop) is: $ j <= Num$. 

The value of variable {\em num\/} represents the number of employees to process. Figure~\ref{fig:emprep} shows the flowchart for the algorithm for the problem with repetition.

\vspace{.1in}
\begin{figure}[h]
\centereps{2.75in}{3.427in}{figs/emprep.eps}
\caption{Employee pay problem with repetition}
\label{fig:emprep}
\end{figure}
\vspace{0.1in}

The following class includes the modified function {\em main}, which has the while loop. The other class, {\em PayEmployee}, has not been changed. 

\vspace{0.1in}
%\begin{quote}
{\tt \small
\begin{verbatim}
description
  This program processes the net pay for a given 
  number of employees. For every employee, 
  it computes the gross pay, tax amount, and net 
  pay an employee.
  */
class Comp_pay is
  public
  description
      This is the main function of the application.
      */
  function main is
    variables
      define num of type integer
      define j of type integer
      //
      define net_pay of type float
      define taxes of type float
      define empname of type string
      define empnum of type string
      define hours of type integer
      define hrate of type float
      define total_taxes of type float
      define total_npay of type float
    object references
      define emp_obj of class PayEmployee
    begin
      display "Enter number of employees to process"
      read num
      set j = 1
      set total_taxes = 0.0
      set total_npay = 0.0
      while j <= num do
          display "Enter employee name: " 
          read empname 
          display "Enter employee number: " 
          read empnum 
          display "Enter hours worked: " 
          read hours 
          display "Enter hourly rate: "
          read hrate
          create emp_obj of class PayEmployee 
               using empname, empnum, hours, hrate 
          call compute_pay of emp_obj
          set net_pay = call get_npay of emp_obj 
          set taxes = get_tax() of emp_obj   // get tax amount
          display "Employee name: ", empname, 
               " Net pay: ", net_pay, " Tax amount: ", taxes 
          increment j
          add taxes to total_taxes
          add net_pay to total_npay
      endwhile    
      display "Total taxes: ", total_taxes
      display "total net pay: ", total_npay
   endfun main 
endclass Comp_pay 
\end{verbatim}
%\end{quote}
}
\vspace{0.1in}

Variables {\em total\_taxes\/} and {\em total\_npay\/} accumulate on every iteration in the while loop, the tax amount and the net pay respectively. These variables are often known as accumulator variables. 

\section{Loop Until}

The loop {\em until\/}\index{loop until} structure is a control flow statement that allows code to be executed repeatedly based on a given condition. The structure consists of a block of code and the condition. 

The actions within the block are executed first, and then the condition is evaluated. If the condition is not true the actions within the block are executed again. This repeats until the condition becomes true.

Loop until structures check the condition after the block is executed, this is an important difference with while loop, which tests the condition before the actions within the block are executed. Figure~\ref{fig:lkrep} shows the flowchart for the loop-until structure.

%\vspace{.1in}
\begin{figure}[h]
\centereps{2.0in}{3.157in}{figs/krep.png}
\caption{Loop-until structure}
\label{fig:lkrep}
%\vskip\baselineskip
\end{figure}
%\vspace{.1in}


The OOSimL statement of the loop-until structure, corresponds directly with the flowchart in Figure~\ref{fig:lkrep} and uses the keywords {\bf repeat}, {\bf until}, and {\bf endrepeat}. The following portion of code shows the general form of the loop-until statement.

%\newpage

\vspace{0.1in}
%\begin{quote}
{\tt %\footnotesize
\begin{algorithm}
\ {\bf repeat} 
\ \ \ $\langle${\em statements in Action block} $\rangle$
\ {\bf until} $\langle${\em condition} $\rangle$
\ {\bf endrepeat} 
\end{algorithm}
}
%\end{quote}
%\vspace{0.2in}

The following example shows the code of a loop until statement for the pay employee problem.

%\newpage

\vspace{0.1in}
%\begin{quote}
{\tt \small
\begin{verbatim}
      set j = 0
      repeat
          display "Enter employee name: " 
          read empname 
          display "Enter employee number: " 
          read empnum 
          display "Enter hours worked: " 
          read hours 
          display "Enter hourly rate: "
          read hrate
          create emp_obj of class PayEmployee 
               using empname, empnum, hours, hrate 
          call compute_pay of emp_obj
          set net_pay = call get_npay of emp_obj 
          set taxes = get_tax() of emp_obj   // get tax amount
          display "Employee name: ", empname, 
               " Net pay: ", net_pay, " Tax amount: ", taxes 
          increment j
          add taxes to total_taxes
          add net_pay to total_npay            
      until j > num
      endrepeat    
\end{verbatim}
%\end{quote}
}
\vspace{0.1in}

\section{For Loop Structure}

The third type of loop structure is the {\em for\/} loop\index{for loop}. It explicitly uses a loop counter; the initial value and the final value of the loop counter have to be indicated. The {\em for\/} loop is most useful when the number of times that the loop is carried out is known in advance. The {\bf for} statement has the  keywords: {\bf for}, {\bf to}, {\bf downto}, {\bf do}, and {\bf endfor}. The {\bf for} statement has the general form:

%\newpage

\vspace{0.1in}
%\begin{quote}
{\tt %\footnotesize
\begin{algorithm}
{\bf for} $\langle${\em counter} $\rangle$ = $\langle${\em initial\_value} $\rangle${\bf to} $\langle${\em final\_value} $\rangle$
\ {\bf do}
\ \ \ Action block
{\bf endfor} 
\end{algorithm}
}
%\end{quote}
\vspace{0.1in}

On every iteration, the loop counter\index{counter} is automatically incremented. The last time through the loop, the loop counter has its final value allowed. In other words, when the loop counter reaches its final value, the loop terminates. The {\em for\/} loop is similar to the {\em while\/} loop in that the condition is evaluated before carrying out the operations in the repeat loop. 

The following portion of code uses a {\bf for} statement for the repetition part of the employee pay problem.

\vspace{0.1in}
%\begin{quote}
{\tt \small
\begin{verbatim}
   for j = 1 to num do
      display "Enter employee name: " 
      read empname 
      display "Enter employee number: " 
      read empnum 
      display "Enter hours worked: " 
      read hours 
      display "Enter hourly rate: "
      read hrate
      create emp_obj of class PayEmployee 
           using empname, empnum, hours, hrate 
      call compute_pay of emp_obj
      set net_pay = call get_npay of emp_obj 
      set taxes = get_tax() of emp_obj   // get tax amount
      display "Employee name: ", empname, 
           " Net pay: ", net_pay, " Tax amount: ", taxes 
      increment j
      add taxes to total_taxes
      add net_pay to total_npay
   endfor    
\end{verbatim}
%\end{quote}
}


%\include{ch08} % arrays
%\include{chap_inherit} % Inheritance
%\include{adv_oo} % Advanced OO concepts

\end{document}


