Chapter 18. Programming Constructs

CONTENTS
  •  Introduction
  •  Assignment Constructs
  •  Mathematical Operators
  •  Comparison Expressions
  •  Loop Constructs
  •  Choice Constructs
  •  Nested if...then...else Statement

Introduction

To create a program using the programming language of your choice, you must first understand the problem to be solved. This requires a generic set of tools that are not specific to any programming language. Having a set of logical tools at your disposal will not only help you design a solution, but will also help you understand existing programs. These tools will illustrate the logical flow of a program design.

Programming constructs are logical tools that can be used to create an algorithm, or logical steps, for your program. This chapter will give you an idea of how to programmatically solve problems. Various programming constructs are discussed in this chapter.

We will start with the most basic construct called assignments. Since programming logic needs additional elements to solve a problem, mathmatical operations and useful expressions are introduced. The choice and loop constructs are discussed, followed by data structures. This will provide you with the logical components necessary to create your own programming design.

A generic format, or pseudocode, is used to help gain an understanding of what these constructs do.

Pseudocode is the expression of a program or statements in a program with simple English that parallels the form of a computer language. Pseudocode is a valuable first step when designing a program. The examples found in this chapter are expressed in pseudocode, and are therefore programming language independent.

Assignment Constructs

A very basic programming contruct is the assignment. Various values, such as numbers and characters, can be assigned to variables within a program. Variables are locations in computer memory that have been assigned a name by the programmer.

Variables are typically assigned a type, which indicates what type of value is to be held in the variable. For example, a programmer may indicate that a variable will hold an integer, while another variable may hold a character, and yet another will hold a string of characters.

Before a variable is used, it needs to be declared. A variable declaration will occur only once and must occur before the variable is used by the program. It is good programming practice to list all the variables to be used at the top of a program. The type is assigned when the variable is declared. The following illustrates an example of a variable called BankAccount, which will hold an integer. The integer is indicated by int. The name BankAccount is assigned to a variable by the programmer. More can be found on this subject in Chapter 22, "C Programming Basics" and Chapter 23, "C++ Programming Basics".

int BankAccount 

Variables can be thought of as mailboxes. The mailbox is assigned a name by the programmer. The computer address can be thought of as the postal address to your mailbox. The computer knows where to find the mailbox in memory by its address. The mail placed inside your mailbox equates to the value assigned to it.

Each variable may contain a value, assigned by the programmer. A program may also assign a value to a variable during its execution. Both scenarios are known as assignment operations. Below is an example of an assignment operation in psuedocode. Most programmers will use the "=" as a short hand to denote assignment.

BankAccount = 100 

Previously we saw that the name BankAccount was assigned to a variable. BankAccount is in the computer memory, physically located at a computer address within memory. The variable BankAccount can be found when needed by the computer via the computer address. A programmer will reference the name BankAccount and the computer will translate that name into the corresponding computer address. After the variable is found in memory by the computer, the information inside can be looked at, changed, or deleted by the programmer. In the example above, the programmer is putting the value 100 inside the variable named BankAccount.

Mathematical Operators

Mathematical operations are a necessary part of many programs. Programming languages have symbols denoting the standard operators. These operators are as follows: addition, subtraction, multiplication, division, integer remainder, and exponentiation. When using mathematical operators in pseudocode, some programmers will spell out the operation, but most will use the customary symbols as short hand, such as:

Add 500 to BankAccount           or  BankAccount + 500 

The syntax for using mathematical operators on the value of a variable in a programming language is not necessarily intuitive. The example below illustrates this more clearly

BankAccount = BankAccount + 500 

Some programmers will use a statement like this in pseudocode. This statement shows that we want to add 500 to the BankAccount variable.

Let's assume the BankAccount variable already has the value 100 in it. The value 500 is added to the 100 resulting in a new value of 600. The value 600 is then assigned to BankAccount using the "=" symbol, copying over the original 100 value. The value held within the variable BankAccount is now 600.

Comparison Expressions

The simplest expression is a comparison. A comparison evaluates to a TRUE or FALSE. Less than, greater than, equal to, less than or equal to, greater than or equal to, or, as well as and are comparison expressions.

A comparison expression will take into account the values on both sides of the expression. The result will be either TRUE or FALSE. To evaluate an expression, it is typically easier to read it as a statement. Once you hear the statement, it becomes obvious whether whatwas said is TRUE or FALSE. Again, as seen in previoussections, the pseudocode below is presenting the expression in a way that many programmers will write it, as a short hand.

BankAccount < 1000 

The example above is stating, "The value in BankAccount is less than 1000." Either the statement is TRUE or FALSE.

If the value in BankAccount is 600, this expression evaluates to TRUE; "600 is less than 1000" is a true statement.

If BankAcount contains 2000, the expression evaluates to FALSE; "2000 is less than 1000" is a false statement.

Let's try another.

PhoneBill >= 50 

If PhoneBill contains 50, then the expression evaluates to TRUE; "50 is greater than or equal to 50" is a true statement.

If PhoneBill contains 51, then the expression evaluates to TRUE again; "51 is greater than or equal to 50" is a true statement.

But, if PhoneBill contains 49, then the expression evaluates to FALSE; "49 is greater than or equal to 50" is a false statement.

Loop Constructs

Loops can be divided roughly into two groups, depending on whether or not we can predict the number of times the loop will be executed. A definite iteration is executed a predetermined number of times. By contrast, the number of executions of an indefinite iteration is not known; the number is determined during the execution of the program.

An example of a definite iteration loop is a program that prints all the numbers between one and ten. A single statement can be inserted in a loop and run ten times instead of writing ten separate statements, one for each number printed:

LOOP ten times      Print number      Add one to number 

If we start with 1, the result of the definite loop would be:

1 2 3 4 5 6 7 8 9 10 

An indefinite iteration loop decides when to stop the looping while the program is running. A while loop is one example, loop while the number printed is 10 or less. Once the number is 11 or higher, the loop stops and the next statement outside the loop is executed:

WHILE number is less than or equal to 10       Print number       Add one to number 

If we started with 1 again, the result of the indefinite loop would be:

1 2 3 4 5 6 7 8 9 10 

Although the results are the same, the way we got there is different. In the first loop, a definite loop, we told it to start at 1 and loop ten times, and then stop. The second loop, an indefinite loop, we started at 1 again but it does not know how many times it will loop until it reaches the number 10.

Let's start with 5 and see what the results would be.

For the definite loop, we start with 5 and loop ten times:

5 6 7 8 9 10 11 12 13 14 

For the indefinite loop, we start with 5, but the loop only continues while the number is less than or equal to 10:

5 6 7 8 9 10 

The difference is that the definite loop was told to loop ten times, whereas the indefinite loop was told to loop while the number was less than or equal to 10. The definite loop didn't care whether it reached the number 10; it is instructed to loop ten times regardless. The indefinite loop had to loop five times to reach the number 10 then it stopped.

Loops can also be nested, one loop inside the other. One common area of use for nested loops is when dealing with tables. One loop can address the columns; another loop can address the rows.

Using the example in Figure 18-1, nested loops can help calculate the number of total hours worked by all employees.

Figure 18-1. Hours Worked Table

graphics/18fig01.gif

LOOP through three rows of employees               LOOP through seven columns of days of the week                           Add number of hours worked 

The outer loop will start with the first row, row one, labeled Liz. The inner loop will then loop through all the columns for row one, Sunday through Saturday, adding the hours worked, for a total of 40 hours.

After the inner loop is completed, control will then be passed back to the outer loop, which will move to row two, labeled Carly. Again, the inner loop will be activated and loop through all the columns for row two, Sunday through Saturday, adding the hours worked for a cumulative total of 62.

Once the inner loop is completed, it will again pass control to the outer loop and move to the row labeled Kit. The inner loop will once again loop through the days of the week, accumulating the hours. The end result is the total number of hours worked by all employees for that week, 86.

Choice Constructs

Logical constructs allowing choice are necessary for making decisions within a program. Choice constructs introduced in this section are the if...then...else and case constructs.

If...then...else Statement

An if...then...else construct allows a choice to be made. An evaluation is made on an expression. This expression is either TRUE or FALSE. If the expression is TRUE, any statements found in the then section are executed. If the expression is FALSE, any statements found in the else section are executed.

The following example illustrates an if...then...else statement where $10 will only be withdrawn if the account balance is at least $10.

IF bank account balance is equal to or greater than $10  THEN               Withdraw $10  ELSE               Print insufficient funds message 

If the account balance is $15, then the if statement is TRUE, and the withdraw is allowed.

If the account balance is only $5, then the if statement is FALSE, and the program executes the statement found in the else section, which is to print an insufficient funds message.

An else is not always necessary. If there is not an else, and the if is FALSE, then nothing is done and the program continues on. For example,

IF bank account balance is greater than $200  THEN               Add interest 

In this case, if the balance is below $200, then no interest is applied to this account. Nothing needs to be done, so the program continues without doing anything for this if statement.

Nested if...then...else Statement

The if...then...else statement can be nested, one inside the other. This possibility allows for sequential choice, as shown in Figure 18-2.

Figure 18-2. Nested if-then-else

graphics/18fig02.gif

Notice that the ELSE is associated with the outer IF statement and there is an if...then nested within the outer THEN section. Also note that the nested if...then does not have an ELSE associated with it.

Also, take note of how the if statements are indented. This is not necessary for most programs, but it is recommended so there is no confusion on the part of the programmer or anyone else trying to read the source code.

The figure shows that the outer THEN is executed if the bank account has $10 or more in it. The withdrawal occurs.

Since the nested if..then is within the outer THEN section, it is executed next. It checks to see if the previous withdrawal left the account empty. If it is, then the account is closed. If the account is not empty, then no action is taken since the nested if statement does not have an ELSE associated with it.

The program is finished executing both the outer and nested if statements.

Case Statement

A case statement uses the value of an expression to select one of several choices for execution:

CASE part number for UNIX software               101:  Print Linux               102:  Print RedHat Linux               103:  Print HP-UX               104:  Print Solaris  ELSE               Print bad part number  END 

The case statement attempts to match the part number it was given with the numbers in the list. If a match occurs, then the name of the part is printed. If no match occurs, the ELSE statement is executed and a bad part number message is printed.

For example, if the part number requested is 102, "RedHat Linux" is printed. If the part number is 200, the bad part number message is printed.

Data Structures

So what happens to the data in a program? Data or information in a program can get confusing. We need a way to organize it. Programming languages allow a programmer to logically group data into something called structures. When a programmer wants to refer to the data, the name of the structure can be used.

For example, a program may know about an employee's name and pay rate, as well as the pay rate for the employee's manager. We would not want to confuse the two if our program generates pay-checks. All the information regarding an employee can be put into a structure called Employee_Record and all the manager's information into a structure called Manager_Record. Both theEmployee_ Record and Manager_Record would have two entries, employee name and their respective pay rates.

STRUCTURE Employee_Record               Employee_Name               Hourly_Pay_Rate  END  STRUCTURE Manager_Record               Employee Name               Salary_Pay_Rate  END 

By organizing the information into logical structures, the readability and understandability of a program is enhanced. It is also important to make the names of the structures as descriptive as possible. Now a programmer can see what information regarding an employee and a manager the program knows about. Because this makes the program logic clearer, it is less likely that the employee pay rate would be confused with the manager pay rate.

CONTENTS


UNIX User's Handbook
UNIX Users Handbook (2nd Edition)
ISBN: 0130654191
EAN: 2147483647
Year: 2001
Pages: 34

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net