#message#
Page 3 of 3: The fourth stage – fourth-generation languages Various GUIs for generating code using fourth-generation languages are available. For example, you can use a report painter to specify the data required from a database and click a single button to generate the code necessary to compile a report. Fourth-generation languages also make use of libraries that provide code for common functions.
Question Sequence the stages in the evolution of software programming languages. Options: A.
Binary code B.
Assembly language
C.
High-level languages
D.
Fourth-generation languages
Answer Correct answer(s): Binary code is ranked the first stage. Binary code consists of 1s and 0s. It was the very first programming language, and is still the only language that a computer processor can understand. Assembly language is ranked the second stage. Assembly language uses short commands made up of abbreviated words and hexadecimal numbers. It's simpler for people to use than binary code, and so represents a second stage in the evolution of programming. High-level languages is ranked the third stage.
895
High-level languages were developed to make programs portable, and to simplify programming by including recognizable words in code. They overcame some of the limitations associated with assembly language and so represent a third stage in the evolution of programming. Fourth-generation languages is ranked the fourth stage. Fourth-generation languages enable programmers to generate code using high-level commands and, in some cases, a GUI. They represent the fourth, or current stage, in the evolution of programming.
2. Programming languages Many programming languages have been developed over the years, partly because different development situations call for different languages. For example, JavaScript is best when you want to implement interactive features or add functionality to a web site, whereas Java is best when you need to develop a program quickly and easily. The choice of programming language also depends on the system that will be used and the types of tasks that a program must perform. Specialized programming languages can be divided into five categories: high-level languages There are several specialized languages within the category of high-level languages. One of these is FORTRAN, which stands for Formula Translator. This language is best used for creating programs for mathematical or scientific work. Another example is COBOL, which stands for Common Business-Oriented Language and is used primarily in commerce. Rapid Application Development – or RAD – languages RAD languages were developed to enable developers to create powerful graphic user interfaces, or GUIs, with objects like mouse pointers, windows, scrollbars, and buttons. Examples of RAD languages are Visual Basic, Delphi, and Visual C#. web programming languages Web programming languages assist programmers in creating web sites. Web programming languages such as PHP and JavaScript enable developers to add interactivity or functionality to web sites. database programming languages, and Database programming languages were developed to fulfill one of the core functions of computers, namely systematic storage of data. Database languages such as SQL can be used to manipulate, retrieve, and store data in a database. scripting programming languages As users have become more knowledgeable and demand more from software, scripting programming languages were developed. They enable users to modify or build features in existing applications.
896
Scripting programming languages are based on high-level languages, but aren't exactly the same and typically take longer to master. An example of a scripting language is Visual Basic for Applications, or VBA, which is supported by most Microsoft programs. The evolution of programming languages has primarily been driven by technological improvements in computers. These improvements have been made in leaps and bounds since the first computer was designed in the 1940s. The evolution of computers can be described in five stages: first generation The first generation of computers began in 1945 with the invention of the Electronic Numeric Integrator and Calculator, also known as ENIAC. This computer weighed 30 tons and failed once every seven minutes. Computer programming was first invented to work with the ENIAC. second generation The second generation of computers began in 1948, when AT&T Bell Telephone Labs developed transistors that could replace the vacuum tubes used in ENIAC. Computers became more widely available, which prompted the development of better programming languages. third generation The third generation of computers began with the invention of integrated circuits, which grouped all the essential components of a computer into one unit. Computers in this generation took up less space and were more reliable than earlier computers. fourth generation, and The fourth generation of computers began in 1974, when the first microcomputers were invented. These computers were also known as personal computers, or PCs. The cost of computers decreased, which made them available to more people, and they also became much more powerful with the invention of semiconductor memory. fifth generation The fifth generation of computers began with chip technology – including technology associated with superconductors, quantum computing, and nanotechnology. It also involved the development of Very Large Scale Integration, or VLSI. Computers in this generation continue to get smaller and more powerful. They also display some signs of artificial intelligence. An example is games that let users play against the computer.
Question Match each programming language to the corresponding category. Options:
897
A.
Delphi B.
JavaScript
C.
SQL
D.
VBA
Targets: 1. RAD languages 2. Web programming languages 3. Database programming languages 4. Scripting languages
Answer RAD languages are used to develop GUIs with objects such as buttons and scrollbars. An example is Delphi. Web programming languages are used to add interactivity and functionality to web sites. An example is JavaScript. Database programming languages are used to retrieve and manipulate data in databases. An example is SQL. Scripting languages enable users to modify existing programs. An example is VBA. Correct answer(s): Target 1 = Option A Target 2 = Option B Target 3 = Option C Target 4 = Option D
Summary Computers can only do what they're told to do. They only understand binary code. Assembly language consists of abbreviated words and hexadecimal numbers, but its programs aren't portable. High-level languages make programs portable and use recognizable words. Fourthgeneration languages also use recognizable words. All programs must ultimately be translated into binary code before a computer can understand them, and this is done by compilers and interpreters. Many languages have evolved to fulfill different needs. The technological evolution of computers
898
has also driven the evolution of programming languages. The first generation of computers were extremely large and unreliable, but each subsequent generation has improved on this through the invention of transistors, integrated circuits, and technology such as nanotechnology, artificial intelligence and VLSI.
899
Software Development Life Cycle Learning Objectives
After completing this topic, you should be able to
recognize the steps in the software development life cycle
identify the differences between the waterfall and extreme programming software development methodologies 1. Development methodologies Creating a large software program is a complicated process. The size and intricacy of software, as well as the nature of the Information Technology industry, has made it necessary for this process to involve many people. Various software development methodologies have been developed in an attempt to establish a systematic method for creating software that can be followed by all programmers. It's advisable to adopt one of these methodologies and follow it throughout the lifetime of a software development project. Doing this helps programmers write software that not only works reliably but can be developed within a reasonable time. Two very different software development methodologies have emerged as common approaches:
the waterfall model, and
extreme programming The waterfall model divides the software development process into four distinct phases. The idea is that all focus is placed on only one phase at a time. Each part of a phase should be fully completed before a programming team moves on to the next phase. The four phases in the waterfall model are analysis Analysis is the first step and involves analyzing requirements to determine exactly what a program is supposed to do. Customers specify what they require of the program. Programmers then interpret these requirements to create a comprehensive list of program specifications. Once the list is complete and customers and programmers are in agreement, the analysis phase is signed off and won't be revisited. design
900
In the design phase, programmers plan how they're going to create a program. They decide which programming language, compiler, and other tools to use. They break down the program into sections that can be assigned to individual programmers to create. They also decide on the communication procedures they'll use to ensure completeness and consistency, and to prevent duplication of work. Once a program has been designed on paper and a deadline has been set, the design phase is complete. implementation, and The implementation phase is when a program is actually written. The programmers write code for the sections they've been assigned, following the plan created in the Design phase. Once all the sections have been written, they're put together to form the whole program. This is the end of the implementation phase. testing In the testing phase, the entire program is tested to check if it works properly. The programmers fix any problems they find and test again to ensure that the fixes haven't created new problems in other areas. The process of fixing and testing continues until all identifiable bugs have been fixed. The testing phase is then over. The program is complete and can be delivered to the customer. The waterfall model looks good in theory, but in practice its rigidity often causes problems. If one phase is stalled or not completed properly, it has a serious knock-on effect on the following phases. In particular a maintenance phase is missing from the waterfall model. It should be added to the waterfall model to make a more complete software development life cycle. The extreme programming method was developed to address the problems associated with the waterfall model. In this method, the phases in the process are integrated instead of distinct and isolated. The process flows back and forth through the phases until a program emerges, complete and free of bugs. Extreme programming includes four overlapping phases:
Coding
Testing
Listening, and
Designing
901
Extreme programming is an adaptive and people-oriented process. Because it's difficult for customers to envision all aspects and features of a program at the start, they're involved throughout the process. A program slowly evolves as the programmers work and communicate both with each other and the customer. The process constantly adapts according to the customer's needs. The general process followed in extreme programming includes four main steps: the customer communicates requirements The customer defines initial requirements for the program. This is a starting point only – the requirements may change as the process continues. programmers build a prototype A small team of programmers creates a simple prototype version of the program as a model for the customer to study and comment on. This helps the programmers determine whether they've understood the customer's requirements and whether they're on the right track. the actual program is built, and The team of programmers creates the actual program, constantly testing it, communicating with the customer, and incorporating necessary changes. additional features are added Once the basic program is complete and working, the team may add additional features requested by the customer.
Question Match each of the phases to the corresponding methodology. More than one phase may match to each of the methodologies. Options: A.
Analysis
B.
Design
C.
Implementation
D.
Coding
E.
Listening
Targets: 1. Waterfall model 2. Extreme programming
Answer 902
The four phases in the waterfall model are analysis, design, implementation, and testing. The four overlapping phases in the extreme programming method are coding, testing, listening, and designing. Correct answer(s): Target 1 = Option A, Option B, Option C Target 2 = Option B, Option D, Option E
2. Development life cycle Each of the software development methodologies has both advantages and disadvantages. Different models are followed in different organizations, and one model may be modified to suit different needs. Although different models are used and these are constantly evolving and being adapted, the modern software development life cycle follows a similar course in most cases.
Drill Down Home Page Typically, the modern software development life cycle includes five phases.
Page 1 of 2: Analysis In the Analysis phase of the software development life cycle, developers list the tasks that software must perform. They study the problems to be solved, and their causes and effects.
Page 2 of 2: Analysis The specific task that a program is required to perform is derived from a problem statement, which is a concise description of the problem that a customer needs to address. The software must provide a workable solution to this problem.
Page 1 of 3: Design In the Design phase, a program is designed. The aim is to meet the goals identified during the Analysis phase in a logical, efficient, and economical manner. The designers consider the existing software and hardware resources they can use to achieve the goal. If these are unsuitable, new software and hardware components may have to be designed.
903
The overall structure of the program is designed first. This is then broken down into smaller components of a manageable size, known as modules.
Page 2 of 3: Design To ensure that everyone involved can understand the design and visualize the necessary components of a planned software program, it's necessary to model the design. Some of the common modeling methods include flowcharts and process diagrams.
Page 3 of 3: Design Once the visual design of the program has been completed, the developers can continue the design process using pseudocode.
Code If student's grade is >= 60 Print "passed" else Print "failed" Pseudocode is used to bridge the gap between algorithms and programming languages. It provides an outline of a computer program, written in a format that can be easily converted into programming statements. Pseudocode isn't a specific programming language but is used to mimic any number of computer languages. It's especially useful if the software planners and programmers haven't yet decided which language to use to create software, or if they plan on porting the software to several languages or operating systems.
Page 1 of 3: Implementation During the Implementation phase, a program is written in a particular programming language. Each language has different advantages and disadvantages. For example, FORTRAN is a good language to use for processing numerical data, whereas LISP is good for artificial intelligence applications. Program code should perform the required tasks, and it must be readable so that other programmers can maintain it. Programs are often written in separate modules, with each module performing a particular task. Each module must function properly, both independently and in relation to the rest of the program.
904
Page 2 of 3: Implementation Computer programs often grow to be quite large and the code they contain may include a variety of dependencies. Because of this, the Implementation phase is often considered to have three functional steps that are cyclical. They are
coding
testing and debugging, and
optimizing code
Page 3 of 3: Implementation The coding step involves writing actual code. Testing and debugging is on-going. Programmers frequently compile their code while they're creating it to ensure that it uses the proper syntax and functions correctly. This ensures that they detect small code errors before they become larger problems. During testing and in the process of writing code, bugs are often found and then remedied on the fly. Programmers may also detect inefficiencies or identify more effective ways of making code work. So the process of optimizing code is also on-going.
Page 1 of 2: Testing Once all components of a program have been written and integrated, the software development life cycle reaches the testing phase.
Page 2 of 2: Testing The entire program is tested as whole to check if it runs smoothly and to detect any bugs. Any problems found are fixed and the program is tested again to ensure that the fixes didn't accidentally cause problems in other parts of the program. This process of fixing and testing continues until all the bugs that can be detected have been fixed.
Page 1 of 3: Maintenance During the maintenance phase, any errors and deficiencies in a program are identified and the necessary improvements are made, while preserving the program's integrity.
905
The use of design notes, well-commented code, and meaningful variable names can all contribute to easier maintenance of a program.
Page 2 of 3: Maintenance The improvements and fixes made during on-going maintenance often mean that new versions of a program are released. Programs can be developed in minor or sub-versions, each addressing particular bugs or inconsistencies. Or they can be upgraded in major versions that include new functionality and involve code rewrites. These major modifications are often designed to take advantage of new hardware or other compatible software and operating systems that have become available. Version control is the process of tracking and controlling the major and minor versions of a program. An important aspect of software development is understanding when the different kinds of version updates are necessary.
Page 3 of 3: Maintenance When a software program is released, it's usually packaged with certain software documentation that includes, for example, descriptions, comments, and help files. The release of new versions of the program should then also be accompanied by the release of new documentation. In the case of minor updates, documents or release notes identifying any changes should be provided. Major upgrades may require completely updated software documentation, with new help files and comments.
Question Sequence the phases in the software development life cycle. Options: A.
Analysis B.
Design
C.
Implementation
D.
Testing
E.
Maintenance
Answer Correct answer(s): Analysis is ranked the first phase.
906
The Analysis phase is the first step and involves determining exactly what a program is supposed to do. Design is ranked the second phase. The Design phase is the second phase. It involves determining how a program must be built to meet the goals set in the Analysis phase. Implementation is ranked the third phase. Implementation is the third phase, when a program is written in a particular programming language. Testing is ranked the fourth phase. Testing is the fourth phase, during which an entire program is tested to check that it works properly. Maintenance is ranked the fifth phase. Maintenance is the fifth phase. During this phase, any errors and deficiencies in the program are identified and the necessary improvements are made.
Summary Various software development methodologies have been developed. Two of the main approaches include the waterfall method and extreme programming. In the waterfall method, analysis, design, implementation, and testing are sequential and completely separate phases. In extreme programming, the phases of coding, testing, listening, and designing all overlap. A general software development life cycle includes a series of five phases – Analysis, Design, Implementation, Testing, and Maintenance.
907
Programming Basics Learning Objectives
After completing this topic, you should be able to
recognize the features of common programming methodologies
recognize the features of a good program 1. Common programming methodologies As customers' demands for program functionality continue to increase, software designers look for methodologies that enable them to create cheap but efficient programs quickly. Like natural languages, which develop in response to social needs, programming methodologies are developed in response to market needs. Applications don't only have to perform to specification – they must also be developed in the shortest possible time on the smallest possible budget. There are two common programming methodologies:
structured programming, and
object-oriented programming, or OOP The structured programming approach was developed after it was discovered in 1966 that any program can be written using just three structures: sequence The sequence structure is the execution of a set of statements in order. selection, and The selection structure is the selection of one particular statement, depending on a particular program state. repetition The repetition structure is the repetition of a statement until a particular program state is detected. With this discovery came the notion that program code can be thought of as a collection of related components – rather than as a long and linear sequence of commands that must be processed from beginning to end. Distinctive components of an application can be re-used, making it unnecessary to repeat code. One core component might be used by a number of ancillary components.
908
Grouping components that perform similar functions also enables modular development of an application, with development of each component constituting a separate development step. Third-generation programming languages are procedural languages, which means they process instructions step-by-step to arrive at a result. Procedural languages are considered suitable for a structured programming approach because they support sequence, selection, and repetition, while still representing a linear structure. OOP was developed in the 1980s. It takes structured programming's notion of modular components further by creating computer abstractions, or objects, to represent real-world objects. So OOP seeks to align the programming logic of an application with its associated realworld logic. This makes code easier to understand and debug. Each object in OOP has a set of properties that describe it. For example a car_aerial object might have extended or retracted as a property value. Each object also has a number of operators or methods associated with it. For example, the car_aerial object might have two methods – extend and retract. OOP retains the modular development principle from structured programming to enable easy debugging. Modular development is useful for OOP and structured programming because program errors tend to be associated with a single module. Structured programming and object-oriented programming can be used by themselves or in combination. Using a combination of the methods can help overcome shortcomings associated with each of the separate methods.
Question What are some of the features of structured programming? Options: 1. Any program can be written using just three structures 2. Statements are processed one after the other, from the beginning of a program to the end 3. Each component constitutes a development step 4. Components of the program reflect real-world objects
Answer Option 1: Correct. Structured programming is based on the theory that any program can be written using just three structures – sequence, selection, and repetition.
909
Option 2: Incorrect. Structured programming overcame the limitation of viewing processing as having to occur in a linear fashion. Option 3: Correct. Structured programming enables developers to plan a project using the development of each component, or module, as a separate development phase. Option 4: Incorrect. OOP takes modularity further than structured programming by mapping components and their logic to real-world objects. Correct answer(s): 1. Any program can be written using just three structures 3. Each component constitutes a development step
2. Features of good programs Regardless of whether a structured or object-oriented approach is taken, programming involves providing a computer with step-by-step instructions. A compiler processes the entire program and converts it into executable binary code. This can take some time. Alternatively, an interpreter executes instructions sequentially – line by line – returning the results for each line as a program runs. You can read the code for a very small program and follow its logic to determine how it works. However, most programs are large and can therefore be difficult to decipher. If you aren't the original programmer, this task becomes even more difficult. A good program has five features:
it's complete
it's efficient
it's usable
it's easy to maintain, and
it's readable A program is complete if all functionality planned in the design phase has been developed and is working properly. Programs should be written efficiently and sensibly.
910
Different computers have different hardware specifications, and inefficient or poorly-written code that worked on one computer may produce unexpected results on another. It's easy to write excessive amounts of code without taking into account how it will affect the performance and stability of a program. Usable programs are those that the intended end users find easy to operate. Usability depends on factors such as ease of input, interface design, and speed. Informative error messages and help files can also improve usability. Offline user documentation, such as a printed manual, is often preferred by users because it's easier to read than online help. However, online help files can be distributed and searched more easily, so they're commonly included with software. Maintaining a program involves making changes to a program after its implementation. A computer system seldom satisfies the needs of its users indefinitely – they'll soon think of ways to improve it. So any software should be easy to adjust and build on. Programmers other than those who originally designed a program should be able to understand and modify it, provided they're familiar with the programming language used. Readable code is easy to follow. You can use indentation to make code clearer. For example, a simple practice like indenting part of an IF statement to the right can make code easier to read.
Code (indented version) IF age < 12 THEN Classification := "child"; ENDIF (unindented version) IF age < 12 THEN Classification := "child"; ENDIF When programs contain hundreds or even thousands of lines of code, indentation – or lack of it – will significantly affect readability. Comments also increase the readability of a program. In all languages, you can ensure that text you add as comments won't be executed as actual code. Designers insert comments, code hints, or remarks to explain sections of code. For example, you might use a comment to explain the purpose of a section of code, to note where a new approach was tested, or to indicate that a portion of the code can be disabled for testing.
911
Different languages use different tags to indicate comments. Also, some languages – such as C++ and Java – differentiate between single-line comments and comment blocks.
Code // This is a comment on a single line. ...MISSING CODE... /* This is a comment of multiple lines. The compiler will ignore everything between the slash on the preceding line and the slash on this line. */ ...MISSING CODE... It's important to know how to identify comments in the programming language you're using. In C++, for example, braces {} indicate a block of commands – whereas in PASCAL, they indicate comments.
Question What are the features of a good program? Options: 1. It's complete 2. It's efficient 3. It's usable 4. It's easy to maintain 5. It's code is easy for other programmers to read 6. Its code is as short as possible 7. It has a small file size
Answer Option 1: Correct. A good program is one in which all functionality planned in the design phase has been developed and is working properly. Option 2: Correct. Coding should be efficient so that programs perform the required tasks quickly and are stable. Option 3: Correct. Usable programs are those that the intended end users find easy to operate. Option 4: Correct. A good program has code that's easy for any programmer familiar with the programming language to read and follow.
912
Option 5: Correct. A good program has code that's easy for any programmer familiar with the language that was used to read and follow. Option 6: Incorrect. If the other characteristics of a good program are present, a program can be considered good even if its code is very long. Also, practices like adding explanatory comments to code are recommended even if they add to overall code length. Option 7: Incorrect. It isn't always necessary for a program to have a small file size. This will depend on how the program will be distributed and used. Correct answer(s): 1. It's complete 2. It's efficient 3. It's usable 4. It's easy to maintain 5. It's code is easy for other programmers to read
Summary The first major programming methodology – structured programming – was developed in the late 1960s. It's based on three steps – sequence, selection, and repetition. OOP was developed in the 1980s as the second major programming methodology. It aims to align the programming logic of an application with associated real-world logic. Computer programs should be complete, efficient, usable, maintainable, and readable. You can help make code more readable by using suitable indentation and comments.
913
Program Development Tools Learning Objective
After completing this topic, you should be able to
recognize the functions of common program development tools 1. Tools for program development Programmers can use a range of development tools to simplify essential programming tasks. An Integrated Development Environment, or IDE, is a set of tools for software development that's integrated in one package. An IDE can have several functions:
it can help you write and edit a program's source code
it may display color-coded syntax for code
it may display relevant error notifications while you type
it can automate certain repetitive tasks
it can help you browse through code modules
it may compile code, and
it may enable you to use drag-and-drop functionality to create visual features and connect to databases Some IDEs provide templates for commonly used modules, objects and code blocks, and include context-sensitive shortcut menus that let you perform common tasks quickly. Some also include auto-complete functions, which can predict and complete functions and methods while you type. A popular IDE is Microsoft Visual Studio, which supports among others, development in C#, Java, and Visual Basic. Visual Studio also enables you to integrate testing of an application into the development life cycle, which improves overall productivity. Various tools are considered important in any software development cycle:
editors
compilers and interpreters
a debugger
914
help file generators
an installation program
a profiler, and
binary, decimal, and hex converters Editors may be simple text editors that are like word-processing applications but don't wrap words to the next line. Source code can be saved in ASCII files and you can even use Microsoft Word to write these files. However, word processors usually include formatting features and other hidden characters that aren't needed in the source files. Dedicated programming editors include additional features. For example, many code editors include line numbers that help you navigate through code. They may also offer automatic tabulation, color-coding of various elements, pop-up help information, and auto-complete functions. The first editors that were used were line editors. These were simple editors that accepted one line of code at a time. This had advantages on systems with limited amounts of memory, but programmers weren't able to navigate through and change existing code. An example of this kind of editor can be found in UNIX. Full-screen editors followed the line editors. These enable navigation and alteration of code. They're still in use today and are considered standard for software development. Some of the features offered by dedicated editors are syntax auto-completion Some editors can recognize a programming language and suggest possible commands, methods, or functions to complete entries you've started to type. You can then select the correct option to complete a command or statement. For example, if you choose an IF-THEN statement, a generic structure is created for you. syntax highlighting Some editors highlight completed commands, methods, or functions to help you distinguish them from the rest of your code. This makes the source much easier to read, understand, and navigate. the ability to view and edit multiple files Some editors enable you to open a number of files that form part of the same project at the same time. You can then switch between the open files, editing and saving them. stacked undo and redo commands
915
Most editors create a stack of changes that you've made and let you undo or redo these changes so you can test different code. support for macros, and Some editors enable you to create macros to automate tasks you perform often. For example if you want certain commands to be shown in uppercase, you can create a macro that will do this automatically. project management Large application projects usually consist of a number of files containing source code. Most editors have features that enable you to manage these files by showing them in a hierarchical tree structure. This organizes large projects and can help you manage and keep track of the files. Computer hardware can understand only machine language that consists of a set of binary instructions. Programming languages have evolved to the point where they're very natural and very much like human languages. But they still have to be translated into machine language before computer hardware can use them. To facilitate this, you can use either a compiler or interpreter to translate the program into machine language. Of the two, interpreters are less commonly used, although they still perform an important role in modern programming. A compiler reads the entire source code and translates it as a whole into machine language. It then stores this in a single file, usually an executable or .exe file. At this point you can distribute the program to users who can simply run the file to use the program. One reason that compilers are a more popular choice than interpreters is that the source code is hidden from users. Once a program is compiled you can use the program without needing the source code, but you'll have to recompile the program if you make any changes to the code. It's important to note that a program compiled for a Windows-based system will not work on a Macintosh-based system. This is because the compiled machine language contains instructions specific to the microprocessor. If you need a Mac version of the program, you'll need to recompile it specifically for Mac. An interpreter reads and converts code to machine language one line at a time. The interpreted code is stored in a computer's memory. Because computer memory is volatile, the interpreted code is discarded whenever the computer is shut down. This means that whenever you want to run the program, the source code has to be reinterpreted. So when you want to distribute a program to users, you have to give them access to the source code. This is the main reason why interpreters are rarely used commercially. Interpreters are popular in web programming, however. For example, web browsers use interpreters to read JavaScript. The reason for this is that not all web users use the same systems, so programs compiled in a specific machine language won't be accessible to everyone.
916
Debugging code involves removing errors from it. All errors must be removed before a program can be said to be complete. The two main types of errors in code are syntax errors, and Syntax errors occur when a programmer writes code that doesn't conform to the rules of the programming language. These are like grammar errors in human languages. If a compiler or an interpreter detects a syntax error, it will cease operation and report the error. logic errors Logic errors are errors in the design of a program. They occur when a line of code conforms to the rules of the language, but the code is based on flawed logic. Logic errors are less obvious than syntax errors, so programs may compile or be interpreted without these types of errors being reported. The errors are often discovered only when a program runs and it performs incorrectly or halts unexpectedly. A debugger runs a program one line at a time so that the programmer can examine it for errors. This is particularly useful for picking up and repairing logical errors. Code should be readable and easy to understand so that it can be maintained. Comments can be written into the code to ensure that it meets these requirements. You can use various methods to debug a program, one of which is called stepping. When you step through a program, each line is executed and you can also see which line of code is being read. If an error occurs, you can see which command caused it. You can step through code at the source level, but also view the machine code for each line as it executes. Stepping line by line is a practical way of debugging small programs that don't contain a lot of source code. For larger programs, you can use different methods to save time or to focus on particular parts of the source code. You can use breakpoints to skip over parts of code you know to be working correctly. You add a breakpoint to the first part of code where you suspect the problem could lie. When you do this and run a debugger, the debugger skips over the first part of the program and halts at the first breakpoint. You can then step through the next section of the program line by line. When you're debugging a large program with multiple subprograms, you can use two techniques to handle the source code more efficiently: step over, and
917
When you mark a subprogram with a step over command, the debugger executes the subprogram without debugging it line by line. You can use this method when you're confident the subprogram is working correctly. step out When you're stepping through a subprogram line by line and want to stop, you can use the step out command to do so. The debugger will then immediately stop stepping through the subprogram and continue with the code that follows it. The step method of debugging enables you to check the logical and working structure of a program. However, when you want to focus on checking the data used by a program, you can use the watching method. The watching method enables you to check the variables used in the program and to change the variable data to manipulate or test the results. This is especially helpful if a program is designed to handle and manipulate user data or calculate mathematical expressions. Creating good help files is an essential step in the development of most software. Help files are generally more accessible than user manuals because they're modeled as miniature web pages. This makes information and solutions to problems much easier to find. Programs similar to word processors can help in the creation of help files. These programs let you write, edit, organize, and format text, and create hyperlinks to different parts of a help file. To help users set up and run the programs you create, you can use installation programs to create installers for software. Programs often contain a number of different files, which, if bundled together, would prove cumbersome for users. You can use installation programs to specify exactly which files are needed by your program and where these files should be stored on disk. An installer configures the registry settings a user's computer will need to find and access all these files, and stores the files in the correct folders. You can also use a program installer to display user license agreements and graphics promoting your company's brand to users. You can use a profiler to optimize a program that consists of a number of parts. A profiler examines a program and identifies the parts of it that are used most frequently. These are the parts that should be optimized. Say a program accepts users' login credentials and then allows them to sort and search through a number of records. The login procedure will occur only once in a session but the search and
918
sort procedures may be called a number of times. So it's the search and sort procedures that should be optimized. Profilers use two methods to examine a program: sampling, and Sampling involves examining a program at fixed intervals and flagging the parts of the program that are used most often. These parts are called hotspots. instrumentation After sampling finds the hotspots, you use instrumentation to check each line of code in the hotspots in detail. You then concentrate on optimizing them to speed up the overall performance of the program. Binary, decimal, and hexadecimal converters are often required during program development. For example, color references are often in hexadecimal format, so a converter is useful in design applications. Similarly, a converter that converts between binary and decimal numbers may be useful in scientific applications.
Graphic Binary: 11111010000000011000 Decimal: 1024024.24 Hexadecimal: FA018 You can change the calculator bundled with Windows to Scientific view to access these types of converters. Similar tools are also available to Mac and Linux users.
Graphic The Windows calculator includes Hex, Dec, Oct, and Bin radio buttons.
Question Match each programming tool to its function. Options: A.
Editor
B.
Compiler or interpreter
C.
Debugger
D.
Help file generators
E.
Profiler
919
Targets: 1. A program for typing instructions for computers 2. Converts programming languages to binary code or machine language 3. Helps find and remove errors 4. Provides guidance to users 5. Examines code for the purpose of optimization
Answer You use editors to type and edit code instructions, which you save to a file. You use compilers and interpreters to convert programming code to binary or machine language so that it can be understood by computers. You use a debugger to find and fix or remove erroneous code from a program. You create help files to guide users in using a particular program. You use a profiler to examine code to determine which parts are executed most often. You can then focus on optimizing these parts of the code. Correct answer(s): Target 1 = Option A Target 2 = Option B Target 3 = Option C Target 4 = Option D Target 5 = Option E
Summary Programmers can use a number of tools to simplify the development process. A programming environment that provides a set of these tools is called an IDE. You use an editor to write source code, and convert programming language to machine language using a compiler or interpreter. You can run a debugger to check code for errors and use a program similar to a word processor to create help files for users. You can also create an installation for a program and use a tool called a profiler to optimize frequently used parts of the program.
920
Understanding Programming Basics Learning Objectives
After completing this topic, you should be able to
demonstrate basic knowledge of computer languages, programs and programmer tools
demonstrate knowledge of software methodologies and programming approaches Exercise overview To perform this exercise you need to understand the basics of software programming. This involves the following tasks:
understanding computer languages, programs and programmer tools and
understanding software methodologies and programming approaches
Understanding programming basics Question Computers have continued to evolve since they were first introduced. With this, programming languages have also evolved. Sequence the stages in the evolution of programming languages. Options: A.
Binary code B.
Assembly language
C.
High-level languages
D.
Fourth-generation languages
Answer Correct answer(s): Binary code is ranked the first stage. Binary code, which consists of 1s and 0s, represents the first stage in the evolution of programming languages. It's the basic code that computers understand. Assembly language is ranked the second stage. Assembly language consists of abbreviated words and hexadecimal numbers, and represents the second stage in the evolution of programming languages.
921
High-level languages is ranked the third stage. High-level languages represent the third stage in the evolution of programming languages. They use recognizable words, and they solved the non-portability problem associated with assembly language. Fourth-generation languages is ranked the fourth stage. Fourth-generation languages represent the fourth stage in the evolution of programming languages. They contain recognizable words and can be used to generate code based on high-level specifications.
Question Match each type of programming language to its description. Options: A.
Rapid Application Development, or RAD languages
B.
Web programming languages
C.
Database programming languages
D.
Scripting languages
Targets: 1. Used to create applications with graphic user interfaces 2. Used to create graphics and interactivity for web sites 3. Used to manipulate and retrieve data 4. Used by users to modify existing applications
Answer RAD languages such as Visual C can be used to create powerful graphic user interfaces – or GUIs – for applications. Web programming languages such as JavaScript and PHP were developed to add graphics and interactivity to web sites. Database programming languages such as SQL were developed for storing, manipulating, and retrieving data in databases. Users can use scripting languages to add or modify features in an existing application. Correct answer(s): Target 1 = Option A Target 2 = Option B
922
Target 3 = Option C Target 4 = Option D
Question What are the features of a good program in any language? Options: 1. It's complete 2. It's efficient 3. It's easy to use 4. It's easy to maintain 5. It's readable 6. It's basic 7. It's short
Answer Option 1: Correct. A good program is a program that includes all the required functionality and that has been completely tested. Option 2: Correct. Programs should be written so that they perform efficiently. Poorly designed code can hamper performance. Option 3: Correct. Usable programs are those that the intended users find easy to operate. Option 4: Correct. Good programs are easy to maintain. So programmers can easily make changes to them after their implementation. Option 5: Correct. Good code is easy for other programmers to read and follow. Option 6: Incorrect. Complicated programs can still be considered good if they're complete, efficient, usable, maintainable, and readable. Option 7: Incorrect. If the other characteristics of a good program are present, a program can be considered good even if it's long. Correct answer(s): 1. It's complete 2. It's efficient 3. It's easy to use
923
4. It's easy to maintain 5. It's readable
Question Match commonly used development tools with their functions. Options: A.
Editor B.
Compiler or interpreter
C.
Debugger
D.
Help file creator
E.
Profiler
F.
Installer
Targets: 1. Used for typing code instructions into a computer 2. Converts a programming language to binary code 3. Helps identify incorrect code 4. Assists in creating user guides 5. Studies source code for the purpose of optimization 6. Creates a file users run to set up the program on their computers
Answer You can use an editor to type and edit code instructions into a computer, and also save the code to a file. You use compilers and interpreters to convert programming code to binary to make the code understandable to the computer. You use a debugger to identify and correct or remove code errors in a program. You use a help file creator to generate help files to guide users in using a program. You use a profiler to examine source code and determine which parts are executed most often. You can then focus on optimizing these parts of the code. You use an installer to create a single file with a set of instructions and program files that will store a program in the correct folders on a user's hard drive. Correct answer(s):
924
Target 1 = Option A Target 2 = Option B Target 3 = Option C Target 4 = Option D Target 5 = Option E Target 6 = Option F
Understanding programming methodologies Question Which of these are phases in extreme programming? Options: 1. Coding 2. Testing 3. Listening 4. Designing 5. Implementation 6. Analysis
Answer Option 1: Correct. Coding is the phase in extreme programming when programmers write the code. Option 2: Correct. Testing is the phase in extreme programming when programmers test a program and fix errors. This occurs at various stages throughout development. Option 3: Correct. Listening is the phase in extreme programming when programmers get feedback from the customer. It occurs at various stages throughout development. Option 4: Correct. Designing is the phase in extreme programming when programmers design the final program. Option 5: Incorrect. Implementation is a phase in the waterfall model, rather than in extreme programming. Option 6: Incorrect. Analysis is a phase in the waterfall model, rather than in extreme programming.
925
Correct answer(s): 1. Coding 2. Testing 3. Listening 4. Designing
Question Sequence the phases in the waterfall model. Options: A.
Analysis B.
Design
C.
Implementation
D.
Testing
Answer Correct answer(s): Analysis is ranked the first step. Analysis is the first phase. It involves determining exactly what a program is supposed to do. Design is ranked the second step. Design is the second phase. It's when programmers plan how they're going to develop a program. Implementation is ranked the third step. Implementation is the third phase, when a program is actually written. Testing is ranked the fourth step. Testing is the fourth phase, when an entire program is tested to see if it works properly.
Question Which step is often added to the waterfall model to make a more complete software development life cycle? Options: 1. Debugging 2. Maintenance 3. Coding
926
4. Listening
Answer Option 1: Incorrect. Debugging is part of the Testing phase in the waterfall model. Option 2: Correct. The Maintenance phase was added to the waterfall model to make a more complete software development life cycle. Option 3: Incorrect. Coding is a phase in extreme programming. Option 4: Incorrect. Listening is a phase in extreme programming. Correct answer(s): 2. Maintenance
Question What are some of the features of structured programming? Options: 1. Any program can be written using just three structures 2. Each component constitutes a development step 3. Statements are processed one after the other from the beginning of a program to the end 4. Components of the program reflect real-world objects
Answer Option 1: Correct. Structured programming breaks all programming into three basic structures – sequence, selection, and repetition. Option 2: Correct. The development of each component of a program in structured programming can serve as a separate development step. Option 3: Incorrect. Structured programming overcomes the need to process an entire program from beginning to end. Option 4: Incorrect. Object-oriented programming, or OOP, uses objects that reflect real-world objects. Correct answer(s):
927
1. Any program can be written using just three structures 2. Each component constitutes a development step
Question What are some of the features of object-oriented programming – or OOP? Options: 1. Programming logic is aligned with its associated real-world logic 2. Objects consist of properties and methods 3. Statements are processed one after the other from the beginning of a program to the end 4. The entire application is consumed by a compiler at runtime
Answer Option 1: Correct. OOP takes modularity further than structured programming by mapping components and their logic to real-world objects. Option 2: Correct. Objects in OOP consist of properties that describe it and methods that perform actions. Option 3: Incorrect. Structured programming overcame the need to process an entire document. Option 4: Incorrect. Interpreters can test single objects within an application without consuming the entire program. Correct answer(s): 1. Programming logic is aligned with its associated real-world logic 2. Objects consist of properties and methods
928
Algorithms Explained Learning Objectives
After completing this topic, you should be able to
recognize factors to consider when writing an algorithm using the top-down approach
recognize how to structure algorithms 1. The top-down approach A computer is essentially an unintelligent machine. It can't perform tasks by itself – instead it simply processes sets of instructions. It steps through the instructions one at a time. The set of instructions followed by the computer to resolve a particular problem is known as an algorithm. A computer is a system that receives input, processes it, and generates output. To use an analogy, consider the process for making a cake. The problem to solve would be needing a cake for someone's birthday. You take an ingredient mix and bake it in an oven to create a cake.
Graphic Three part process: 1. input 2. process 3. output The input in the baking system is the ingredient mix, the process is baking the ingredient mix in the oven, and the output is a cake. If the input or the process isn't correct, a suitable cake won't be made and the problem of needing a birthday cake will persist.
Graphic Three part process: 1. input - ingredients 2. process - bake 3. output - cake The algorithm is the part that performs the processing – for example, combining the ingredients and then baking at 350 degrees for 40 minutes. The algorithm for making cake is simple. However, an algorithm can become extremely complex if a system must be able to accept a lot of input, perform a complicated process, and return output. It might consist of thousands of lines of code.
929
The top-down approach to algorithm writing addresses this problem by segmenting an algorithm into manageable parts, or modules. Each part is then further distilled into a number of subparts. This continues until the steps in the algorithm can't be further broken down into constituent steps. There are a number of important points to remember when writing algorithms:
you should include all the steps
all input conditions should be addressed
no step should be ambiguous, and
steps should result in output at some point First it's crucial to ensure that you include all the required steps in an algorithm. After the steps are divided into modules, you must ensure that no module or constituent step has been accidentally left out. Some valid output should always be rendered for any input, even if it's merely a message indicating that the input is insufficient. The process should take into account all the possible input conditions. So in an algorithm for boiling water, for example, you would include sub-steps for what to do if the kettle is already full or if the water is already hot. No step in an algorithm can be ambiguous or it won't be clear whether the step has been performed properly.
Code if X=10 then A if X=9+1 then B The steps should account for what to do when the desired output is generated. This means you need to put an end point in the list of instructions. Consider a text-based description of the steps in an algorithm for printing invoices.
Graphic The listed steps include retrieve customer details, retrieve all order details for that customer, and calculate the total invoice amount.
930
You need to ensure you include all the steps. So you need to further distill the calculating step into its constituent steps.
Graphic You add four sub-steps to the calculate the total invoice amount step: add 5% interest to orders one month or more overdue, add 10% to orders two months and over overdue, sum the orders, and add sales tax. You also need to ensure there is an end point. So you add the final step to print the invoice.
Graphic You add print the invoice as the final step. The two steps related to adding interest include some ambiguity. Should orders that are two months overdue be charged an extra 10%, or an extra 15%?
Graphic The first sub-step of calculate the total invoice amount is indicated: add 5% interest to orders one month or more overdue. So you change the step to add 5% only where the order is one month overdue, and 10% only when the order is two or more months overdue.
Graphic The first sub-step of the calculate the total invoice amount step is changed to add 5% interest to orders one month overdue. All input conditions have been considered. For example an account that is three months overdue is handled as well as an account that isn't overdue.
Question What are some of the guidelines for writing algorithms? Options: 1. All the constituent steps should be present 2. All input conditions should be considered 3. Only particular inputs should be anticipated
931
4. No end point to the instruction should be defined
Answer Option 1: Correct. You should distill the steps into their constituent parts until you can no longer break them up. Option 2: Correct. You should aim to receive valid output for any input condition. Option 3: Incorrect. All input conditions should be addressed. Option 4: Incorrect. An end point should be defined in the instruction for when the output conditions are met. Correct answer(s): 1. All the constituent steps should be present 2. All input conditions should be considered
2. Pseudo-code and algorithms After breaking down the steps of an algorithm to their most basic form, you can begin to think about converting the algorithm into a programming language. Pseudocode is a way to start converting your natural language instructions into a programming language. It can't be executed by a computer but it provides a framework on which to start writing the program code. Pseudocode uses natural language that conforms to certain broad rules of syntax. Guidelines for writing pseudocode are to
use simple English
use a new line for each instruction
use indentation
provide one entry and one exit point for the algorithm, and
group instructions into modules
932
You should use simple English to make pseudocode clear and concise. For example, the algorithm instruction find the difference between numbers A and B could be rewritten as difference = A-B in pseudocode. You should also use only one line for each instruction. Putting multiple instructions on one line makes the algorithm harder to follow. This should be re-written.
Code BEGIN GET A GET B CALCULATE difference = A-B PRINT difference END Each step should start on a new line.
Code BEGIN GET A GET B IF B EQUALS 10 THEN CALCULATE THE DIFFERENCE BETWEEN A AND B END You should use indentation to indicate the logical hierarchy between the instructions. For example, a THEN statement should be indented from its corresponding IF statement.
Code BEGIN GET DAY ASSIGN DISCOUNT VALUE IF DAY = MONDAY DISCOUNT = 15% IF DAY = TUESDAY DISCOUNT = 10% IF DAY = WEDNESDAY DISCOUNT = 5% ELSE DISCOUNT = 0% END ASSIGN DISCOUNT VALUE END Instead of using BEGIN and END tags to indicate the start and end of an algorithm, you can provide other entry and exit points.
Code 933
INPUT A INPUT B IF B = 10 THEN C = A - B ENDIF In this case, INPUT A is the entry point and ENDIF is the exit point. You should group instructions into modules that can each perform a distinct operation. You could also use indentation to mark appropriate modules.
Graphic This code is indicated: IF B = 10 THEN C = A - B ENDIF
Code INPUT A INPUT B IF B = 10 THEN C = A - B ENDIF Instead of re-writing modules when they're needed again, you can write them just once and simply call them as reusable objects when they're needed. Once you've written the pseudocode for a program, you can start to turn each instruction into actual code.
Code INPUT A INPUT B IF B = 10 THEN C = A - B ENDIF In this example, the C programming language is used.
Code
934
int a int b if (b c }
= 15; = 10; == 10) { = a - b;
Note In this case, the = sign is an assignment operator, and == is a comparison operator.
Question What are some of the guidelines for writing pseudocode? Options: 1. Use simple programming language 2. Use a new line for each module 3. Use indentation 4. Provide one entry and one exit point for the algorithm 5. Group instructions into modules
Answer Option 1: Incorrect. You should use simple natural language to write pseudocode. Option 2: Incorrect. You should use a new line for each instruction, rather than for each module. Option 3: Correct. You make pseudocode easier to read by using indentation. Option 4: Correct. The pseudocode should provide for single entry and exit points. Option 5: Correct. You should group related instructions into modules, which can be called in other parts of the code if they're needed more than once. Correct answer(s): 3. Use indentation 4. Provide one entry and one exit point for the algorithm 5. Group instructions into modules Most programming languages use certain conventions. You can apply these to pseudocode to make it easier to convert into actual executable code.
935
In particular, conventions relate to
getting input
performing operations and assigning values, and
providing output There are a number of common commands for handling input. You can use the GET command to acquire input from the keyboard.
Code BEGIN GET A GET B IF B EQUALS 10 THEN CALCULATE THE DIFFERENCE BETWEEN A AND B END And you can use the READ command to acquire input from other sources, such as a file. Processing of instructions in an algorithm involves arithmetic functions and assigning values to variables. In the case of pseudocode, values are assigned to nouns.
Graphic Two examples of assigning values to pseudo-code nouns are indicated: t=100 temperature=100 For example, in this pseudocode A and B were the nouns. You now give values to the variables A and B.
Code INPUT A INPUT B IF B = 10 THEN C = A - B ENDIF You can use the common arithmetic operator conventions in pseudocode: +
936
You can use the plus sign to add values. For example, the code total=total+1 adds 1 to the value of total and assigns the new value to the total variable. You can use the minus sign to subtract values. For example the code total=total-1 subtracts 1 from the value of total and assigns the new value to the total variable. * You can use the asterisk to multiply values. For example, the code total=total*2 multiplies the value of total by 2 and assigns the new value to the total variable. / You can use the forward slash to divide values. For example, the code total=total/2 divides the value of total by 2 and assigns the new value to the total variable. () You can use parentheses to indicate the order of precedence, where the content of the brackets is calculated first. For example, in the code total=3*(2+4), the addition will be performed before the multiplication function, resulting in total of 18 rather than 10. There are a number of ways to assign values to variables. Depending on the programming language used, you could use VAR or LET statements, or simply assign values.
Code total = 10
Note You use the = arithmetic operator to assign a value to a variable. For example, this BASIC programming language command stores the value 10 in the total variable.
Code LET total = 10 This JavaScript programming language command stores the value 4 in the total variable.
Code var total = 4
937
There are a number of ways to handle output, depending on which language you use. Each language uses its own syntax. in BASIC for example, you can use PUT, OUTPUT, DISPLAY, WRITE, and PRINT statements to handle output. The PUT, OUTPUT, and DISPLAY statements send output to the computer screen.
Code DISPLAY total You use the WRITE statement to store data in a file on the computer.
Code WRITE total In BASIC, you can use the PRINT statement to output data to the display. This statement will print the total variable.
Code PRINT total To print the word "total" instead of the value of the variable that has that name, you enclose the word in single quotation marks.
Code PRINT 'total'
Question Match the examples of commands to their functions. Options: GET
A. B.
READ
C.
PRINT
D.
WRITE
E.
LET
F.
VAR
938
Targets: 1. Input 2. Output 3. Assign values and arithmetic operations
Answer GET and READ are input statements. PRINT and WRITE are output statements. LET and VAR assign values to variables. Correct answer(s): Target 1 = Option A, Option B Target 2 = Option C, Option D Target 3 = Option E, Option F
3. Evaluating pseudocode Say you've written an algorithm in pseudocode that calculates the discount offered at a restaurant depending on the day of the week.
Code BEGIN GET DAY ASSIGN DISCOUNT VALUE IF DAY = MONDAY DISCOUNT = 15% IF DAY = TUESDAY DISCOUNT = 10% IF DAY = WEDNESDAY DISCOUNT = 5% ELSE DISCOUNT = 0% END ASSIGN DISCOUNT VALUE END The algorithm should include all the steps and can be broken into modules. This includes distilling each step into its constituent parts. In this case, there appears to be no way to further
939
distill the restaurant algorithm. The ASSIGN DISCOUNT VALUE block can be considered a module, as can the entire code sample.
Code BEGIN GET DAY ASSIGN DISCOUNT VALUE IF DAY = MONDAY DISCOUNT = 15% IF DAY = TUESDAY DISCOUNT = 10% IF DAY = WEDNESDAY DISCOUNT = 5% ELSE DISCOUNT = 0% END ASSIGN DISCOUNT VALUE END All possible input conditions need to be addressed and there should be a single entry point. The possible input conditions are the days of the week, or an empty value. In all these cases, the IF statements handle each eventuality and a catch-all ELSE statement handles any other condition. The entry point is the GET DAY statement.
Code BEGIN GET DAY ASSIGN DISCOUNT VALUE IF DAY = MONDAY DISCOUNT = 15% IF DAY = TUESDAY DISCOUNT = 10% IF DAY = WEDNESDAY DISCOUNT = 5% ELSE DISCOUNT = 0% END ASSIGN DISCOUNT VALUE END Each instruction should be free of ambiguity. All possible inputs should be accommodated, leading to valid error-free output.
Code BEGIN GET DAY
940
ASSIGN DISCOUNT VALUE IF DAY = MONDAY DISCOUNT = 15% IF DAY = TUESDAY DISCOUNT = 10% IF DAY = WEDNESDAY DISCOUNT = 5% ELSE DISCOUNT = 0% END ASSIGN DISCOUNT VALUE END The steps in an algorithm need to terminate at some point to result in output, and there should be a single point of output. In this case, each output is generated by populating the DISCOUNT variable with a value. This variable is the termination point of the algorithm.
Code BEGIN GET DAY ASSIGN DISCOUNT VALUE IF DAY = MONDAY DISCOUNT = 15% IF DAY = TUESDAY DISCOUNT = 10% IF DAY = WEDNESDAY DISCOUNT = 5% ELSE DISCOUNT = 0% END ASSIGN DISCOUNT VALUE END Pseudocode should use simple, natural language. In this case, basic English words have been used.
Code BEGIN GET DAY ASSIGN DISCOUNT VALUE IF DAY = MONDAY DISCOUNT = 15% IF DAY = TUESDAY DISCOUNT = 10% IF DAY = WEDNESDAY DISCOUNT = 5% ELSE DISCOUNT = 0%
941
END ASSIGN DISCOUNT VALUE END A new line should be used for each step in the instruction, and sub-instructions should be indented. In the example, each instruction is on a new line and the child elements are indented.
Code BEGIN GET DAY ASSIGN DISCOUNT VALUE IF DAY = MONDAY DISCOUNT = 15% IF DAY = TUESDAY DISCOUNT = 10% IF DAY = WEDNESDAY DISCOUNT = 5% ELSE DISCOUNT = 0% END ASSIGN DISCOUNT VALUE END
Case Study: Question 1 of 2 Scenario For your convenience, the case study is repeated with each question.
You're writing an algorithm that calculates the tip amount that should be given at a restaurant, depending on the level of service. To do this, you need to get the total bill, subtract the sales tax from the total before establishing the tip percentage – which is determined based on the level of service, and calculate the tip amount based on the subtotal and level of service. Answer the questions in order.
Question How is this pseudocode deficient? Code BEGIN GET BILL TOTAL GET SUBTOTAL BY SUBTRACTING TAX FROM BILL TOTAL INPUT "How was the service (poor, good or excellent)?" IF SERVICE WAS POOR THEN TIP AMOUNT EQUALS 10% IF SERVICE WAS GOOD THEN TIP AMOUNT EQUALS 15%
942
IF SERVICE WAS EXCELLENT THEN TIP AMOUNT EQUALS 20% Options: 1. Each instruction should be on a new line 2. The instruction shouldn't be ambiguous 3. Instructions should be grouped in modules 4. Input should be handled
Answer Option 1: Correct. GET BILL and GET SUBTOTAL should be on separate new lines. Option 2: Incorrect. The pseudocode handles all possible input conditions without ambiguity. Option 3: Incorrect. The full pseudocode sample is itself a module. Option 4: Incorrect. The pseudocode handles all possible input conditions. Correct answer(s): 1. Each instruction should be on a new line
Case Study: Question 2 of 2 Scenario For your convenience, the case study is repeated with each question.
You're writing an algorithm that calculates the tip amount that should be given at a restaurant, depending on the level of service. To do this, you need to get the total bill, subtract the sales tax from the total before establishing the tip percentage – which is determined based on the level of service, and calculate the tip amount based on the subtotal and level of service. Answer the questions in order.
Question How is this pseudocode deficient? Code BEGIN GET BILL TOTAL GET SUBTOTAL BY SUBTRACTING TAX FROM BILL TOTAL
943
INPUT "How was the service (poor, good or excellent)?" IF SERVICE WAS POOR THEN TIP AMOUNT EQUALS 10% IF SERVICE WAS GOOD THEN TIP AMOUNT EQUALS 15% IF SERVICE WAS EXCELLENT THEN TIP AMOUNT EQUALS 20% Options: 1. The pseudocode should use indentation 2. There is no end point 3. Each instruction should be on a new line 4. Instructions should be grouped in modules
Answer Option 1: Correct. You should indent instructions that are sub-steps of a parent line. THEN statements should be indented from their IF statements. Option 2: Correct. The pseudocode still needs to calculate and print the tip amount, which is the subtotal divided by the tip amount. Option 3: Incorrect. Each new instruction is already on a new line. Option 4: Incorrect. The entire sample constitutes a single module. Correct answer(s): 1. The pseudocode should use indentation 2. There is no end point
Summary A computer program receives input, processes it, and generates output to solve a problem. The algorithm is what performs the processing. When there is a lot of input and a system has to perform a complicated process, keeping track of the output can be challenging. The top-down approach to algorithm writing addresses this problem. Algorithms should include all the steps, all input conditions should be addressed, no step should be ambiguous, and steps should terminate to result in output at some point. You can use pseudocode to start converting natural language instructions into an algorithm in preparation for a programming language. Pseudocode should use simple language, use a new line for each instruction, use indentation, provide one entry and one exit point for the algorithm,
944
and group instructions into modules. You can apply conventions that most programming languages use to make pseudocode easier to convert into executable code.
945
Creating an Algorithm Learning Objectives
After completing this topic, you should be able to
create a letter-counting algorithm
create a tax-calculating algorithm Exercise overview In this exercise, you're required to identify the input, process, and output elements of problem statements in order to construct an algorithm. This involves the following tasks:
using a defining table to create a letter-counting algorithm, and
using a defining table to create a tax-calculating algorithm
Creating a letter-counting algorithm You want to write an algorithm that asks the user to enter two words and then adds the number of letters in the first word to the number of letters in the second word, and then displays total number of letters in both words.
Question To help create the algorithm, you decide to use a table to identify the input and output elements and the order in which they should appear. The algorithm has to be designed to display a result as output immediately after a user enters a word. It also has to return the total number of characters in two words. Assign each step, which is explained using pseudocode, to the appropriate column. Options: A.
word1_length
B.
total
C.
word2_length
D.
word1
E.
word2
Targets: 1. Input
946
2. Output
Answer The word1 step is the first input parameter. The word2 step is the second input parameter. These are all the inputs that the process requires. The word_length1 step corresponds to the number of letters in the first input , word1. The word_length2 step is the number of letters in the second input , word2. And total is the sum of the number of letters in both words. These are the three outputs of the process. Correct answer(s): Target 1 = Option D, Option E Target 2 = Option A, Option C, Option B In the algorithm, the numbers of characters are the required output. In this case, the algorithm is symmetric – meaning that you can re-order the inputs to get the same total. If the algorithm is well designed, it will shut down if it encounters a problem such as invalid or missing input. A good algorithm doesn't assume the availability of required elements. You could extend the algorithm to receive a variable number of words.
Code Input 1: word1 Input 2: word2 ...PROCESS... Output 1: word1_length Output 2: word2_length Output 3: total
Question Next you want to structure the processes that change the input elements to the desired output elements. Place the processes – which are described in pseudocode – in the order in which they should appear in the algorithm. Options:
947
A. GET word1 GET word2 B.
CALCULATE word_length1 CALCULATE word_length2
C.
ADD word_length1+word_length2=total
D.
PRINT total
Answer Correct answer(s): GET word1 GET word2 is ranked the first step. The first step is to retrieve, or "GET", the relevant parameters – in this case, the two words entered by a user. CALCULATE word_length1 CALCULATE word_length2 is ranked the second step. As the second step, the algorithm must calculate the length of each of the two words entered by the user. ADD word_length1+word_length2=total is ranked the third step. As the third step, you add the number of characters in each of the two words to calculate a total. You can do this using an ADD operation. Note that this operation can easily be expanded to accept more than two inputs, making the algorithm more dynamic and flexible. PRINT total is ranked the fourth step. The final step is to print the result, which is the total number of characters in the two words a user has entered. Every programming language has an equivalent of a PRINT operation that prints to the standard output device – usually the screen. Standard output can be redirected to a printer, a file, or some other device. The defining table has been completed and you can now create the algorithm.
Graphic A table with three columns and one row is labelled Defining table: the column headers are Input, Process, and Output. The input is GET word1 and GET word2, the process is CALCULATE word_length1, CALCULATE word_length2, and ADD word_length1+word_length2=total, and the output is PRINT total.
Question Which is the correct algorithm for the defining table you just created?
948
Options: 1. GET word1 GET word2 CALCULATE word1_length CALCULATE word2_length ADD word1_length TO word2_length PRINT total 2. GET word1 CALCULATE word1_length CALCULATE word2_length ADD word1_length TO word2_length PRINT total 3. GET word1 GET word2 CALCULATE word1_length and word2_length ADD word1_length TO word2_length PRINT total
Answer Option 1: Correct. You GET the input, CALCULATE and ADD the numbers of characters as the process, and print the total as the output. Option 2: Incorrect. Input for word2 has not been handled in this example. Option 3: Incorrect. There is ambiguity here about whether the CALCULATE function applies to the word2_length. Correct answer(s): 1. GET word1 GET word2 CALCULATE word1_length CALCULATE word2_length ADD word1_length TO word2_length PRINT total
Creating a tax-calculating algorithm You now want to create an algorithm that calculates and prints the tax payable on an invoice total. The tax and total should then be passed back to the calling routine.
Question
949
To create the algorithm, you use a defining table to identify the input and output elements and the order in which they should appear. Match each option with the correct column. Options: GET invoice total
A. B.
CALCULATE tax final_amount = invoice total + tax
C.
PRINT tax PRINT final_amount
Targets: 1. Input column 2. Process column 3. Output column
Answer GET invoice total is an input command. The invoice total is required for the process to work. CALCULATE tax and final_amount = invoice total + tax are process commands. The invoice total is added to a tax value to result in the final_amount. PRINT tax and PRINT final_amount are output commands. The process results in values for tax and for the final_amount. Correct answer(s): Target 1 = Option A Target 2 = Option B Target 3 = Option C
Question Identify the correct algorithm for the defining table you created. Options:
950
1. GET invoice total CALCULATE tax final_amount = invoice total + tax PRINT tax PRINT final_amount RETURN tax AND final_amount TO CALLING ROUTINE 2. GET invoice total CALCULATE tax final_amount = invoice total + tax RETURN tax AND final_amount TO CALLING ROUTINE PRINT tax PRINT final_amount
Answer Option 1: Correct. This is the correct algorithm to calculate and print the tax payable on an invoice total. Option 2: Incorrect. RETURN tax AND final_amount TO CALLING ROUTINE will finish before the algorithm is complete. This code is written using the spaghetti programming method. Correct answer(s): 1. GET invoice total CALCULATE tax final_amount = invoice total + tax PRINT tax PRINT final_amount RETURN tax AND final_amount TO CALLING ROUTINE Two algorithms have been created – one to count letters in words and the other to calculate tax.
951
Structuring an Algorithm Learning Objectives
After completing this topic, you should be able to
recognize examples of sequence, selection, and repetition
express inputs, processes and outputs as an algorithm 1. Sequence, selection, and repetition In the early 1960s, the coding method used by programmers was less logical and linear than it's today. This led to the method being called spaghetti code.
952
Spaghetti code relied on the GOTO command to skip unnecessary lines of code in a program. The GOTO command recognized lines of code by a name or number, depending on the programming language. For example, if a certain criterion was met in a line of code, the GOTO command could then move the program along to a later line of code.
Graphic Five lines of code are shown, code skips from 3 to 5 as follows: 1: CODE 2: CODE 3: CODE GO TO 5 4: CODE 5: CODE The GOTO command resulted in a lot of movement backwards and forwards through the code, which was difficult to follow logically. If a program used too many GOTO commands, it would end up with a complex structure that was prone to errors. Consider writing a program to print address labels. You would need the program to understand the difference between a mailbox and a street address. The example code shows how spaghetti code would rely on the GOTO statement to differentiate between the two address types.
Code 21: 22: 23: 24: 25: 26: 27: 28:
PRINT name IF address IS empty GOTO 25 PRINT address GOTO 26 PRINT postbox PRINT city PRINT state GOTO 17 Structured programming on the other hand would use IF, THEN, and ELSE statements in a linear and logical sequence.
Code IF street IS empty THEN
953
PRINT postbox ELSE PRINT address ENDIF PRINT city PRINT state The end result of both methods is the same, but it's far easier to follow the structured programming method due to its linearity. Structured programming uses three control structures as the basis for writing a program: sequence The sequence control structure ensures that a program runs instructions in sequence and performs each instruction once only. Instructions aren't repeated or skipped, unless repetition control is applied. selection, and The selection control structure is used when a choice has to be made. These choices depend on the conditions defined by the programmer. repetition The repetition control structure is used to repeat a certain section of code until a specific condition is met. Consider sequence control in an example of code for printing information. Each command runs only once to perform the necessary print action. The sequence of the printed address in this case is the sequence the programmer specifies – the recipient's name, followed by the recipient's street address, and so on.
Code 21: 22: 23: 24: 25:
PRINT PRINT PRINT PRINT PRINT
name address postbox city state
The most commonly used commands for capturing information for selection control are IF, THEN, and ELSE.
Code
954
IF street IS empty THEN PRINT postbox ELSE PRINT street Some programming languages require that you end any IF statement with a keyword, such as ENDIF.
Code IF street IS empty THEN PRINT postbox ELSE PRINT street ENDIF PRINT city PRINT state In certain scenarios, you may not need to use the ELSE statement if there is no alternative action to take.
Code
ELSE
In this example, you're creating a list of adults. Persons under the age of 18 shouldn't be added to the list. There is no ELSE statement because there is no action to take if a person's age is under 18.
Code IF age >= 18 THEN STORE name IN adult_list ENDIF This is known as a null ELSE statement. The repetition control structure is used to repeat a section of code until a specific condition is met. This is also known as looping.
955
The commands used to create a loop are FOR, WHILE, and DO. FOR is the most common of these commands and is used across multiple languages. In this example, a WHILE loop is terminated using the ENDWHILE command. Different programming languages may use different methods to terminate loops.
Code seats_allocated = 0 WHILE seats_allocated < 5 DO GET booking PRINT ticket ADD 1 to seats_allocated ENDWHILE This code is used to book seats on a minibus. The seats_allocated value is defined before the loop starts because the loop needs a value to compare seats_allocated to. The code runs until the value of seats_allocated reaches 5, at which point the ENDWHILE command runs.
Question Consider the code example. Which type of control structure is being used? Code GET name PRINT name GET address PRINT address GET postbox PRINT postbox GET city PRINT city GET state PRINT state Options: 1. Sequence 2. Selection 3. Repetition
Answer 956
Option 1: Correct. The sequence control structure ensures that instructions are run once in sequence. No instructions are repeated or skipped. Option 2: Incorrect. Selection control is used when a choice needs to be made. This code represents a sequence control in which instructions are run one at a time in the specified order. Option 3: Incorrect. Repetition control repeats a certain part of the code until a specific condition is met. This code represents a sequence control in which instructions are run one at a time in the specified order. Correct answer(s): 1. Sequence
2. Inputs, processes, and outputs An algorithm is a set of instructions used to solve a problem. Creating this is the first step a programmer will take when developing a computer program. The programmer constructs algorithms using simple language before beginning to use any actual computer code. An algorithm takes an input, processes it, and produces an output. These different parts of an algorithm are written using different types of words. The processing in an algorithm is usually described using verbs such as "find", "calculate", or "sort." The inputs or outputs are described using nouns, adjectives, or adverbs. Examples are "time", "speed", or "distance." It's common to use a defining table, or input-process-output table, as the basis for developing an algorithm.
Graphic A table with three columns and one row is labelled Defining table: the column headers are Input, Process, and Output. The row details are Input: Get booking, Process: Add 1 to seats allocated, and Output: Print ticket. The process elements become statements in the algorithm. The input and output elements become arguments for the statements in the algorithm. An argument is similar to the object of a sentence. In this example, "booking" is an argument. Say you need to calculate the speed that a courier must drive in order to cover a certain distance in a specific time. You have to take time, speed, and distance into account, and then create an algorithm that will process all these variables.
957
To create a defining table, you'd need to identify what your input, process, and output are. In this case, the inputs are distance and time, the process can be defined as "calculate", and the output is speed. Using this table, you can create your algorithm. Once you have calculated the output, you need to specify a process or operation to make the output visible. An example is an instruction to display the speed.
Code BEGIN Convert kilometers_to_miles DISPLAY 'Enter the distance in kilometers.' GET kilometers miles = kilometers * 0.625 DISPLAY kilometers 'kilometers = ' miles 'miles.' END Once you've defined your input, process, and output using the defining table, you can start to create the algorithm.
Question You're developing an algorithm to print shipping labels for certain packages in a post office. Match each statement to the correct column in an input-process-output table. Options: A.
INPUT "More [Y/N]?"
B.
WHILE answer = "Y"
C.
PRINT Label
Targets: 1. The input column 2. The process column 3. The output column
Answer INPUT "More [Y/N]?" is an input statement. Users have to input Y or N, depending on whether they want to print labels.
958
After confirming that the label is needed, the algorithm processes any statements inside the WHILE command. So the WHILE command belongs in the process column. A label is created as output using the PRINT statement. Correct answer(s): Target 1 = Option A Target 2 = Option B Target 3 = Option C An algorithm usually follows a certain structure. It begins with a name that describes the algorithm's function.
Code CALCULATE overdraft_interest Once the algorithm has been named, any instructions that occur between the name and the END statement must be indented. This makes it easier to identify each of the instructions.
Code WHILE answer="Y" DO READ name READ address PRINT label DISPLAY "Print another?" ENDWHILE You need to indent every new control structure that is introduced. The indentation will return to its previous level at the end of a control structure.
Code CALCULATE overdraft_interest WHILE answer="Y" DO READ name READ address PRINT label DISPLAY "Print another?" ENDWHILE
959
The different components of the defining table can be broken down into one or more pseudocode instructions.
Graphic A table with three columns and one row is labelled Defining table: the column headers are Input, Process, and Output. The row details are Input: GET info, Process: Do action, and Output: DISPLAY result. The components of the input and output columns are used as arguments for the instructions in an algorithm. Say you need to convert kilometers to miles. You can create an algorithm to express this. You begin by defining the inputs, processes, and outputs. The input is the distance in kilometers, the process is the conversion of miles to kilometers, and the output is the distance in miles.
Graphic A table with three columns and one row is labelled Defining table: the column headers are Input, Process, and Output. The input is "GET kilometers", the process is "CALCULATE miles = kilometers * 0.625", and the output is "DISPLAY enter distance in km" and "DISPLAY miles." You can then use the table to create an algorithm that converts kilometers to miles.
Graphic A table with three columns and one row is labelled Defining table: the column headers are Input, Process, and Output. The input is "GET kilometers", the process is "CALCULATE miles = kilometers * 0.625", and the output is "DISPLAY enter distance in km" and "DISPLAY miles."
Code BEGIN Convert kilometers_to_miles DISPLAY 'Enter the distance in kilometers.' GET kilometers miles = kilometers * 0.625 DISPLAY kilometers 'kilometers = ' miles 'miles.' END
960
Even with a defining table to help you create the algorithm, you'll probably need to refine it several times.
Question You need to calculate the speed a courier must drive to cover a given distance within a given time. Identify the correct pseudocode algorithm to express this. Options: 1. Get distance Get time Calculate speed by dividing distance by time Display speed 2. Get distance Calculate speed by dividing distance by time Display speed 3. Get distance Get time Calculate speed by adding distance to time Display speed
Answer Option 1: Correct. This algorithm can correctly calculate speed as it has the requisite distance and time as inputs. Option 2: Incorrect. This algorithm can't calculate speed without a value input for time. Option 3: Incorrect. This algorithm can't correctly calculate speed as it uses the incorrect process of adding distance to time. Correct answer(s): 1. Get distance Get time Calculate speed by dividing distance by time Display speed
Summary You can use the three control structures – sequence, selection, and repetition – to help structure an algorithm you're creating.
961
An algorithm can also be broken down into three different components – input, output, and process. Once you've identified the different components, you can begin to build the algorithm.
962
IF Statements Learning Objectives
After completing this topic, you should be able to
recognize the features of IF statements
recognize how programming languages process IF statements 1. The features of IF statements Structured programming includes three control structures – repetition, sequence, and selection. The repetition control structure represents the process whereby a series of commands are executed until specified criteria are met. The sequence control structure represents the order in which statements in a program are executed. The selection control specifies when and how a statement is chosen to execute, depending on what the programmer requires. In code, IF statements are part of the selection control structure. Statements like these, which are part of the selection control structure, are also known as conditional statements. Programmers use IF statements to select which statements to execute based on whether conditions are true or false. IF statements come in a variety of forms. The most basic form is IF...THEN, which instructs a program to check whether a specified condition is true before running a specified statement block. If the condition in an IF...THEN statement is met - is true - the statement block associated with the THEN keyword will be executed. If the condition isn't met – is false – the statement block associated with the THEN keyword is ignored and the program moves to the next line of code after the IF..ENDIF structure.
Syntax IF [condition is true] THEN [statement block] END IF
Note In the BASIC language, the IF structure is terminated with the END IF statement.
963
An IF statement compares one value or variable to another to determine whether a condition is true or false. For example, it may check whether the amount a customer spends is greater than $1000, and if it is, will apply a discount of 5% because the condition is true.
Code IF purchases > 1000 THEN total = purchases * 0.95 END IF This makes the statement a binary decision. Either the statement is true, with a binary value of 1, or it's false, with a binary value of 0. In IF statements, you can use six different comparison operators to compare items: = The equal sign (=) is the equals operator and is used to evaluate whether two values are the same. For example, 5 = 9 results in false. The equals operator can also be indicated by two equal signs (==), as is the case in "squiggly bracket" languages such as C and Java. < The less than operator is indicated by the less than sign (<) and is used to evaluate whether one value is less than another. For example, the statement 5 < 9 results in true. > The greater than operator is indicated by the greater than sign (>) and is used to evaluate whether one value is higher than another. For example, 5 > 9 results in false. <= The less than or equal to operator is indicated by the less than sign combined with the equal sign (<=) and is used to evaluate whether one value is equal to or lower than another value. For example, 5 <= 9 results in true. >=, and The greater than or equal to operator is indicated by the greater than sign combined with the equal sign (>=) and is used to evaluate whether one value is equal to or higher than another value. For example, 5 >= 9 results in false. <> The not equal to operator is indicated by the less than and greater than signs together (<>) and is used to evaluate whether one value is not equal to another value. Whereas 5 = 9 results in false, 5 <> 9 results in true. In "squiggly bracket" languages such as C and Java, the not equal to operator is indicated by !=.
964
A selection condition can compare multiple factors to another factor, as in the expression (a+b)>c. Consider an example of an IF statement written in the BASIC programming language. It will print a specified message on the receipts of customers only if they spend $1000 or more at a store.
Code IF client_purchases >= 1000 THEN PRINT "We value your generous patronage." END IF PRINT client_name If a customer spends less than $1000, the program ignores the code after the THEN statement and prints only the client's name. In other words, when the IF statement is false, the program will continue to run the code after the END IF keyword, which marks the end of the IF...THEN statement. You can include an ELSE clause to run alternative code if the condition in an IF statement evaluates as false. This type of statement is referred to as an IF...THEN...ELSE statement.
Graphic In the image there is a question box which asks :Is condition 1 met? Then there are two branches – the top branch will execute if the value is true or the bottom branch will execute if the statement is false.
Syntax IF [condition is true] THEN [statement1 block] ELSE [statement2 block] END IF If the condition in the IF statement is met - is true, statement1 block will run. If the condition isn't met – is false, statement2 block – included after the ELSE keyword – will run.
Syntax IF [condition is true] THEN
965
[statement1 block] ELSE [statement2 block] END IF If you manage an online store, you might want to let your customers know when a specific item is in stock. You can create an IF...THEN...ELSE statement that checks if there is stock of an item and then displays a different message depending on whether the item is or isn't available.
Code IF Stock >= 1 THEN PRINT "Stock available" ELSE PRINT "Out of stock" END IF
Note The code shows a BASIC language example of the IF…THEN…ELSE construct. This is an example of an IF...THEN...ELSE statement written in Pascal. It specifies that if the price of an item plus tax is equal to or greater than 120, a program must execute the first WRITELN command. If the sum of the price and the tax is less than 120, the second WRITELN command will execute.
Code if (price+tax) >= 120 then writeln ('total price is equal to or more than 120') else writeln ('total price is less than 120'); This example of an IF...THEN...ELSE statement is written in C. It specifies that if a client's balance is negative, a computer program must print the message "overdrawn." If the balance is positive, the program will print "in credit."
Code if (balance < 0) { printf("overdrawn \n"); } else
966
{ printf("in credit \n"); }
Note Note that IF statements written in C don't end with the END IF keyword. The \n used in the printf statement is called an escape sequence - after printing something to the screen you usually want to print something on the next line. If there is no \n then a next printf command will print the next string on the same line. An IF statement that doesn't include an ELSE clause is also sometimes referred to as a null ELSE statement.
Code IF [purchases are more than $1000] THEN [apply a discount of 5%] END IF
Question Which descriptions of IF statements are correct? Options: 1. An IF statement tells a program which code to execute based on whether a condition is true or false 2. The statement block in an IF...THEN statement will execute only if a specific condition is met 3. An IF...THEN...ELSE statement will run alternative code if a specified condition isn't met 4. All statement blocks in an IF...THEN...ELSE will run if a condition is met 5. A null ELSE statement is a statement that includes an ELSE command
Answer Option 1: Correct. IF statements are part of the selection control structure. They enable a program to select code to execute based on whether a condition is true or false. Option 2: Correct. In an IF...THEN statement, the statement block after the THEN keyword runs only if the condition specified after the IF keyword is met. Option 3: Correct. If the condition in an IF...THEN...ELSE statement isn't met, the statement block after the ELSE command will run.
967
Option 4: Incorrect. If the specified condition is met, only the first statement block in an IF...THEN...ELSE statement will run. Option 5: Incorrect. A null ELSE statement is an IF statement that doesn't include an ELSE statement. It's the same as a simpleIF...THEN statement. Correct answer(s): 1. An IF statement tells a program which code to execute based on whether a condition is true or false 2. The statement block in an IF...THEN statement will execute only if a specific condition is met 3. An IF...THEN...ELSE statement will run alternative code if a specified condition isn't met
2. Processing IF statements Sometimes you may need to include more than one condition in an IF statement. This is known as a compound condition.
Graphic In this diagram representing an IF statement, a compound condition is created, which first tests Requirement 1 AND Requirement 2 then another AND is used to join the condition to a second condition which tests Requirement 3 OR Requirement 4. Then based of the results of the compound condition either the true or false branch will be executed. Compound conditions use the logical operators AND or OR. The AND operator joins two conditions so that an expression evaluates as true only if both those conditions are met. If only one or other of the conditions is met, the expression evaluates as false. The OR operator specifies that an expression is true if either of two conditions is true. So if one condition is true and the other is false, the result of the expression is true. Another operator that can be used in an IF statement is the NOT operator. It is used to specify that an expression is true only if a condition is actually false. Consider an IF...THEN...ELSE statement with a condition that uses the AND operator to check whether a cup of coffee meets each of four conditions.
Code IF coffee AND cream AND sugar AND (Jamaican OR Javanese) THEN
968
accept coffee ELSE decline coffee END IF The cup of coffee has to have cream, coffee, and sugar, and to be either Jamaican or Javanese to be accepted.
Graphic The relevant code is: coffee AND cream AND sugar AND (Jamaican OR Javanese) Here is the code again.
Code IF coffee AND cream AND sugar AND (Jamaican OR Javanese) THEN accept coffee ELSE decline coffee END IF The final condition uses the OR operator to specify that the coffee can be either Jamaican or Javanese.
Graphic The relevant code is: (Jamaican OR Javanese) Here is the code again.
Code IF coffee AND cream AND sugar AND (Jamaican OR Javanese) THEN accept coffee ELSE decline coffee END IF Consider an IF...THEN...ELSE statement written in Pascal to check air pressure and wind direction.
969
Code if ((air_pressure > 1000) and (wind = 'nw')) then writeln ('It is likely to rain.') else writeln ('It probably won't rain.') ; The statement is considered true only if the conditions for air pressure and for wind direction are both met. If both conditions are met, the message "It is likely to rain" will display. If one or both conditions fail, the message "It probably won't rain" will display. A nested IF statement is an IF statement within another IF statement. You can use this type of statement to specify multiple, separate conditions.
Graphic In the image there is a question box which asks: Is condition 1 met? Then there are two branches – the top branch will execute if the value is true or the bottom branch will execute if the statement is false. The true branch then has a question box which asks: Is condition 2 met? If condition 2 is met, then a second set of true conditions will execute. If the condition is not met, then a different set of conditions will execute. Say you need to write a C++ program that checks the overdraft charges for savings and checking accounts. The program first checks whether an account has a positive balance. If it does, the first printf statement will run.
Graphic The relevant code is: if (balance >= 0) { printf ("Account in credit");
Code if (balance >= 0) { printf ("Account in credit"); } else { if (account_type == 'c')
970
{ printf ("Checking account overdraft charge is $15 \n"); } else { printf ("Savings account overdraft charge is $12 \n"); } } If the account has a negative balance, the program needs to check what type of account it is. So the nested if statement after the else keyword will run.
Graphic The relevant code is: else { if (account_type == 'c')
Code if (balance >= 0) { printf ("Account in credit"); } else { if (account_type == 'c') { printf ("Checking account overdraft charge is $15 \n"); } else { printf ("Savings account overdraft charge is $12 \n"); } } The program will then check the type of account that has the overdraft. If the account type is "c", the first printf statement in the nested if statement will run. If the account type isn't "c", the second printf statement will run.
Graphic The relevant code is: printf ("Checking account overdraft charge is $15 \n");
971
} else { printf ("Savings account overdraft charge is $12 \n"); } }
Code if (balance >= 0) { printf ("Account in credit"); } else { if (account_type == 'c') { printf ("Checking account overdraft charge is $15 \n"); } else { printf ("Savings account overdraft charge is $12 \n"); } } Consider a BASIC program that calculates interest earned on positive credit card balances. It uses a nested IF statement to determine the interest calculated for three types of credit cards.
Code IF (card_type = "gold") THEN IF (account_type = "business") THEN print "Interest calculated at 6%" ELSE print "Interest calculated at 5%" END IF ELSE print "Interest calculated at 4%" END IF This statement first checks the type of card. If it's a gold card, the account will earn 5% or 6% interest, depending on whether it's a standard gold card or a business gold card. If it isn't a gold card, the account will earn 4% interest.
Code 972
IF (card_type = "gold") THEN IF (account_type = "business") THEN print "Interest calculated at 6%" ELSE print "Interest calculated at 5%" END IF ELSE print "Interest calculated at 4%" END IF If the card is a gold card, the first nested IF statement is run. The nested IF statement determines if the account is a business account. If it is then the interest is set to 6%. If the account isn't a business account, the ELSE statement is run, which sets the interest at 5%.
Graphic The relevant code is: IF (card_type = "gold") THEN IF (account_type = "business") THEN print "Interest calculated at 6%" ELSE print "Interest calculated at 5%" END IF
Code IF (card_type = "gold") THEN IF (account_type = "business") THEN print "Interest calculated at 6%" ELSE print "Interest calculated at 5%" END IF ELSE print "Interest calculated at 4%" END IF If the card isn't a gold card, the nested IF statement is skipped. The interest is then set at 4%.
Graphic The relevant code is: ELSE print "Interest calculated at 4%" END IF
973
Code IF (card_type = "gold") THEN IF (account_type = "business") THEN print "Interest calculated at 6%" ELSE print "Interest calculated at 5%" END IF ELSE print "Interest calculated at 4%" END IF
Question You've written a simple program in C that uses IF statements. What does the nested IF statement accomplish? Code if (numDozens < 12) { numDozens = numDozens + 1; gross = gross + 1; if (countToADozen < 12) { countToADozen = countToADozen + 1; } else { num = num + 1; cout << numDozens << " dozen.\n"; countToADozen = 0; } } else { cout << "12 dozen.\n"; done = true; cout << "TOTAL = " << gross << "\n"; cout << "One gross has been counted\n"; }
Options: 1. It will increment the variable countToADozen by 1 until the value of countToADozen equals 12 2. It will increment the variable numDozens by 1 until the value of numDozens equals 12 3. It will increment the variable countToADozen by 1 if the value of countToADozen is greater than 12
974
4. It will set the value of countToADozen to 0 until the value of numDozens is greater than 12
Answer Option 1: Correct. Until the value of countToADozen equals 12, 1 will be added to the value for countToADozen. As soon as the value of countToADozen is equal to 12, the nested IF statement will break. Option 2: Incorrect. The nested IF statement is used to determine the value of countToADozen, not numDozens. Option 3: Incorrect. Once the value of countToADozen is equal to 12, the nested IF statement will break and control will pass back to the first IF statement, so no more values will be added to countToADozen. Option 4: Incorrect. countToADozen will be set to 0, only if the value of countToADozen is already 12 or more when the nested IF statement starts executing. Correct answer(s): 1. It will increment the variable countToADozen by 1 until the value of countToADozen equals 12
Summary Programmers use IF statements to select which code statements to execute based on whether specified conditions are met. In an IF...THEN statement, a statement block after the THEN keyword executes only if the condition is true. An IF...THEN...ELSE statement works in the same way, but if the condition is false, a statement block after the ELSE keyword is executed. You can use the AND and OR logical operators in IF statements to create compound conditions. You can also use the NOT operator to specify that a statement block must execute if a condition is false. You can use nested IF statements to include multiple conditions and associated statement blocks.
975
CASE Statements Learning Objective
After completing this topic, you should be able to
identify the features of CASE statements 1. How to use CASE statements Although an IF statement is useful for making simple decisions, using IF statements for more than two options can become unnecessarily complicated.
Graphic In the diagram, when processing starts, an IF condition is tested. If it's false, the ELSE code executes and the program ends. If the condition is false, then another IF condition is tested. If this condition is false, the ELSE code executes and the program ends. If the condition is true, then the true code statements execute and the program will end. Nested IF statements can be used to deal with code that requires three or more options. However, the more options there are, the harder it becomes to understand and follow multiple nested IF statements. This can make it difficult to debug code. You can use CASE statements to replace complicated nested IF statements.
Syntax SELECT CASE variable CASE value_1 first statement block CASE value_2 second statement block CASE value_x xth statement block CASE ELSE optional ELSE clause/statement block END SELECT A CASE statement consists of comparison options in a list, only one of which can be valid. Each option condition is unique and has an associated statement block. If a particular option is matched to the case variable, its associated statement block is executed – or run.
976
Graphic In this diagram, there is a Start command, then there are three boxes, one below the other, with conditions for testing. Each of these conditions is tested and will execute code according to the result of the condition. After a condition is met the CASE statement ends. If no condition is met, it will default to the OTHER block. Each CASE option can evaluate as many expressions as necessary. The final CASE ELSE statement caters for all other possibilities not handled by a specific option. In this example, if a value falls within the range defined for value_1, the first statement block will run. If a value falls within the range defined for value_2, the second statement block will run. The same applies to value_x and the xth_statement block.
Syntax SELECT CASE variable CASE value_1 first statement block CASE value_2 second statement block CASE value_x xth statement block END SELECT You might use a selection statement, for example, to define student's grades based on their test results. The code for doing this can be written using one of two methods. You can use IF statements, which use Boolean variables, such as IF (result = ―F‖), to determine if statements are true or false. This example is correct, but is lengthy and hard to follow.
Code IF result THEN PRINT END IF IF result THEN PRINT END IF IF result THEN PRINT
= "F" "You got an F" = "D" "You got a D" = "C" "You got a C"
977
END IF IF result = "B" THEN PRINT "You got a B" END IF IF result = "A" THEN PRINT "Good job! You got an A" END IF Alternatively, you can use a CASE statement, which is much shorter and easier to follow. Each CASE statement must have an option for every possible result. Each result is checked to determine which range it falls into. If a result falls within a specific range, the statement associated with that range is executed.
Code SELECT CASE result CASE ―F‖ PRINT "You got an F" CASE ―D‖ PRINT "You got a D" CASE ―C‖ PRINT "You got a C" CASE ―B‖ PRINT "You got a B" CASE ―A‖ PRINT "Good job! You got an A" END SELECT CASE statements aren't limited to checking that a variable matches a single value. You can check for multiple values in a case line using the SELECT CASE statement.
Code SELECT CASE Result CASE ―F‖ PRINT ―Failure is not an option‖ CASE ―D‖, ―C‖, ―B‖ PRINT ―Try harder next time‖ CASE ―A‖ PRINT ―Excellent work!‖ END SELECT
978
For example, you can write code that prints different messages depending on the result. In this example, if a learner gets a B, C, or D, the message "Try harder next time" will print. This demonstrates how multiple conditions can be incorporated into one CASE statement. You can also check for number variables using a SELECT CASE statement. If you have a list of numbers in sequence, you can specify the number for each case.
Graphic The relevant code is CASE 1,2,3,4,5,6,7,8,9,10,11
Code SELECT CASE Dozen CASE 1,2,3,4,5,6,7,8,9,10,11 Result = ―Less than a dozen‖ CASE 12 Result = ―One dozen‖ CASE 13 Result = ―A baker‘s dozen‖ END SELECT You can also write a list of sequential numbers using the TO command. For example, you have 11 potential results for the first CASE statement. Instead of specifying each CASE number, you can simply list them as CASE 1 TO 11.
Code SELECT CASE Dozen CASE 1 TO 11 Result = ―Less than a dozen‖ CASE 12 Result = ―One dozen‖ CASE 13 Result = ―A baker‘s dozen‖ END SELECT You can use comparison operators, such as >, <, or <>, to expand the ways that the CASE statement can be used.
Code
979
SELECT CASE Age CASE IS < 12 ageStatus = "Pre-teen" CASE 13 TO 19 ageStatus = "Teenager" CASE 20 ageStatus = "Unsure" CASE IS > 20 ageStatus = "Adult" END SELECT In many programming languages, you can use comparison operators by using the IS or TO keywords. The IS keyword checks the tested variable against the expression listed after it. The TO keyword checks the tested variable using a range of values.
Code SELECT CASE Age CASE IS < 12 ageStatus = "Pre-teen" CASE 13 TO 19 ageStatus = "Teenager" CASE 20 ageStatus = "Unsure" CASE IS > 20 ageStatus = "Adult" END SELECT
Note Curly bracket languages, like C and C++, don't allow you to use comparison operators in a switch statement. In this SELECT CASE example, a different status message displays depending on the age group into which the value of the Age variable falls. When you've created a range of CASE statements and need to use a variable that doesn't fit into any of the specified ranges, you can use the ELSE statement. In this example, a final case determines that if the value of Age is 65, the corresponding status is retired.
Graphic
980
The relevant code is: CASE 65 ageStatus = “Retired”
Code SELECT CASE workStatus CASE IS < 12 ageStatus = "Can‘t work" CASE 13 TO 19 ageStatus = "Student" CASE 20 TO 64 ageStatus = "Time to find a job" CASE 65 ageStatus = "Retired" END SELECT In another example, the ELSE command defines the status of anyone who falls outside of the defined categories, which cover people up to the age of 64. If someone is 65 years or older, the ELSE command will run and the status will be set as retired.
Graphic The relevant code is: CASE ELSE ageStatus = “Retired”
Code SELECT CASE workStatus CASE IS < 12 ageStatus = "Can‘t work" CASE 13 TO 19 ageStatus = "Student" CASE 20 TO 64 ageStatus = "Time to find a job" CASE ELSE ageStatus = "Retired" END SELECT
Question Identify the features of CASE statements.
981
Options: 1. They can be used to replace complicated nested IF statements 2. They work by choosing a single option from a list of options 3. They can only evaluate a limited number of expressions 4. They need to cater for every possible result
Answer Option 1: Correct. Nested IF statements can become unnecessarily complicated when you're dealing with multiple options. You can use a CASE statement in this situation to replace the IF statements. Option 2: Correct. The option that's chosen determines which statement block will run. Option 3: Incorrect. A CASE statement can be used to evaluate as many expressions as necessary. Option 4: Incorrect. In many programming languages, CASE statements don't have to have options for every possible result. Correct answer(s): 1. They can be used to replace complicated nested IF statements 2. They work by choosing a single option from a list of options
2. Implementing CASE statements Not all programming languages use the CASE syntax. Instead they may use different syntax to serve the same function. Say you want to print descriptions of three comparison operators – <, >, and = – using both Pascal and C. Pascal uses the CASE statement to display the description of each operator.
Code case comparator of '<' : writeln ("less than"); '>' : writeln ("greater than"); '=' : writeln ("equal"); else writeln ("invalid"); end
982
C uses the switch and break statements to select and display a description of a specific comparison operator.
Code switch (comparator) { case '<': printf ("less than"); break; case '>': printf ("greater than"); break; case '=': printf ("equal"); break; default: printf ("invalid"); }
Keyboard Sequence By convention, most keywords in C are written using lowercase. Like SELECT CASE, the switch statement is used to select a result from a set of options. In languages like C, the break statement ends the execution of the switch block. The switch statement processes case statements until it finds a match. After a case statement runs, the break statement halts further processing of case statements. In this example, if the value is the greater than operator (>), the printf command will print "greater than." The break command will then halt processing of any other commands in the switch statement, and processing will resume after the closing brace (}).
Code switch (comparator) { case '<' : printf ("less than"); break; case '>' : printf ("greater than"); break; case '=' : printf ("equal"); break; default : printf ("invalid"); }
983
Question Which line of code executes when the value of ageStatus is 70? Code SELECT CASE ageStatus CASE IS < 12 workStatus = ―Can‘t work‖ CASE 13 TO 19 workStatus = ―Student‖ CASE 20 TO 64 workStatus = ―Time to find a job‖ CASE ELSE workStatus = ―Retired‖ END SELECT Options: 1. workStatus = ―Retired‖ 2. workStatus = ―Time to find a job‖ 3. workStatus = ―Student‖ 4. workStatus = ―Can‘t work‖
Answer Option 1: Correct. If a value falls outside the ranges defined by case statements, as it does if ageStatus is equal to any value greater than 64, the code after the else keyword will execute. Option 2: Incorrect. This code will execute only if the value of ageStatus falls in the range from 20 to 64. In this example, the value of the variable is 70. Option 3: Incorrect. This code will execute only if the value of ageStatus falls in the range from 13 to 19. Option 4: Incorrect. This code will execute only if the value of ageStatus is less than 12. Correct answer(s): 1. workStatus = ―Retired‖
Summary Instead of using potentially complex nested IF statements to handle three or more options in code, you can use CASE statements. Using this type of statement, you can provide a list of
984
options and instruct a program to run a statement block associated with whichever option applies. In many programming languages, you use the keywords SELECT CASE at the beginning of a range of CASE statements to identify the variable being checked. Some programming languages use different syntax for the same purpose as SELECT CASE. For example, C uses switch statements, with break statements to halt processing once an option has been selected.
985
Solving a Problem using Branching Statements Learning Objectives
After completing this topic, you should be able to
identify the steps in solving a basic programming problem
complete branching statements in C code 1. Solving a basic programming problem To simplify the programming process, which can be defined as the process of solving a programming problem, you can follow four main steps:
analyze the problem, which is typically captured in a problem statement
create a defining table
create an algorithm in pseudocode, and
write the algorithm code To understand the problem completely, you might need to start by doing some research to put the problem in context. Once you fully understand the problem, you can define its functional requirements by analyzing it in terms of its input, processing, and output elements. The second step is to create a defining table that determines which data the program should process and what the result should be. After identifying the input, process, and output elements, you can compile a table that lists the elements under the relevant headings.
Graphic A table includes Input, Process, and Output columns. Input and output elements are generally nouns in a problem statement, and processes are identified using verbs. It's processes that will transform the input into the output. Every input element has an associated process to acquire the data associated with it. And every output element has a process to display or otherwise act on the data that has been processed. Some elements may not be explicitly mentioned in the problem statement, so you need to determine these from the context and the expected results.
986
Graphic In the first line of this diagram an Input flows into a process and on the second line a Process flows to an Output. There isn't necessarily a one-to-one mapping of processes to input and output elements. This is because many different procedures or functional elements may be required to act on a single input element or to produce a single output element.
Graphic In this diagram there are 3 Inputs, the first two flows into one process and the 3rd flows into one process. The two processes then flow out into one Output. In large modern object-oriented programs, such as those created using C++ or Java, hundreds of functional elements known as classes may be needed to model and implement the required behavior.
Graphic A large circle is in the center and four smaller circles are attached to it. The third step is to create an algorithm in pseudocode that outlines how the program will function. This should take the form of a detailed, ordered set of instructions that have to be carried out. But it doesn't implement these in any specific programming language. Instead of using a specific programming language, a pseudocode algorithm uses clear and precise language to describe the instructions that have to be carried out, and in what order.
Code IF x > y THEN PRINT "X is: "; x END IF The fourth and final step is to convert the pseudocode into a programming language. Pseudocode algorithms should be written in such a way that they can be encoded into any programming language. Each programming language has different strengths and weaknesses, so you may have to consider the purpose of the program you're designing before choosing the language you'll use to create it.
Question 987
Sequence the steps for solving a programming problem. Options: A.
Analyze the problem statement
B.
Create a defining table
C.
Create an algorithm in pseudocode
D.
Write the algorithm in a programming language
Answer Correct answer(s): Analyze the problem statement is ranked the first step. The first step is to create and analyze a problem statement, defining its input, processing, and output elements. Create a defining table is ranked the second step. After analyzing the problem statement, you compile a table that defines the relevant input, processing, and output elements. Create an algorithm in pseudocode is ranked the third step. After compiling a defining table you create an algorithm in pseudocode. This involves writing a detailed, ordered set of instructions that the program will have to execute. Write the algorithm in a programming language is ranked the fourth step. As the last step, you convert the pseudocode you've created into a programming language that's suitable given the purpose of the program.
2. Branching statements in C code You work for a theater that's developing a program to manage bookings and ticket sales. You've been asked to write the part of the program that calculates the total price of tickets bought by customers. The theater has three sections, each represented by a code, and each section has a limited number of seats. When tickets are requested, the program must check seat availability before printing the tickets. After a ticket sale, it must update the number of allocated seats to prevent over-booking. The theater includes three sections:
the front section, which has 50 seats costing $30 each
the center section, which has 100 seats costing $20 each, and
988
the back section, which has 50 seats costing $10 each You start by considering the problem statement. There are two inputs you'll need to use – the number of seats requested and where they are located.
Graphic The Input column of the table has two entries – no_of_seats and theater_section. The rest of the table is still empty. Next you consider the required processes. The program needs to retrieve the number of requested seats and the theater section from the customer's input. Then it needs to match the customer's section to the code that represents it. It also has to check for seat availability and calculate the total price of a ticket.
Graphic The Process column of the table now contains the following pseudocode: GET no_of_seats GET theater_section SELECT code for relevant theater_section CHECK available_seats CALCULATE price PRINT tickets Last the program has to print the ticket, update the number of seats allocated for that section, and calculate and display the total cost of the ticket to the customer.
Graphic Two additional processes have been added to the Process column – CALCULATE seats_allocated and DISPLAY total_price. There are two outputs for this problem. The program must display the total cost of the ticket to the customer and print the ticket. Both outputs involve a process and should be indicated in the table as such.
Graphic Two entries have been added to the Output column – total_price and tickets. Once you've finished creating a defining table, you can use it to guide you through the rest of the process.
989
You can now start preparing the pseudocode algorithm for the program. The program must branch to the code that deals with each of the theater sections – front, center, and back – depending on which one the customer wants. The program must also check that enough seats are available in that section, calculate the ticket price, and update the number of seats allocated. You start the algorithm by creating statements that represent the processing needed to capture the input data. There are three sections in the theater, so you use a CASE statement to branch to the relevant code for each theater section.
Graphic The relevant code is CASE theater_section IS
Code GET no_of_seats GET theater_section CASE theater_section IS front : center : back : ENDCASE The IF statement first checks how many seats are currently available by subtracting the number of seats already allocated from the maximum capacity of the section, which is 50 in this case. The IF statement then compares the difference to the number of seats requested.
Graphic The relevant code is IF no_of_seats <= (50-front_allocated) THEN
Code GET no_of_seats GET theater_section CASE theater_section IS
990
front : IF no_of_seats <= (50 - front_allocated) THEN ticket_price = no_of_seats * 30 PRINT ticket front_allocated = front_allocated + no_of_seats ELSE OUTPUT "Not enough seats left in this section" ENDIF center : back : ENDCASE The program continues processing a ticket request only if tickets in the relevant section are available. It then calculates the ticket price and prints the ticket.
Graphic The relevant code is ticket_price = no_of_seats * 30 PRINT ticket
Code GET no_of_seats GET theater_section CASE theater_section IS front : IF no_of_seats <= (50 - front_allocated) THEN ticket_price = no_of_seats * 30 PRINT ticket front_allocated = front_allocated + no_of_seats ELSE OUTPUT "Not enough seats left in this section" ENDIF center : back : ENDCASE Once the tickets have been printed, the number of seats sold is added to the total number of seats already allocated in the section. This ensures that the number of seats listed as available is kept up to date.
Graphic
991
The relevant code is front_allocated = front_allocated + no_of_seats
Code GET no_of_seats GET theater_section CASE theater_section IS front : IF no_of_seats <= (50 - front_allocated) THEN ticket_price = no_of_seats * 30 PRINT ticket front_allocated = front_allocated + no_of_seats ELSE OUTPUT "Not enough seats left in this section" ENDIF center : back : ENDCASE If the number of seats requested exceeds those available, the ELSE statement is triggered and the program prints a message stating that there are not enough seats left in the section.
Graphic The relevant code is ELSE OUTPUT "Not enough seats left in this section"
Code GET no_of_seats GET theater_section CASE theater_section IS front : IF no_of_seats <= (50 - front_allocated) THEN ticket_price = no_of_seats * 30 PRINT ticket front_allocated = front_allocated + no_of_seats ELSE OUTPUT "Not enough seats left in this section" ENDIF center : back : ENDCASE
992
You can adjust the code for the front theater section to reuse it for the center and back sections. You simply replace the number of seats and the ticket price per section in each case.
Code GET no_of_seats GET theater_section CASE theater_section IS front : IF no_of_seats <= (50 - front_allocated) THEN ticket_price = no_of_seats * 30 PRINT ticket front_allocated = front_allocated + no_of_seats ELSE OUTPUT "Not enough seats left in this section" ENDIF center : IF no_of_seats <= (100 - front_allocated) THEN ticket_price = no_of_seats * 20 PRINT ticket front_allocated = front_allocated + no_of_seats ELSE OUTPUT "Not enough seats left in this section" ENDIF back : IF no_of_seats <= (50 - front_allocated) THEN ticket_price = no_of_seats * 10 PRINT ticket front_allocated = front_allocated + no_of_seats ELSE OUTPUT "Not enough seats left in this section" ENDIF ENDCASE You can now write the algorithm pseudocode in a programming language – C in this case. You can convert the pseudocode to a programming language one section at a time.
Code no_of_seats = scanf ("%d",&no_of_seats); theater_section = scanf ("%c",&theater_section); switch (theater_section){ case 'F' : if (no_of_seats <= (50 - front_allocated)) {ticket_price = no_of_seats * 30; printf("Front seats cost $%d", ticket_price, "\n"); front_allocated = front_allocated - no_of_seats;} else printf("Not enough seats left.\n");
993
break; case 'C' : if (no_of_seats <= (100 - center_allocated)) {ticket_price = no_of_seats * 20; printf("Center seats cost $%d", ticket_price, "\n"); center_allocated = center_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break; case 'B' : if (no_of_seats <= (50 - back_allocated)) {ticket_price = no_of_seats * 10; printf("Back seats cost $%d", ticket_price, "\n"); back_allocated = back_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break;} GET no_of_seats GET theater_section To input the number of seats and the theater section requested by the user, you use the scanf statement, which reads information from an input device like a keyboard. Because the number of seats is an integer, you use the %d option in the scanf statement. This accepts an integer as input and then writes this to the variable no_of_seats. The value of the variable theater_section will be a character, so you use the %c option to read it. Code no_of_seats = scanf ("%d",&no_of_seats); theater_section = scanf ("%c",&theater_section); switch (theater_section){ case 'F' : if (no_of_seats <= (50 - front_allocated)) {ticket_price = no_of_seats * 30; printf("Front seats cost $%d", ticket_price, "\n"); front_allocated = front_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break; case 'C' : if (no_of_seats <= (100 - center_allocated)) {ticket_price = no_of_seats * 20; printf("Center seats cost $%d", ticket_price, "\n"); center_allocated = center_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break; case 'B' : if (no_of_seats <= (50 - back_allocated)) {ticket_price = no_of_seats * 10;
994
printf("Back seats cost $%d", ticket_price, "\n"); back_allocated = back_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break;} CASE theater_section IS front: The switch statement is used to perform conditional logic with case statements in C. After the case statement, the theater_section variable follows in parentheses to indicate that the value of this variable determines the code that executes next. The theater_section variable can equal one of the three values – F, C, or B. Code no_of_seats = scanf ("%d",&no_of_seats); theater_section = scanf ("%c",&theater_section); switch (theater_section){ case 'F' : if (no_of_seats <= (50 - front_allocated)) {ticket_price = no_of_seats * 30; printf("Front seats cost $%d", ticket_price, "\n"); front_allocated = front_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break; case 'C' : if (no_of_seats <= (100 - center_allocated)) {ticket_price = no_of_seats * 20; printf("Center seats cost $%d", ticket_price, "\n"); center_allocated = center_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break; case 'B' : if (no_of_seats <= (50 - back_allocated)) {ticket_price = no_of_seats * 10; printf("Back seats cost $%d", ticket_price, "\n"); back_allocated = back_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break;} IF no_of_seats <= (50-front_allocated) THEN Before processing the ticket request, the program checks that there are enough seats left in the selected section. If the condition is true it enters the if code block. Code no_of_seats = scanf ("%d",&no_of_seats);
995
theater_section = scanf ("%c",&theater_section); switch (theater_section){ case 'F' : if (no_of_seats <= (50 - front_allocated)) {ticket_price = no_of_seats * 30; printf("Front seats cost $%d", ticket_price, "\n"); front_allocated = front_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break; case 'C' : if (no_of_seats <= (100 - center_allocated)) {ticket_price = no_of_seats * 20; printf("Center seats cost $%d", ticket_price, "\n"); center_allocated = center_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break; case 'B' : if (no_of_seats <= (50 - back_allocated)) {ticket_price = no_of_seats * 10; printf("Back seats cost $%d", ticket_price, "\n"); back_allocated = back_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break;} ticket_price = no_of_seats * 30 PRINT ticket front_allocated = front_allocated - no_of_seats Next the program calculates the total price of the tickets and prints a message to the output device to show this total. The code inside the printf statement, /n, is the new line character, which moves the cursor to the next line on the output device. Lastly, it adjusts the number of the seats already allocated in the selected section. Code no_of_seats = scanf ("%d",&no_of_seats); theater_section = scanf ("%c",&theater_section); switch (theater_section){ case 'F' : if (no_of_seats <= (50 - front_allocated)) {ticket_price = no_of_seats * 30; printf("Front seats cost $%d", ticket_price, "\n"); front_allocated = front_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break; case 'C' :
996
if (no_of_seats <= (100 - center_allocated)) {ticket_price = no_of_seats * 20; printf("Center seats cost $%d", ticket_price, "\n"); center_allocated = center_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break; case 'B' : if (no_of_seats <= (50 - back_allocated)) {ticket_price = no_of_seats * 10; printf("Back seats cost $%d", ticket_price, "\n"); back_allocated = back_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break;} ELSE OUTPUT "Not enough seats left in this section" When there are not enough seats left, the if condition is false. The program then prints an error message to the output device. Code no_of_seats = scanf ("%d",&no_of_seats); theater_section = scanf ("%c",&theater_section); switch (theater_section){ case 'F' : if (no_of_seats <= (50 - front_allocated)) {ticket_price = no_of_seats * 30; printf("Front seats cost $%d", ticket_price, "\n"); front_allocated = front_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break; case 'C' : if (no_of_seats <= (100 - center_allocated)) {ticket_price = no_of_seats * 20; printf("Center seats cost $%d", ticket_price, "\n"); center_allocated = center_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break; case 'B' : if (no_of_seats <= (50 - back_allocated)) {ticket_price = no_of_seats * 10; printf("Back seats cost $%d", ticket_price, "\n"); back_allocated = back_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break;} ENDCASE
997
The break statement causes the program to exit the switch statement. If it is omitted, the program will continue to evaluate the remaining case conditions. Code no_of_seats = scanf ("%d",&no_of_seats); theater_section = scanf ("%c",&theater_section); switch (theater_section){ case 'F' : if (no_of_seats <= (50 - front_allocated)) {ticket_price = no_of_seats * 30; printf("Front seats cost $%d", ticket_price, "\n"); front_allocated = front_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break; case 'C' : if (no_of_seats <= (100 - center_allocated)) {ticket_price = no_of_seats * 20; printf("Center seats cost $%d", ticket_price, "\n"); center_allocated = center_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break; case 'B' : if (no_of_seats <= (50 - back_allocated)) {ticket_price = no_of_seats * 10; printf("Back seats cost $%d", ticket_price, "\n"); back_allocated = back_allocated - no_of_seats;} else printf("Not enough seats left.\n"); break;}
Question Set You've now been given an algorithm in pseudocode that keeps track of customers' purchases. Each customer is categorized as belonging to "Bronze", "Silver", or "Gold" categories depending on the value of their purchases. Silver and Gold customers qualify for discounted purchases. The algorithm can be implemented in any programming language, but you decide to use C.
Question 1 of 3 Question To start, you want to read the value of the customer's total purchases, which is an integer value, from the keyboard.
998
Complete the code to do this. Code totalPurchases = INSERT THE MISSING CODE("%d",&totalPurchases); ...
Answer The scanf method reads data from the keyboard. Correct answer(s): 1. scanf
Question 2 of 3 Question Next you want to find out if the customer qualifies as a Bronze, Silver, or Gold customer. These levels are represented by the B, S, and G characters. You read this information from the keyboard using the scanf method. Complete the code that instructs scanf to receive data in the form of characters. Code totalPurchases = scanf ("%d",&totalPurchases); preferredDiscount = scanf (INSERT THE MISSING CODE,&preferredDiscount);
Answer The "%c" parameter indicates to the scanf method that a character is expected from the keyboard. Correct answer(s): 1. "%c"
Question 3 of 3 Question You have written the CASE block for the Bronze customer level. Complete the code to ensure the program doesn't execute the Silver and Gold code after running the Bronze processes.
999
Code totalPurchases = scanf ("%d",&totalPurchases); preferredDiscount = scanf ("%c",&preferredDiscount); switch (preferredDiscount) { case 'B' : if (totalPurchases < 1000) { discount = 0; printf("Sorry, no discount. Spend $1000 or more to receive a discount.\n"); } else { printf("Welcome back, preferred customer!\n"); } INSERT THE MISSING CODE;
Answer You use the break command to exit the switch statement once a case statement has been executed. Correct answer(s): 1. break
Summary You can follow four steps to simplify the process of solving a programming problem. You analyze the problem statement, create a table defining the required inputs, processes, and outputs, use the table to guide you in writing a pseudocode algorithm, and finally convert the pseudocode into a programming language. If program inputs are limited to a number of specific possibilities, you can use branching statements to create the program. You can use CASE statements to decide on the number of actions to take. You can also nest IF and ELSE block statements to further branch the processes, as required.
1000
Completing Selection Statements Learning Objectives
After completing this topic, you should be able to
complete IF statements in a given example
complete CASE statements in a given example
complete a program based on a defining table in a given example Exercise overview In this exercise, you're required to recognize how to use selection statements in programming. This involves the following tasks:
completing IF statements
completing CASE statements, and
using a defining table to complete an algorithm
Completing IF statements Question You are coding registration software for a university. The university is offering $1,000 discounts to the first 100 students to register. Complete the IF statement so that the discount is correctly applied. Code IF student_no INSERT THE MISSING CODE THEN Discount = 1000 Options: 1. <= 100 2. >= 100 3. < 100
Answer Option 1: Correct. The code <=100 will ensure that the first 100 students get the $1,000 discount.
1001
Option 2: Incorrect. The code >=100 would cause the students with the $1,000 discount to overlap with the students getting the $500 discount. Option 3: Incorrect. The code <100 would cause the hundredth student to register to be excluded from the discounts. Correct answer(s): 1. <= 100
Question Another $500 discount is offered to the next 100 students to register. Complete the ELSE IF statement to ensure that the students from 101 to 200 are given the $500 discount. Code IF student_no <= 100 THEN Discount = 1000 ELSE IF student_no > 100 AND student_no INSERT THE MISSING CODE THEN Discount = 500 ELSE Discount = 0 END IF END IF
Answer Correct. The code <= 200 ensures that the students from 101 to 200 are given the $500 discount. Correct answer(s): 1. <= 200
Completing CASE statements Question There are a variety of student discounts, which are classified according to category. The student categories are P for part-time, F for full-time, and X for extra-mural. Which discount does a part-time student receive?
1002
Code CASE student category of : X: discount = 1500 P: discount = 3750 F: discount = 6500 other: discount = 0 ENDCASE Options: 1. $3,750 2. $1,500 3. $6,500
Answer Option 1: Correct. If a student is part-time, they fall into category P. The discount for category P is $3,750. Option 2: Incorrect. The discount for category X is $1,500. This discount is applied to extra-mural students. If a student is part-time, they fall into category P, which has a discount of $3,750. Option 3: Incorrect. The discount for category F is $6,500. This discount is applied to full-time students. If a student is part-time, they fall into category P, which has a discount of $3,750. Correct answer(s): 1. $3,750
Using a defining table You want to write the section of the program that calculates the total course fees and prints a receipt that specifies the discounted price.
Question You have created the defining table and have already added the inputs and outputs. Identify the first process that will be added to the Process column.
1003
A defining table contains course_fee and student_category in the Input column, and total_ price and receipt in the output column. The processes column is blank. Options: 1. SELECT category_discount 2. PRINT receipt 3. CALCULATE total_price 4. GET course_fee, student_category
Answer Option 1: Incorrect. SELECT category_discount will be performed after retrieving the course_fee and student_category values. Option 2: Incorrect. PRINT receipt will be the final process in the table. Option 3: Incorrect. CALCULATE total_price will be performed after the course_fee, student_category, and category_discount values are created. Option 4: Correct. GET course_fee, student_category will be the first process in the defining table to retrieve data inputs from the user. Correct answer(s): 4. GET course_fee, student_category
Question Identify the first process that will use input to produce the desired outputs. GET course_fee, student_category has been added to the first row in the Process column. Options: 1. CALCULATE total_price 2. PRINT receipt 3. SELECT category_discount
Answer
1004
Option 1: Correct. CALCULATE total_price will use the two user inputs with the category_discount value to calculate the total price. Option 2: Incorrect. PRINT receipt is the final process in the defining table and will print all necessary information to the output device. Option 3: Incorrect. SELECT category_discount is the second process in the defining table and forms part of the calculation that outputs total_price. Correct answer(s): 1. CALCULATE total_price
Question The student categories are P for part-time ($3,500), F for full-time ($5,000), and X for extra mural ($1,250), which form part of a CASE statement. Match each category with the algorithm used to calculate the total price. Options: A. B.
P:
C.
F:
D.
Other:
X:
Targets: 1. total_price = course_fee - 1250 2. total_price = course_fee - 0 3. total_price = course_fee - 5000 4. total_price = course_fee - 3500
Answer Extra-mural students get a discount of $1,250. Students who don't fall into these categories get no discount on their course fees. Full-time students get a discount of $5,000. Part-time students get a discount of $3,500.
1005
Correct answer(s): Target 1 = Option A Target 2 = Option D Target 3 = Option C Target 4 = Option B IF and CASE statements have been completed, and a defining table has been used to complete an algorithm.
Code GET discount CASE student category OF X:
total_price = course_fee – 1250 PRINT receipt P: total_price = course_fee – 3500 PRINT receipt F: total_price = course_fee – 5000 PRINT receipt other: total_price = course_fee – 0 PRINT receipt ENDCASE
1006
FOR Loops Learning Objectives
After completing this topic, you should be able to
sequence the operations in a FOR loop
recognize how to use the FOR loop in computer programs 1. Introducing FOR loops You may need to execute either single or compound statements a number of times in a program. If you want to create a piece of code to print five address labels, you could write a print statement and repeat it five times, for example.
Code GET name_and_address PRINT name_and_address PRINT name_and_address PRINT name_and_address PRINT name_and_address PRINT name_and_address This is a rather inefficient method, especially if you are printing a large number of labels. The amount of duplicated code is time-consuming to write, and difficult for other programmers to read. Also, overly large programs use up memory and processing resources. The leaner a program is, the better its performance.
Code GET name_and_address PRINT name_and_address PRINT name_and_address PRINT name_and_address PRINT name_and_address PRINT name_and_address To avoid creating unwieldy code, you can use a programming procedure called a loop to avoid using the same statement repeatedly.
Graphic
1007
In this diagram, the program is told to print a statement 5 times. At the beginning of the FOR loop, the variable count equals 0. Each time a statement is printed the program adds 1 to count and checks to see if count is greater than 4 (i.e., has looped 5 times). If it hasn’t then the program loops again, printing another statement. Once 5 iterations have been processed, count will equal 5 and the program will end the loop. A FOR loop lets you run a task a predetermined number of times. It removes the need to repeat code, making the code shorter. Conditions in a program can be used to determine a variable for the number of times the task has to be executed. A FOR loop can contain only one command or encompass an entire program that needs to be run several times before terminating. Each time the code in a FOR loop runs, the cycle is known as an iteration. A FOR loop performs specific steps in sequence: the counter is set to an initial value The counter value is set before code in the FOR loop is executed. You set the increment or decrement value, which is usually one. if the counter value hasn't reached its limit, the instructions included in the loop are executed The loop will continue to repeat as long as the counter value remains inside the range set by the loop limit. the counter is incremented or decremented, and Because the counter is used to control the number of times the loop is executed, it's incremented or decremented after the instructions included in the loop are executed. the loop is terminated when the counter reaches its limit The loop stops executing as soon as the counter exceeds the limit. You can write a program so that when it executes, it asks the user to set the number of times a FOR loop must run. The user can be prompted to specify a number as the limit of the counter value – for example, to set how many copies of an invoice to print.
Code INPUT "How many copies of the Invoice do you need printed? "; number$ FOR count = 1 to number$ 'the code to print the invoice details NEXT count
1008
Question Identify the order of the steps a program takes when it executes a FOR loop. Options: A.
Initialize the counter in the loop to an initial value
B.
If the counter hasn't reached its limit, execute the instructions included in the FOR loop
C.
Increment or decrement the counter
D.
Terminate the loop when the counter reaches its limit
Answer Correct answer(s): Initialize the counter in the loop to an initial value is ranked the first step. Before the code in a FOR loop is executed, the counter in the loop is initialized, with the increment or decrement value usually set to one. If the counter hasn't reached its limit, execute the instructions included in the FOR loop is ranked the second step. The loop will continue to repeat as long as the counter remains inside the range set by the counter limit. Increment or decrement the counter is ranked the third step. Because the counter is used to control the number of times the loop is executed, it's incremented or decremented after the instructions included in the loop are executed. Terminate the loop when the counter reaches its limit is ranked the fourth step. Once the counter exceeds the specified value, the loop will stop running.
2. Using FOR loops In a FOR loop to print a specific number of address labels, the first line of code receives the required input details. Then the address details are specified, and finally the labels are printed.
Code Name$ = "Joe Bloggs" Address$ = "12 Basic Language Avenue" FOR count = 1 to 5 PRINT "Name: "; Name$; " Address: "; Address$ NEXT count
1009
You don't have to repeat the code for each statement because the single FOR loop can be set to make the program print five labels.
Code Name$ = "Joe Bloggs" Address$ = "12 Basic Language Avenue" FOR count = 1 to 5 PRINT "Name: "; Name$; " Address: "; Address$ NEXT count The loop is created by using a counter variable called count, with a starting value of one. The number of iterations is set to five. The count is incremented by one every time the loop is executed.
Code Name$ = "Joe Bloggs" Address$ = "12 Basic Language Avenue" FOR count = 1 to 5 PRINT "Name: "; Name$; " Address: "; Address$ NEXT count The counter is used to terminate the loop once the specified number has been reached. So once the count exceeds five, the loop will terminate.
Code Name$ = "Joe Bloggs" Address$ = "12 Basic Language Avenue" FOR count = 1 to 5 PRINT "Name: "; Name$; " Address: "; Address$ NEXT count You want to write a program to calculate the total mass of the cargo in a shipping container, which varies according to the number of parcels in the container. You first need to retrieve the input details. So you list the number of packages and the package mass in each container as input elements in a defining table.
Graphic A table contains Input, Process, and Output columns. The Input column contains no_of_packages and package_mass.
1010
Processes that must run to generate a result include getting the number of packages in each container, calculating the individual mass of the packages, and calculating the sum of their mass.
Graphic The Process column contains GET no_of_packages, CALCULATE package_mass, and CALCULATE total_package_mass. The total package mass is the output value.
Graphic The Output column contains total_package_mass. You begin this pseudocode algorithm with a request for the number of packages in the container.
Code PRINT 'How many packages are in the container?' GET no_of_packages You can use a FOR loop to get the mass of each package and add it to the mass total.
Code FOR i = 1 to no_of_packages GET package_mass total_package_mass = total_package_mass + package_mass ENDFOR The number entered by the user determines how many times the loop will execute.
Code GET no_of_packages FOR i = 1 to no_of_packages GET package_mass total_package_mass = total_package_mass + package_mass ENDFOR PRINT total_package_mass In most languages, the default loop control variable increment step is 1.
1011
You can change this by adding the STEP statement and specifying the step size as any number.
Code FOR count = 1 TO 10 STEP 2 PRINT count NEXT count When executed, the result displays every second number from one to nine.
Graphic The output in the example is 1 3 5 7 9. You can also decrement the control variable by replacing to with downto.
Code FOR count = 10 DOWNTO 1 PRINT count NEXT count When executed, the code produces the numbers ten down to one.
Graphic The output is 10 9 8 7 6 5 4 3 2 1.
Question You're creating a FOR loop to print labels containing clients' contact details. The variable numberOfClients will be used to determine how many labels to print. Identify the pseudocode that will enable the loop to run for the required number of iterations. Code GET numberOfClients FOR printClientInfo = INSERT THE MISSING CODE GET clientName GET clientPhoneNumber GET clientAddress PRINT clientName PRINT clientPhoneNumber
1012
PRINT clientAddress ENDFOR Options: 1. 1 to numberOfClients 2. GET printClientInfo 3. NEW printClientInfo
Answer Option 1: Correct. You use 1 to numberOfClients to begin the loop and specify the number of times that the FOR loop will execute. Option 2: Incorrect. The correct way to begin a loop is to provide the loop count variable range. Option 3: Incorrect. The correct way to begin a loop is to provide the loop count variable range. Correct answer(s): 1. 1 to numberOfClients
3. Nesting FOR loops A loop can run within another loop. Loops that appear inside other loops are known as nested loops.
Graphic The diagram has a Nested loop contained in an Outer loop. The Outer loop code is: FOR X = 1 TO 3 PRINT "Outer loop run #"; X and NEXT X. The Nested loop code is FOR Y = 1 TO 5 PRINT " Nested loop run #"; Y and NEXT Y. Every time the outside loop runs through an iteration, the inside loop is processed, running all its iterations. For each iteration of the outside loop, the inner loop goes through all its iterations. So nested loops process more iterations than outer loops. It can be very difficult to follow the code for a program if you include a large number of nested loops within one loop. So as a general rule, nest only one loop inside another. This pseudocode example is designed to generate reports for three students, each with five different test grades that are stored in the grades array. The program gets a student's name once and then processes that student's five grades.
1013
Code FOR X = 1 to 3 GET studentName from the array PRINT "Student " studentName " grades" FOR Y = 1 to 5 GET gradeAmount from the array PRINT "Grade #" Y " for student " studentName " is " gradeAmount NEXT Y NEXT X As defined by the pseudocode, each time the outer loop is run, the inner loop runs five times. Ultimately, the nested loop will run 15 times, whereas the outer loop will run only three times – once per student.
Code FOR X = 1 to 3 GET studentName from the array PRINT "Student " studentName " grades" FOR Y = 1 to 5 GET gradeAmount from the array PRINT "Grade #" Y " for student " studentName " is " gradeAmount NEXT Y NEXT X The final output includes students' names and their grades.
Code Student John Grade #1 for Grade #2 for Grade #3 for Grade #4 for Grade #5 for
Sands grades student John student John student John student John student John
Student Amy Smith grades Grade #1 for student Amy Grade #2 for student Amy Grade #3 for student Amy Grade #4 for student Amy Grade #5 for student Amy
Sands Sands Sands Sands Sands
Smith Smith Smith Smith Smith
is is is is is
is is is is is
86 62 90 75 78
91 88 91 82 78
Student Elaine Evans grades
1014
Grade Grade Grade Grade Grade
#1 #2 #3 #4 #5
for for for for for
student student student student student
Elaine Elaine Elaine Elaine Elaine
Evans Evans Evans Evans Evans
is is is is is
77 79 83 70 84
Summary You can use FOR loops to execute statements a set number of times, for a predetermined number of cycles. Each time a FOR loop runs, the commands it contains execute and a counter is incremented or decremented by a set value – usually one, although you can change this. Once the value of the counter reaches a specified limit, the loop terminates. Loops that appear inside other loops are called nested or inner loops. Each time an outer loop runs, the inner loop iterates a specified number of times.
1015
WHILE Loops Learning Objective
After completing this topic, you should be able to
recognize how to use the WHILE loop in computer programs 1. Using WHILE loops When you write a computer program, it may be necessary to test a single condition multiple times. However, it may not always be feasible to add lines of code for every instance because you may not know in advance how many times the condition will be tested. For example, you may want to process numbers from a list of unspecified length. Because you don't know how many numbers there are to be processed, you don't know how many times the loop should be executed. You can use a WHILE loop to resolve this problem. The WHILE statement is an entry-condition or loop pre-test. This means that a program won't execute the statement block within the loop unless the specified condition is met. In this pseudocode example, the condition is that the number entered in the algorithm must be less than 3.
Code NUM = 2 WHILE NUM < 3 PRINT NUM NUM = NUM + 1 ENDWHILE If the condition is immediately false, as it is in this example, the loop won't execute at all.
Code NUM = 7 WHILE NUM < 3 PRINT NUM NUM = NUM + 1 ENDWHILE A WHILE loop runs indefinitely unless the loop condition becomes false. In this case, the value of NUM will never change – so the WHILE loop will never stop iterating.
1016
Code NUM = 1 WHILE NUM < 3 PRINT NUM ENDWHILE PRINT "The final number is", NUM To ensure that this doesn't happen, a WHILE loop should include a statement that changes the value of the conditional expression. In this example, the value of NUM is incremented by 1, so at some point in the loop's execution, it should fail the tested condition.
Graphic The relevant code is: NUM = NUM + 1
Code NUM = 1 WHILE NUM < 3 PRINT NUM NUM = NUM + 1 ENDWHILE PRINT "The final number is", NUM To determine whether the loop should be executed again, the loop condition is queried after each iteration. When the loop condition becomes false, the loop terminates and the program moves on to the statements following the loop. In this example, the value of NUM will be printed until its value is greater than 2. After processing two iterations, NUM will equal 3 and the WHILE loop will terminate.
Graphic The relevant code is: PRINT "The final number is", NUM
Code NUM = 1 WHILE NUM < 3
1017
PRINT NUM NUM = NUM + 1 ENDWHILE PRINT "The final number is", NUM To write an algorithm that uses a WHILE loop to print several labels, you first complete a defining table for the problem statement.
Graphic The table has three columns: INPUTS, PROCESSES, and OUTPUTS. In the INPUTS column there is one row with the value answer. In the PROCESSES column, there are four rows: PRINT name and address, PRINT " Do you wish to print another label?", GET answer, and PRINT "Thank you". In the OUTPUTS column, there are two rows: name and address, and End message. You then create this pseudocode algorithm to capture the user's details, print a label, and ask whether another label is required.
Code answer = "yes" WHILE answer = "yes" PRINT name and address PRINT "Do you wish to print another label?" GET answer ENDWHILE PRINT "Thank you" The loop condition is answer = "yes". As long as this condition is true, the loop will continue to execute.
Code answer = "yes" WHILE answer = "yes" PRINT name and address PRINT "Do you wish to print another label?" GET answer ENDWHILE PRINT "Thank you"
1018
Because the variable answer is set to yes as the loop begins its execution, the loop will execute at least once.
Graphic The relevant code is answer = "yes" WHILE answer = "yes"
Code answer = "yes" WHILE answer = "yes" PRINT name and address PRINT "Do you wish to print another label?" GET answer ENDWHILE PRINT "Thank you" After the first label has been printed, the user will have the option to end the process by entering a response other than yes, when prompted about printing more labels.
Graphic The relevant code is PRINT "Do you wish to print another label?" GET answer
Code answer = "yes" WHILE answer = "yes" PRINT name and address PRINT "Do you wish to print another label?" GET answer ENDWHILE PRINT "Thank you" The user response is then evaluated against the loop condition. If the answer is yes, the loop will iterate again.
1019
Because the answer is no in this case, the loop won't execute again. Instead the next line of the program will execute.
Graphic The relevant pieces of code are WHILE answer = "yes" and PRINT "Thank you"
Code answer = "yes" WHILE answer = "yes" PRINT name and address PRINT "Do you wish to print another label?" GET answer ENDWHILE PRINT "Thank you"
Question In this pseudocode example, how many times will this WHILE loop execute? Code num = 7 WHILE num < 3 num=num+1 PRINT num ENDWHILE PRINT num Options: 1. Never 2. After a single iteration 3. After seven iterations 4. After three iterations
Answer Option 1: Correct. The condition is immediately false so the loop won't execute at all. Because the WHILE loop is an entry condition loop, a condition must be met or the loop won't execute.
1020
Option 2: Incorrect. The loop won't execute at all as the condition will be immediately false. Option 3: Incorrect. The loop won't execute at all because the initial tested condition will evaluate to false. Option 4: Incorrect. The loop will never be executed because the initial tested condition is false. Correct answer(s): 1. Never Depending on the programming language you're using, the syntax of the WHILE loop may be slightly different. In this example, BASIC has been used to create a program to print labels. The loop ensures that labels will continue to print until the user enters 'N' – or anything other than 'Y'.
Graphic The relevant code is: WHILE answer$ = 'Y'
Code answer$ = "Y" WHILE answer$ = "Y" PRINT name$ PRINT address$ PRINT "Do you want to print another? Y/N" INPUT answer$ WEND In this example, the program to print labels is written in Pascal. Unlike in the BASIC example, the WHILE statement includes a condition followed by the keyword DO. Also, the statements that make up the loop are placed between BEGIN and END tags.
Code while answer = "Y" do begin writeln (name); writeln (address); writeln ("Do you want to print another ? Y/N");
1021
read (answer) end; This is the same program written in C. In the tested condition, the relational operator "==" means equal to.
Graphic The relevant code is: (answer == 'Y')
Code while (answer == 'Y') { printf ("%s\n" , name); printf ("%s\n" , address); printf ('Do you want to print another? Y/N'); scanf ("%s\n" , answer); } The statement is followed by the looped print and scanf statements, which are placed between opening and closing curly braces.
Code while (answer == 'Y') { printf ("%s\n" , name); printf ("%s\n" , address); printf ('Do you want to print another? Y/N'); scanf ("%s\n" , answer); } You can nest WHILE loops in the same way that you nest FOR loops.
Graphic The algorithm starts and tests choice 1. If it is false then the loop ends. If it is true, then a second loop condition (choice 2) is tested. If choice 2 is false he loop ends. If it is true, the code will execute and the condition will be tested again. When the second loop condition is false, it will test choice 1 again.
1022
However, it's generally best to avoid doing this because it increases the risk that you'll include a WHILE loop that will continue executing indefinitely and so cause a program to hang or crash. It also isn't a good idea to nest too many loops because this can make the structure of a program very complex. You can also nest WHILE loops inside FOR loops, or nest FOR loops inside of WHILE loops. This is an example of a BASIC program that uses a WHILE loop nested inside a FOR loop. It's a counting program designed to output five grades for each of three students in a database.
Code FOR X = 1 to 3 'write code to get the studentName from the array PRINT "Student "; studentName " grades" Y = 1 WHILE Y <= 5 'write code to get the gradeAmount from the array PRINT "Grade #"; Y " for student " studentName " is " gradeAmount Y = Y + 1 WEND NEXT X In this program, the FOR loop specifies that the data will be retrieved for three students.
Graphic The relevant pieces of code are FOR X = 1 to 3 and NEXT X
Code FOR X = 1 to 3 'write code to get the studentName from the array PRINT "Student "; studentName " grades" Y = 1 WHILE Y <= 5 'write code to get the gradeAmount from the array PRINT "Grade #"; Y " for student " studentName " is " gradeAmount
1023
Y = Y + 1 WEND NEXT X When the program begins its execution, the first student's name is retrieved from the array. The name will also appear on screen.
Graphic The relevant code is: 'write code to get the studentName from the array PRINT "Student " studentName " grades"
Code FOR X = 1 to 3 'write code to get the studentName from the array PRINT "Student "; studentName " grades" Y = 1 WHILE Y <= 5 'write code to get the gradeAmount from the array PRINT "Grade #"; Y " for student " studentName " is " gradeAmount Y = Y + 1 WEND NEXT X Because the WHILE loop doesn't count in the same way as a FOR loop, the variable Y has to be set to 1 before the WHILE loop starts its execution for each increment of the FOR loop. The value of Y is also manually incremented inside of the WHILE loop.
Graphic The relevant pieces of code are: Y=1 and Y=Y+1
Code FOR X = 1 to 3 'write code to get the studentName from the array
1024
PRINT "Student "; studentName " grades" Y = 1 WHILE Y <= 5 'write code to get the gradeAmount from the array PRINT "Grade #"; Y " for student " studentName " is " gradeAmount Y = Y + 1 WEND NEXT X The WHILE loop will read and store values for the student grades until the value of Y equals 6. Even though only five grades are being entered, the value of Y has to be 6 before the loop can break.
Graphic The relevant code is: WHILE Y <= 5 'write code to get the gradeAmount from the array PRINT "Grade #"; Y " for student " studentName " is " gradeAmount Y=Y+1
Code FOR X = 1 to 3 'write code to get the studentName from the array PRINT "Student "; studentName " grades" Y = 1 WHILE Y <= 5 'write code to get the gradeAmount from the array PRINT "Grade #"; Y " for student " studentName " is " gradeAmount Y = Y + 1 WEND NEXT X When this happens the WHILE loop will break and return control to the loop, executing the FOR loop again until the value of X equals 3 or end the program as soon as X is equal to 3.
Graphic The relevant code is:
1025
FOR X = 1 to 3 Here is the code again
Code FOR X = 1 to 3 'write code to get the studentName from the array PRINT "Student "; studentName " grades" Y = 1 WHILE Y <= 5 'write code to get the gradeAmount from the array PRINT "Grade #"; Y " for student " studentName " is " gradeAmount Y = Y + 1 WEND NEXT X When the program runs, this is an example of the expected output. There are three students listed, with five grades listed for each student.
Code FOR X = 1 to 3 'write code to get the studentName from the array PRINT "Student "; studentName " grades" Y = 1 WHILE Y <= 5 'write code to get the gradeAmount from the array PRINT "Grade #"; Y " for student " studentName " is " gradeAmount Y = Y + 1 WEND NEXT X
Question When will this WHILE loop stop executing? Code answer$='Y' WHILE answer$ ='Y' PRINT name$ PRINT address$ PRINT "Would you like to print another ticket? Y/N"
1026
INPUT answer$ WEND Options: 1. When a user enters the value N 2. When a user enters the value Y 3. After it has completed a specified number of iterations 4. It will never stop 5. It will never execute 6. Having any input except Y for answer
Answer Option 1: Correct. Once the input stored in the answer variable is N, the loop condition will be false and the loop will terminate. The next instruction after the loop will be processed. Option 2: Incorrect. If the input for answer is Y, the WHILE loop will continue executing because the loop condition will still be true. Option 3: Incorrect. There is no value specified for the number of iterations of the loop. It will continue executing until its tested condition evaluates as false. Option 4: Incorrect. The loop isn't infinite because it has a condition that can be evaluated to false. Option 5: Incorrect. The loop has an initial tested condition that evaluates to true. This ensures that the loop will execute at least once. Option 6: Correct. The loop will terminate if the value input is any value other than Y. N is used as the preferred value to indicate the response is No. Correct answer(s): 1. When a user enters the value N 6. Having any input except Y for answer
Summary In a program, you may need to test a condition a number of times that will be specified only when the program runs. You can use a WHILE loop to do this. The WHILE loop will iterate as long as its test condition evaluates to true. Once the condition is false, the loop terminates. WHILE loop syntax is similar in Pascal, BASIC, and C.
1027
Solving a Repetition Problem Learning Objectives
After completing this topic, you should be able to
recognize where to use the WHILE loop
analyze the use of a WHILE loop in PASCAL code in given examples 1. When to use WHILE loops You can use a WHILE loop to repeat a process as many times as necessary, without having to write long, time-consuming code. For example, you might be collecting cash donations for a charity and want to print a receipt every time a donation is received. You may also need to calculate the number of donations, the average donation, and the total donations. You can use a WHILE loop to repeat required processes for each donation you receive. There are four steps you need to follow to create your program: 1.
analyze the problem statement
2. create a defining table 3. create an algorithm in pseudocode, and 4. convert the pseudocode into an appropriate programming language Once you've analyzed the problem statement, you can break it down into a defining table that identifies the relevant inputs, processes, and outputs.
Graphic The table has three columns: INPUTS, PROCESSES, and OUTPUTS. In the INPUTS column there is one row with the value donation_amount. In the PROCESSES column, there are four rows: GET donation_amount, CALCULATE no_of_donations, CALCULATE total_donations, and CALCULATE average_donations. In the OUTPUTS column, there are four rows: receipt, no_of_donations, total_donations, and average_donations. Inputs and outputs in the problem statement are usually indicated by nouns, while process tasks are usually indicated by verbs.
1028
Graphic There is a table with three columns labeled Input, Process, and Output. Input The amount of the donation received goes in the Input column. This is the basic data that will be processed to get results, or output. The Input column contains donation_amount Process The Process column contains the calculations that need to be done in order to get an output result. These include the calculations for the total donations and the number of donations, as well as the statement to get the source donation amounts. The Process column contains GET donation_amount, CALCULATE average_donation, CALCULATE total_donations, and CALCULATE no_of_donations. Output The Output column contains the outputs from the calculations in the Process column, which include the results for the total number of donations and the average donation. It also contains the statement to issue a receipt after the amount of the donation is processed. The Output column contains statements for receipt, no_of_donations, total_donation, and average donation. You can use the defining table as the basis for writing a pseudocode algorithm, which can then be coded. You're first prompted by the algorithm to enter the amount for the first donation. It then prints a receipt for that amount.
Code PRINT Enter the donation GET donation_amount PRINT receipt The number of donations counter is initialized to one, and the total donations amount is set to equal the value of the first donation.
Graphic The relevant code is no_of_donations=1
1029
Code PRINT Enter the donation GET donation_amount PRINT receipt no_of_donations=1 total_donations=donation_amount The algorithm then asks if there are further donations to be entered. If the answer is YES, the first iteration of the WHILE loop is processed.
Graphic The relevant code is WHILE other_donations=YES
Code PRINT Enter the donation GET donation_amount PRINT receipt no_of_donations=1 total_donations=donation_amount GET other_donations WHILE other_donations=YES The compound statement for the WHILE loop performs four steps:
Code PRINT Enter the donation GET donation_amount PRINT receipt no_of_donations=1 total_donations=donation_amount GET other_donations WHILE other_donations=YES GET donation_amount PRINT receipt total_donations=total_donations+donation_amount no_of_donations=no_of_donations+1 PRINT 'Are there any more donations to accept?'
1030
GET other donations ENDWHILE
it gets the amount for each donation The relevant code is GET donation_amount. Code PRINT Enter the donation GET donation_amount PRINT receipt no_of_donations=1 total_donations=donation_amount GET other_donations WHILE other_donations=YES GET donation_amount PRINT receipt total_donations=total_donations+donation_amount no_of_donations=no_of_donations+1 PRINT 'Are there any more donations to accept?' GET other donations ENDWHILE
it prints a receipt The relevant code is PRINT receipt Code PRINT Enter the donation GET donation_amount PRINT receipt no_of_donations=1 total_donations=donation_amount GET other_donations WHILE other_donations=YES GET donation_amount PRINT receipt total_donations=total_donations+donation_amount no_of_donations=no_of_donations+1 PRINT 'Are there any more donations to accept?' GET other donations ENDWHILE
1031
it adds each donation received to the donations total, and The relevant code is total_donations=total_donations+donation_amount Code PRINT Enter the donation GET donation_amount PRINT receipt no_of_donations=1 total_donations=donation_amount GET other_donations WHILE other_donations=YES GET donation_amount PRINT receipt total_donations=total_donations+donation_amount no_of_donations=no_of_donations+1 PRINT 'Are there any more donations to accept?' GET other donations ENDWHILE
it increases the total number of donations by one The relevant code is no_of_donations=no_of_donations+1 Code PRINT Enter the donation GET donation_amount PRINT receipt no_of_donations=1 total_donations=donation_amount GET other_donations WHILE other_donations=YES GET donation_amount PRINT receipt total_donations=total_donations+donation_amount no_of_donations=no_of_donations+1 PRINT 'Are there any more donations to accept?' GET other donations ENDWHILE
The WHILE loop then asks if there are any more donations to accept. If the answer is YES, it continues to execute. The WHILE loop terminates if the user types anything other than YES.
1032
Graphic The relevant code is PRINT 'Are there any more donations to accept?'
Code PRINT Enter the donation GET donation_amount PRINT receipt no_of_donations=1 total_donations=donation_amount GET other_donations WHILE other_donations=YES GET donation_amount PRINT receipt total_donations=total_donations+donation_amount no_of_donations=no_of_donations+1 PRINT 'Are there any more donations to accept?' GET other donations ENDWHILE When the WHILE loop terminates, the total donations are divided by the number of donations to calculate the average donation.
Graphic The relevant code is average_donation=total_donation/no_of_donations
Code PRINT Enter the donation GET donation_amount PRINT receipt no_of_donations=1 total_donations=donation_amount GET other_donations WHILE other_donations=YES GET donation_amount PRINT receipt total_donations=total_donations+donation_amount no_of_donations=no_of_donations+1
1033
PRINT 'Are there any more donations to accept?' GET other donations ENDWHILE average_donation=total_donation/no_of_donations PRINT no_of_donations PRINT 'the total amount donated is' PRINT total_donation PRINT 'the average amount donated is' PRINT average donation The algorithm then displays the number of donations, the average donation, and the total amount donated.
Graphic The relevant code is PRINT no_of_donations PRINT 'the total amount donated is' PRINT total_donation PRINT 'the average amount donated is' PRINT average donation
Code PRINT Enter the donation GET donation_amount PRINT receipt no_of_donations=1 total_donations=donation_amount GET other_donations WHILE other_donations=YES GET donation_amount PRINT receipt total_donations=total_donations+donation_amount no_of_donations=no_of_donations+1 PRINT 'Are there any more donations to accept?' GET other donations ENDWHILE average_donation=total_donation/no_of_donations PRINT no_of_donations PRINT 'the total amount donated is' PRINT total_donation PRINT 'the average amount donated is' PRINT average donation
1034
Question You've created an algorithm to count the number of logs placed on a logging truck. Once the truck is full of logs, it can leave and an empty truck can take its place. Which type of loop is it most appropriate to use in your program? Options: 1. WHILE 2. FOR 3. IF 4. CASE
Answer Option 1: Correct. A WHILE loop allows processing to continue as long as a tested condition is true, once the condition is false, the loop will end. In this instance as long as the truck can be loaded, the loop will execute. Option 2: Incorrect. When you use a FOR loop, you generally need to know how many times you want the loop to execute. In this instance, the number of logs that can go on a truck is unknown, so a FOR loop is unsuitable. Option 3: Incorrect. IF is a statement, not a loop. It's most often used as a selection statement in programming. Option 4: Incorrect. CASE is a statement, not a loop. It commonly replaces nested IF statements. Correct answer(s): 1. WHILE
Question Sequence the lines in the pseudocode algorithm. Options: A.
GET numLogsOnTruck
B.
WHILE numLogsOnTruck < 50
C.
PUT another log on the truck numLogsOnTruck = numLogsOnTruck + 1
D.
ENDWHILE
1035
E.
DO THIS Send truck on its way Receive an empty truck
Answer Correct answer(s): GET numLogsOnTruck is ranked the first step. You first have to determine the input you need to base your calculations on. This is the first line of the algorithm WHILE numLogsOnTruck < 50 is ranked the second step. You set the initial condition to be executed to begin running the loop. This is the second line of the algorithm PUT another log on the truck numLogsOnTruck = numLogsOnTruck + 1 is ranked the third step. The counter is set to increment the number of logs on the truck once for each iteration. These are the third and fourth lines of the algorithm. ENDWHILE is ranked the fourth step. You close the WHILE loop. This is the fifth line of the algorithm. DO THIS Send truck on its way Receive an empty truck is ranked the fifth step. Once the conditions in the loop are met to indicate the truck is full, it can leave and be replaced by an empty truck. This is the sixth and final line of the algorithm.
2. Using a WHILE loop in Pascal Once you've written the algorithm for collecting donations in pseudocode, you can code the algorithm – for example, in Pascal. The program starts by performing six actions:
Code writeln ('Enter the first donation'); read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := 1; total_donations := donation_amount; writeln ('Are there any more donations to accept? Y/N'); read (other_donations);
1036
prompting the user to enter the first donation The relevant code is writeln ('Enter the first donation'); Code writeln ('Enter the first donation'); read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := 1; total_donations := donation_amount; writeln ('Are there any more donations to accept? Y/N'); read (other_donations);
reading the donation amount The relevant code is read (donation_amount); Code writeln ('Enter the first donation'); read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := 1; total_donations := donation_amount; writeln ('Are there any more donations to accept? Y/N'); read (other_donations);
printing a receipt The relevant code is print ('Thank you for your donation of', donation_amount); Code writeln ('Enter the first donation'); read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := 1; total_donations := donation_amount; writeln ('Are there any more donations to accept? Y/N'); read (other_donations);
initializing the number of donations to one The relevant code is
1037
no_of_donations := 1; Code writeln ('Enter the first donation'); read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := 1; total_donations := donation_amount; writeln ('Are there any more donations to accept? Y/N'); read (other_donations);
assigning the initial donation amount to total donations, and The relevant code is total_donations := donation_amount; Code writeln ('Enter the first donation'); read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := 1; total_donations := donation_amount; writeln ('Are there any more donations to accept? Y/N'); read (other_donations);
asking for and accepting input for more donations The relevant code is writeln ('Are there any more donations to accept? Y/N'); read (other_donations); Code writeln ('Enter the first donation'); read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := 1; total_donations := donation_amount; writeln ('Are there any more donations to accept? Y/N'); read (other_donations);
The entry condition of the WHILE loop is decided by the value of the other_donations variable.
1038
Graphic The relevant code is read (other_donations);
Code writeln ('Enter the first donation'); read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := 1; total_donations := donation_amount; writeln ('Are there any more donations to accept? Y/N'); read (other_donations); Adding do to the while loop requires the loop to run once and check if the conditions are met to return a value of 'Y'.
Code writeln ('Enter the first donation'); read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := 1; total_donations := donation_amount; writeln ('Are there any more donations to accept? Y/N'); read (other_donations); while other_donations = 'Y' do If a 'Y' value is returned, the while loop will run and will continue to execute for as many times as the 'Y' value is returned.
Code writeln ('Enter the first donation'); read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := 1; total_donations := donation_amount; writeln ('Are there any more donations to accept? Y/N'); read (other_donations); while other_donations = 'Y' do
1039
begin and end tags are used to contain the statements within the loop.
Code writeln ('Enter the first donation'); read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := 1; total_donations := donation_amount; writeln ('Are there any more donations to accept? Y/N'); read (other_donations); while other_donations = 'Y' do begin read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := no_of_donations + 1; total_donation := total_donation + donation_amount; writeln ('Are there any more donations to accept? Y/N') ; read (other_donations) end; average_donation := total_donation/no_of_donations; So that the loop doesn't run indefinitely, the entry condition other_donations has a new value read at the end of the loop. The loop terminates when the other_donations variable no longer contains the value 'Y'.
Graphic The relevant code is Y/N
Code writeln ('Enter the first donation'); read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := 1; total_donations := donation_amount; writeln ('Are there any more donations to accept? Y/N'); read (other_donations); while other_donations = 'Y' do begin read (donation_amount); print ('Thank you for your donation of', donation_amount);
1040
no_of_donations := no_of_donations + 1; total_donation := total_donation + donation_amount; writeln ('Are there any more donations to accept? Y/N') ; read (other_donations) end; average_donation := total_donation/no_of_donations; The average donation is calculated once the loop has terminated.
Graphic The relevant code is average_donation := total_donation/no_of_donations;
Code writeln ('Enter the first donation'); read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := 1; total_donations := donation_amount; writeln ('Are there any more donations to accept? Y/N'); read (other_donations); while other_donations = 'Y' do begin read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := no_of_donations + 1; total_donation := total_donation + donation_amount; writeln ('Are there any more donations to accept? Y/N') ; read (other_donations) end; average_donation := total_donation/no_of_donations; Finally the program displays output, including the number of donations, total amount of the donations, and average donation amount.
Graphic The relevant code is writeln ('The number of donations is ', no_of_donations); writeln ('The total amount donate is ', total_donation); writeln ('The average amount donated is ', average_donation);
1041
Code writeln ('Enter the first donation'); read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := 1; total_donations := donation_amount; writeln ('Are there any more donations to accept? Y/N'); read (other_donations); while other_donations = 'Y' do begin read (donation_amount); print ('Thank you for your donation of', donation_amount); no_of_donations := no_of_donations + 1; total_donation := total_donation + donation_amount; writeln ('Are there any more donations to accept? Y/N') ; read (other_donations) end; average_donation := total_donation/no_of_donations; writeln ('The number of donations is ', no_of_donations); writeln ('The total amount donate is ', total_donation); writeln ('The average amount donated is ', average_donation);
Question What is the error in this example of Pascal code? Code program loop; var i, limit : integer; begin writeln ('Please enter a limit.'); readln (limit); while i <= limit begin do write(i, ' '); i := i + 1 end; end Options: 1. The keyword do is in the wrong place 2. The begin and end tags around the while loop's statements are optional 3. The writeln statement should come after the while loop
1042
Answer Option 1: Correct. The keyword do should be on the while line, not the begin line. Option 2: Incorrect. Statements in the while loop require a begin and end tag. Option 3: Incorrect. The while loop comes after the writeln statement as a value needs to be entered before the loop can execute. Correct answer(s): 1. The keyword do is in the wrong place
Summary A while loop is useful for repeating processes a required number of times. The loop can be designed to execute as long as there is information to process. It will stop executing once an entry condition statement returns a false value when queried at the beginning of an iteration. In Pascal, you use begin and end tags to enclose the statements in a while loop.
1043
Using Loops Learning Objectives
After completing this topic, you should be able to
create a defining table to determine inputs, processes, and outputs
structure an algorithm containing a FOR loop
complete a WHILE loop in an algorithm Exercise overview In this exercise, you're required to use loops in a program. This involves the following tasks:
creating a defining table to determine inputs, processes, and outputs
structuring an algorithm containing a FOR loop, and
completing a WHILE loop in an algorithm
Creating defining tables You are starting to create a program that accepts donation amounts as input and then generates output such as total donations and average amount donated. You can use a defining table to assist you in your planning.
Question Match each defining table heading with the element contained in its column. Options: A. B.
Process
C.
Output
Input
Targets: 1. Amount of each donation 2. Calculate the total donations 3. Total donations
Answer
1044
The value amount of each donation should go into the Input column. The calculation to determine the total donations should go into the Process column. The final value for the total donations should go into the Output column. Correct answer(s): Target 1 = Option A Target 2 = Option B Target 3 = Option C
Question Which process task would be carried out first? Options: 1. Get the donation amount 2. Calculate the average donation 3. Calculate the total amount donated 4. Calculate the number of donations
Answer Option 1: Correct. The statement processed first should be the GET pseudocode statement. Option 2: Incorrect. You can only calculate the average donation once you have totaled the donation amounts and determined the number of donations. Option 3: Incorrect. The statement processed first should be the GET statement because it retrieves the data for calculations. You can only calculate the total once you have had all the donation amounts input. Option 4: Incorrect. You can only calculate the number of donations after the donation amounts data has been processed. Correct answer(s): 1. Get the donation amount
1045
Structuring a FOR loop A FOR loop removes the need to repeat code because it allows you to run a task a predetermined number of times.
Code GET value FOR i = 1 TO value Process ENDFOR
Question Identify correct statements about the operations in a FOR loop. Options: 1. The counter is initialized before code in the FOR loop is executed 2. After an iteration, the value of the counter is tested against the loop limit 3. When it's initialized, the amount being incremented or decremented always has a starting value of zero 4. The loop terminates before the counter exceeds a set limit
Answer Option 1: Correct. The counter in the loop is initialized before code in the FOR loop is executed. Option 2: Correct. After each iteration, the counter is compared to the set limit value. The loop will continue to repeat as long as the counter remains within the range set by the loop limit. Option 3: Incorrect. The amount being incremented or decremented has a default starting value of one, which is then incremented or decremented as the loop executes. Option 4: Incorrect. The loop stops executing only when the counter exceeds the range set by the limit. Correct answer(s): 1. The counter is initialized before code in the FOR loop is executed 2. After an iteration, the value of the counter is tested against the loop limit
1046
Using WHILE loops You are writing an algorithm that converts weights from pounds to kilograms. Because you want the algorithm to run as long as there is a valid input for the weight in pounds, you use a WHILE loop.
Code value = ―Y‖ WHILE value = ―Y‖ Process ENDWHILE
Question You have completed most of the code for a pseudocode algorithm. You're not sure how many iterations are required, so you need to include a conditional statement. Which conditional statement should you use in the WHILE loop? Code more_weights="Y" WHILE INSERT THE MISSING CODE GET pounds PRINT pounds kilograms=pounds*0.4536 PRINT 'The weight in kilograms is' PRINT kilograms GET 'more_weights? Y/N' ENDWHILE Options: 1. more_weights = "Y" 2. pounds > 20 3. more_weights = 0
Answer Option 1: Correct. The more_weights variable is assigned an initial value of "Y" before the loop. This ensures that the loop executes at least once.
1047
Option 2: Incorrect. This option requires the input weight to be greater than 20 pounds. However, there shouldn't be any restriction on the weights that can be converted. Option 3: Incorrect. If you use this conditional expression, the loop would never run because the more_weights variable will never be 0. The loop has an initial value of "Y" and with every loop the user enters either "Y" to continue the loop or "N" to terminate it. Correct answer(s): 1. more_weights = "Y"
Question In your algorithm, the code inside the WHILE loop ends with a prompt asking whether there are more weights. What happens if the highlighted statement is omitted? The highlighted statement is GET 'more_weights =?Y/N' Code more_weights="Y" WHILE more weights = "Y" GET weights PRINT weight_in_pounds Kilograms=pounds*0.4536 PRINT 'The weight in kilograms is' PRINT kilograms INPUT 'more_weights Y/N?' more_weights ENDWHILE Options: 1. The loop runs indefinitely 2. The loop ends after one iteration 3. The loop can't not function, failing to start
Answer Option 1: Correct. Without the closing statement – which asks whether there are more weights – the condition variable more_weights will never be updated. Consequently, it will always have a value of "Y" and the loop will continue iterating indefinitely. Option 2: Incorrect. The while condition is evaluated before each iteration. It completes one iteration because the more_weights variable is assigned an initial value of "Y". The loop would
1048
only end after one iteration if the more_weights variable was set to something other than "Y" during the first iteration. Option 3: Incorrect. The more_weights variable is assigned an initial value of "Y" outside the loop. Consequently, the while condition is true when it's initially evaluated and the loop will execute. Correct answer(s): 1. The loop runs indefinitely A defining table has been created, a FOR loop algorithm has been written, and WHILE loops have been used in a program.
Code value = ―Y‖ WHILE value = ―Y‖ Process ENDWHILE
1049
The history of computers Learning objective
After completing this topic, you should be able to discuss the history of computers and describe the different types of computers
1. The evolution of computers Many people attempted to build mechanical computers before electricity was discovered.
500 BC 1625 AD 1642 1822 1935
500 BC The abacus is considered the oldest calculating machine. It was invented in Asia Minor about 5000 BC to allow users to add and subtract large numbers using a system of sliding beads arranged on a rack. 1625 AD The slide rule was developed in England around 1625. This mechanical calculator used physical distances to multiply and subtract numbers. 1642 In 1642, Blaise Pascal invented the first working machine that could add numbers. This brass rectangular box, called a Pascaline, contained eight movable dials that could add figures up to 8digits in length. Unfortunately, the Pascaline was limited to addition. 1822 In 1822, Charles Babbage designed a steam-powered machine that could automatically compute mathematical tables and functions. However, Babbage's Difference engine was never built. 1935 George Boole created Boolean algebra in 1847 with his mathematical analysis of logic. The first working binary machine was built in 1935 and represented the concepts of true and false using only the 1s and 0s in Boolean algebra. The first electric computers were created during the 1920s and 1930s. This heralded the age of electronic computing. The electronic computer has evolved in generations, with a technical or material breakthrough usually acting as a catalyst to start a new generation.
1050
The electronic computer has evolved in generations, with a technical or material breakthrough usually acting as a catalyst to start a new generation. The first generation of electronic computers began in 1945 and lasted until approximately 1956. The Electronic Numeric Integrator and Calculator (ENIAC) was built in 1945. It was created at the University of Pennsylvania's Moore School of Electrical Engineering to compute ballistic charts during World War II. The main problems with first-generation computers were their
size price power consumption unreliability
size First-generation computers were extremely large. The ENIAC weighed 30 tons and had to be housed in a special building. It contained 18,000 vacuum tubes, 70,000 resistors, and 5,000,000 soldered joints. price First-generation computers, such as the ENIAC, were extremely expensive. power consumption First-generation computers used vast amounts of electricity. When it was running, the ENIAC consumed around 200 kilowatts of electrical power per hour and caused brownouts in Philadelphia when it was switched on. unreliability First-generation computers were unreliable. On average, the ENIAC failed every seven and a half minutes. In 1946, John von Neumann pioneered computer programming. The main threads of his theory of programming were that
data and instructions were stored in a read-write memory memory was addressable by location programs were executed sequentially by themselves
The second generation of computers began in 1958 with the development of transistors by AT&T Bell Telephone Laboratories. Transistors were faster, more reliable, and needed less power than the vacuum tubes used in first-generation computers.
1051
Second-generation computers were cheaper than their predecessors. More businesses and universities could afford to have computers. As computers' availability increased, so did their rate of development. With many more people working on computers, the second generation saw the development of the first computer programming languages. The invention of integrated circuits brought the second computer generation to an end in the mid-1960s. Integrated circuits grouped all the essential elements of a computer into one unit. They saved space and eliminated the need to connect components with wires, making these computers more reliable than their predecessors. Computer memory became very compact, so more data could be stored in less space than before. The fourth generation of electronic computers started in 1974. Around this time, the first microcomputers became available on the market. Microcomputers later became known as personal computers or PCs.
Question Computers today are very different to first-generation computers. Which statements are true of computers as they evolve? Options: 1. 2. 3. 4.
They become more robust They become more powerful They become more expensive They become more proprietary
Answer Computers are continually becoming more powerful and more robust. More households can afford them as they become less expensive. In contrast to early computers, which could run only customdesigned software, modern computers are more open and can use hardware and software from many different vendors. Option 1 is correct. As integrated circuits become smaller and more lightweight – thanks to nanotechnology – they become increasingly easy to maintain and replace. This results in more power, reduced overhead, and a greater robustness, due to fewer mechanical failures.
1052
Option 2 is correct. Moore's law states that computer processing power effectively doubles every eighteen months. This is due to increased rate of development and advances in material design and infrastructure. Option 3 is incorrect. On the contrary, computers become smaller, cheaper, and more powerful at the advent of each new generation. As components become streamlined in a factory production environment, manufacturing costs decrease accordingly. This saving is passed on to the end consumer. Option 4 is incorrect. Early computers were proprietary, with companies developing their own hardware and software standards. As hardware components become standardized and the OMG (Object Model Group) promotes open software standards, computer systems become less proprietary. The price of PCs, which are thousands of times more powerful than the ENIAC, is decreasing all the time. Technological advancement, such as the development of integrated circuits and semiconductor memory, is the main reason for the inverted power-to-cost relationship in computers. Computers have now reached their fifth generation. Advances in computer design and technology, such as the development of superconductors, have made this latest step forward possible. The fifth-generation computers will continue to get smaller and will display some artificial intelligence. For example, a computer in the future may be able to make medical diagnoses when given a patient's symptoms.
2. Basic computer features and functions To compute means to process data into information. Information has meaning whereas data does not. For example, the figure 20,000 has no meaning when it resides as raw data inside the computer. But, when a program reads the data and tells you the value in dollars of your overdraft, it becomes information. When the ENIAC was switched off in 1954, it was supposed to have done more arithmetic in nine years than the entire human race had done before 1945. Computers perform tasks – such as calculations, comparisons, and searches – faster and more efficiently than humans. And they do not get fatigued or bored with repetitive tasks – they can repeat the same task in exactly the same manner.
1053
The mathematician Alan Turing devised a test in which a person types questions on a terminal. The person does not know whether the responses to their questions come from a computer or another human being. If a computer is answering, and its answers are indistinguishable from a human's, the computer passes the Turing test. Computers that pass this test can be regarded as exhibiting artificial intelligence or being sentient like humans. No computer has yet managed to pass the Turing test because humans are better than computers at performing unpredictable tasks such as answering questions they haven't previously seen. Computer systems consist of both hardware and software.
Question Hardware refers to the physical components of the system, whereas software refers to the intangible parts of a computer system. See if you can match each of these options to their correct category. Options: 1. 2. 3. 4.
Keyboard Hard drive Operating system Programs
Targets: A. Software B. Hardware
Answer The software components of a computer system are operating systems and programs, while the hardware components of a computer system are the keyboard and hard drive. Without software, hardware is useless. Programs are basically lists of instructions for a computer to carry out. They are detailed and exact because, unlike humans, computers cannot work out anything for themselves. Apart from specially written applications, the most common software packages used today are
1054
word processors spreadsheets database managers
word processors Word-processing programs, such as Microsoft Word, have replaced typewriters in producing textbased documents. They can contain various letter fonts, colors, and graphics, so you can produce professional looking documents very easily with them. spreadsheets Spreadsheets are mostly used to analyze numerical data. They resemble tables that comprise many cells with every cell holding some data or function. Spreadsheets are more suited to numerical data than to text, but you can sort small amounts of textual data in a spreadsheet. database managers You can use database managers to create new database structures and process data already present in databases. Users can view their data in different ways with a database manager. For example, database managers can easily produce two reports of customer information from the same data. One may be sorted according to customers' names, whereas the other is sorted according to customers' addresses. Software packages are becoming more and more integrated, and the boundaries between their functions are becoming blurred. Spreadsheets can be used to perform database functions, and word processors can be used to do calculations. Databases, spreadsheets, and word processors are popular because they are very easy to use, and you do not need programming skills to use them. However, most incorporate a programming language in case more advanced users want to automate some tasks. Often no off-the-shelf program does exactly what a user wants it to do. So many computer programmers are needed to enable software companies to create customdesigned programs for their clients. Computer programmers are also required to produce offthe-shelf applications.
1055
3. Computer types There are five main types of computers:
supercomputers mainframes personal computers servers portables
Supercomputers are typically thousands of times faster than the fastest personal computers. Supercooled liquids run through the circuits of super computers, so the electrical resistance in their circuitry becomes very low, enabling their components to operate at high speeds. Supercomputers operate specialized programs, such as weather prediction, fluid-dynamics modeling, animated graphics, nuclear energy research, and petroleum exploration. The main concern of supercomputers is fast program execution, not the number of programs running concurrently. Supercomputers are unexpectedly small – they are smaller than mainframe computers. The dominant corporation in the supercomputer field is the Cray Research Company. Mainframe computers support many users, who can run many programs simultaneously. Mainframes accept input from terminals, personal computers, and other mainframe computers.
Note A terminal is normally a screen with a keyboard. It does not have any processing power and is sometimes called a dumb terminal. Mainframes are usually housed in special rooms where only cooled and dust-filtered air is allowed to circulate. Banks, governments, large corporations, and universities are the main users of mainframes because they need to give thousands of users simultaneous access to the same information. Personal computers (PCs) are small and inexpensive. They generally have only one processor. They were first known as microcomputers because they were complete computers built on a smaller scale than the huge systems being used by most businesses.
1056
Many application software packages – such as word processors, spreadsheets, and games – run specifically on PCs. A desktop computer, also known as a workstation, fits comfortably on a desk and is the most popular from of PC. It consists of a computer case that houses the processor and disk drives, a display screen, and a keyboard. PCs can communicate with peripheral equipment, such as printers, scanners, and modems. Most businesses now connect personal computers together to form a network. Local area networks (LANs) and wide area networks (WANs) effectively distribute processing power across all the PCs on the network. Network servers, which are similar to PCs but much more powerful, manage the network security, shared files, and shared printers. A server is a computer that is optimized to provide services to other computers over a network. Servers generally have powerful processors, a lot of memory, and large hard drives. Computers are becoming smaller and more portable.
Laptops Personal digital assistants (PDAs) Wearable computers
Laptops Laptop computers are also called notebooks. They are more expensive than desktop computers because of the technology needed to fit the same processing power and storage space into a small unit. The advantage of a laptop over a desktop computer is that it is completely portable. Mains power or batteries can drive a laptop, but the batteries have to be recharged every few hours. Personal digital assistants (PDAs) A PDA fits into your hand, and so it is also known as a hand-held computer. It usually acts a personal organizer, but some models can download e-mails, play music, or do word processing. PDAs can communicate with other devices, such as disk drives and modems, to increase their functionality. Some PDA models take input from a special pen rather than a keyboard. Wearable computers Wearable computers have recently been developed. In these computers, common applications, such as e-mail and name and address databases, are integrated into watches, mobile phones, visors, and even clothing.
1057
Summary Many mechanical computing devices have been created throughout history, but the first generation of electronic computers began only in 1945. Computers have evolved, and we now use fifth-generation machines that are much more powerful and affordable than their predecessors. Computers can perform repetitive tasks more quickly and accurately than humans. They are often used to manage databases and spreadsheets and for word processing. Supercomputers, mainframes, PCs, servers, and portables are the main types of computers available today.
1058
Programming princples Learning objective
After completing this topic, you should be able to discuss the basic principles of programming.
1. Classical programming Because computers cannot think, they need instructions to tell them what to do. A program contains a set of instructions that a computer can use to perform a task. Computers understand only a language of 1s and 0s. This language is called machine language, machine code, or binary code. A typical machine language instruction is 0000010000010111. Computers use millions of solid-state electronic switches that represent 0 when they are off and 1 when they are on. Punch cards work on the same principle, with a hole representing 1 and the absence of a hole representing 0. The on and off states of a switch enable computers to use Boolean algebra, which was invented by the mathematician George Boole. Binary systems operate according to the rules of Boolean logic. These rules are used to perform calculations on data. Humans find it difficult to understand machine language, so assembly language was invented in the 1950s. Assembly language involves the translation of the number combinations in machine language into instructions written with letters. This is the assembly language instruction to add the value of variable "B" to variable "A."
Add A, B Each of the different computer types has a different assembly language. The same range of commands is available in assembly languages and in machine languages. A special program, called an assembler, translates the assembly-language program into machine language so that the computer can understand it and execute the instructions.
1059
Both assembly and machine languages are low-level languages, and they are processor dependent.
Note A processor, also known as a central processing unit (CPU), performs logical and arithmetic operations. It also controls memory and the execution of instructions. Because every processor type has its own architecture, an assembly-language program written for one processor will not run on a different processor type. High-level programming languages include
FORTRAN Pascal COBOL BASIC C
FORTRAN FORTRAN is an acronym of FORmula TRANslation. It is used for mathematical and scientific applications. It was the first high-level programming language and was published by IBM in 1950. Pascal Pascal was created around 1970 and is named after the mathematician Blaise Pascal. It was designed for simplicity and intended as a teaching language. Pascal has been influential in programming language design. COBOL COBOL is an acronym for Common Business Oriented Language. It was created in 1960, and it can process simple computations of large amounts of data. Programs written in COBOL tend to be longer than those written in other languages, but this wordiness makes COBOL easier to follow. COBOL was a popular language for business applications that ran on large computers, although it is not as widely used today as it was in previous decades. BASIC BASIC stands for Beginner's All-purpose Symbolic Instruction Code. It was first run in 1964 and is, as its name suggests, a quick and easy programming language for students and beginners. C C was created in 1972 as a system implementation language for the first UNIX operating system.
1060
Along with C++, Java, and C#, which are all to varying degrees based on it, C is the most widely used programming language for software implementation. High-level languages are closer to human languages than assembly languages because they use words based on spoken language, such as BEGIN, END, and IF. Compilers and interpreters are used to make machine-level versions of high-level language programs. Each high-level language instruction translates into five to ten machine-level instructions. Fourth-generation computer programming languages (4GLs) have commands that are very close to human languages. Fourth-generation computer programming languages (4GLs) have commands that are very close to human languages. SQL (Structured Query Language) is a fourth-generation language. Most fourth-generation languages manage databases. For example, this SQL command would return database details of all full time employees.
Select From Where
* Employees Full_Time = 'Yes'
Question Let's say that you want to compare how different programming languages implement an instruction to set the value of a variable called "A" equal to "3." See if you can match each code example to its language type. Options: 1. 2. 3. 4.
A := 3 1000100011100110 Set A equal to 3 MOV A,3
Targets: A. Machine language B. Assembly language C. High-level language D. Fourth-generation language
1061
Answer A := 3 is in high-level language, 1000100011100110 is in machine language, Set A equal to 3 is in fourth-generation language, and MOV A,3 is in assembly language. The further away a programming language moves from machine language, the more complex its translation becomes. So high-level programs demand more from computer resources to execute their instructions than low-level programs. High-level programs are easier to write, maintain, and understand than low-level programs. This is especially true when programs run into thousands of lines of code. Each programming language has its own strengths and weaknesses. For example, COBOL is very good at financial and business applications, whereas FORTRAN performs best with scientific calculations. If you intend to become a professional programmer, you will probably learn several languages during your career. Most people start off with an easy-to-learn but less powerful language. They then move on to more complex and powerful languages such as C, C++, or Java.
2. Programming trends Two mathematicians published a paper in 1966 to show that you can write any program using only three types of control structures:
sequence selection repetition
The paper led to an approach to programming called structured programming. Large programs are often too complex to handle by just starting at the beginning and working your way sequentially through to the end. So structured programming has evolved to include top-down development and modular design. Top-down development involves breaking a problem into components of a manageable size, resulting in more precise and reliable programs. Modular design groups tasks that perform the same function.
1062
For example, a calculation on overdraft interest will form one module in a program. Any other part of the program can use that module, so it may be called several times by other modules. Modular program design complements the top-down development approach because the substeps in the development process become modules in the program. Third-generation programming languages, such as Pascal, C, and BASIC, suit a structuredprogramming approach because they are procedural languages that need step-by-step instructions to arrive at a desired result. Fourth-generation languages were first developed in the late 1970s. They use one instruction to generate 30 to 50 machine-language instructions. Programs written using these languages can therefore be written quickly and easily maintained. Fourth-generation languages are considered nonprocedural because the programmer asks for a result without providing the steps to get there. For example, this SQL statement results in the Products table from the Inventory database being displayed.
GET Products FROM Inventory Most fourth-generation languages are used to access databases, which use the following components:
database management system (DBMS) database query language screen generator report generator
database management system (DBMS) The database management system ensures that the language can read the database properly. database query language The database query language allows users to specify exactly what they want from the database. screen generator The screen generator provides an easy-to-use graphical interface to quickly generate user-input forms. report generator The report generator creates customized reports within seconds.
1063
Fourth-generation languages are user-friendly, so people who are not trained as programmers can quickly learn to use them. Programs written in fourth-generation languages are good for extracting data and presenting it in a specific format. However, fourth-generation languages have compilers that are very large and slow when compared with those for third-generation languages. Examples of DBMSs that use fourth-generation languages include
Informix Oracle
Informix Informix provides relational database management systems that run on several UNIX platforms. Relational databases store data in the form of related tables. They are very powerful because data can be viewed in many ways. Oracle The Oracle database was the first database management system to incorporate the SQL language and to be used with a wide variety of platforms. SQL (Structured Query Language) is the industry's standard interactive and programming language that is used to extract information from and maintain databases. Oracle offers a variety of application development tools and is a major promoter of the network computer. Object-oriented programming (OOP) became an alternative to structured programming during the late 1980s. OOP creates computer abstractions from real-world objects. Each computer object has a set of properties and operations – or methods – associated with it. For example, the object "car_aerial" may have the property status "extended" or "retracted." And the methods "extend" and "retract" are also associated with the object. Object-oriented programs are modular. Modular programs are easy to debug because programming errors are usually limited to within a module. At first, mainly real-time and embedded software programs were written with OOP languages.
1064
Note Embedded software is normally used by very specialized applications. Appliances with a digital interface, such as microwave ovens and washing machines, employ embedded software. But these days many new information systems, of all types, are written using this methodology. Examples of OOP languages include
Smalltalk Java C++ C#
Smalltalk Smalltalk was the first language developed according to OO principles. Smalltalk has more rigorously enforced rules than C++. Java Developed by Sun Microsystems, Java is an object-oriented language that is similar to C++ but has been clarified to eliminate language features that cause common programming errors. Java has a number of features that make it suitable for use on the Internet. C++ C++ is a superset of the C language. It is generally considered to be one of the best languages for designing large-scale applications. C# Developed by Microsoft, C# (pronounced C sharp) is a hybrid of C and C++ that was developed to compete with Java. It was designed to improve productivity in the development of web applications while retaining the flexibility of C and C++.
3. The principles of good programming A good program is robust, efficient, usable, and maintainable.
Robust Efficient Usable Maintainable
Robust
1065
A program is said to be robust when it is fault tolerant. You should test your program extensively to indicate faults it cannot handle yet. You need to find a balance between the cost of testing a program and the need for error handling. You cannot feasibly test all programs for all faults, just as it is not possible to make all programs 100 percent error free. Efficient Programs should make efficient use of the system they run on. In aircraft, for example, the size and weight of computer hardware are limited. So the software will also be limited with regard to the storage space, memory, and processor speed. Programs that waste resources can grind the whole system to a halt when data volumes increase. Usable Usable programs are those that the end-user finds easy to operate. Usability depends on such factors as input forms, the menu system design, and information presentation. Informative error messages and help files improve usability. Offline user documentation, such as a printed manual, is often preferred by users, as it can be easier to read. However, online help files can be distributed and searched more easily, so they are more often included with software. Maintainable Maintaining a program involves making changes to a program after its implementation. A computer system seldom satisfies the needs of its users indefinitely – they will soon think of ways to improve it. So any software should be easily adjusted, altered, and developed. A programmer should understand and be able to modify programs, provided they are familiar with the programming language used. You have now learnt about the features of a good program
Question When writing a program, programmers should ensure that future users can understand and maintain their code. Which of these options do you think a programmer can use to make a program more maintainable?
1066
Options: 1. 2. 3. 4.
Comments within code Code bookmarks Numerical code Well-structured code
Answer Programmers can use well-structured code and documentation – including manuals, wellcommented code, and design notes – to make programs readable and maintainable. You can use indentation to make code clearer and easier to follow. You can use indentation to make code clearer and easier to follow. For example, you can indent each subpart of an IF statement to the right. You can see the difference indentation makes to readability.
(indented version) IF age < 12 THEN Classification := "child"; ENDIF (unindented version) IF age < 12 THEN Classification := "child"; ENDIF When programs contain hundreds or even thousands of lines of code, indentation – or lack of it – will significantly affect readability. Comments increase the readability of a program. All languages have a way of inserting text into code that will not be executed as part of the program. For example, C treats text between /* */ as comments.
/*This is program that demonstrates the IF age < 12 THEN Classification := "child"; ENDIF 1067
IF statement*/
It takes effort to think of meaningful variable names, but they greatly enhance a program's readability. You can compare these two pieces of Pascal code that print a list of employees and their salaries to see the difference that meaningful variable names make. The first section of code is easier to understand because the reader does not have to guess the meaning of the variables.
(meaningful variables) FOR employee := 1 TO Number_of_employees DO BEGIN PRINT (employee_name); PRINTLN (employee_salary); END (not meaningful variables) FOR I := 1 TO num DO BEGIN PRINT (n); PRINTLN (s); END Variable names should be descriptive without being too long. So "average_temperature" is preferable to "average_temperature_for_the_week." You do not need to capture all the information about a variable in its name. You can use comments in your code instead. You should be consistent in naming variables to improve a program's readability. Say you have declared the variable "employee_name." So you should use "employee_salary" rather than "salary_of_employee" to be consistent with your first declaration.
Question What features should a good program possess? Options:
1068
1. 2. 3. 4.
Efficiency Maintainability Robustness Small size
Answer A good program should be robust, efficient, and easy to maintain. Option 1 is correct. Programs should make efficient use of the systems on which they run. In aircraft, for example, storage space for software is limited with regard to the memory, and processor speed. Programs that waste resources can grind the overall system to a halt when data volumes increase. Option 2 is correct. The hallmark of a good programmer is being able to create programs that are easily maintained by programmers coming after him or her. Easy maintenance makes for faster time to market and increased customer satisfaction. Option 3 is correct. The best programming is defensive programming – allowing for as many potential failovers as possible, without exploding the codebase. For example, if an entry field is designed to accept only textual input, you should ensure that the system doesn't crash when a control key sequence is pressed. Option 4 is incorrect. It is not always possible to limit the size of a program, due to the vagaries of different applications. So long as the codebase is consistent, concise, and controlled, size is not a primary issue.
Summary A program contains the instructions needed for a computer to perform a task. The computer understands these instructions in machine code only – 1s and 0s. Programming languages are becoming more like natural languages. SQL is a fourth-generation language. Object-oriented programming (OOP) has become an alternative to structured programming. Computer programs should be maintainable. This can be done by using indentation, comments, and easily understood variable names within the program.
1069
This page contains a JavaScript function that prints out the current frame document. To print out the document without using JavaScript, you need to press Control P. & lt;/p> | Print | Contents | Close |
Software life cycle phases Learning objective
After completing this topic, you should be able to describe the phases of the software life cycle.
1. Introducing the software life cycle Software varies in complexity depending on what it is required to do. Most software packages consist of many modules, with each module responsible for performing a different task. Each module must be planned, written, and tested before it can be integrated with the other modules to form the complete package. To simplify software development, a continuous series of logical steps called the software life cycle is followed throughout the lifetime of the software.
Question The software life cycle can be represented as a circle. See if you can match each step of the software life cycle to its position in the diagram if 1 is the first step
Options Option
Description
A
Coding the program
B
Testing the program
C
Understanding the problem
D
Maintaining the program
E
Designing the program
1070
Answer Correct ranking Option
Description
C
Understanding the problem
E
Designing the program
A
Coding the program
B
Testing the program
D
Maintaining the program
There are typically five steps involved in the software life cycle.
Step 1: Understanding the problem Step 2: Designing the program Step 3: Coding the program Step 4: Testing the program Step 5: Implementing and maintaining the program
Step 1: Understanding the problem In the first phase of the software life cycle, the tasks that the software must perform are listed. The problems to be solved, and their causes and effects, are studied in this phase. The specific task that is required from the program is derived from the problem statement, which is a concise description of the problem being addressed. The software must provide a usable solution to this problem. Step 2: Designing the program In the design phase, the program is designed to fulfill the required goal. The aim of the design phase is to meet the required goals of the program in a logical, efficient, and economical manner. The designers consider the software and hardware resources that are available to achieve the goal. If the existing hardware and software are unsuitable, new software and hardware components may have to be designed. The overall structure of the program is designed first. This is then broken down into smaller and smaller tasks until the tasks are of a manageable size.
1071
These individual components are called "modules." Step 3: Coding the program During the coding phase, the program is written in a programming language. A variety of languages can be used, each with their own advantages and disadvantages. For example, FORTRAN is a good language to use for processing numerical data, whereas LISP is good for artificial intelligence applications. Program code should perform the required tasks, and it must be readable so that other programmers can maintain it. Programs are often written in separate modules, with each module performing a particular task. Each module must function properly independently and in relation to the rest of the program. Step 4: Testing the program During the testing phase, the program is run and checked. It must accomplish the tasks required of it, and it must run without errors. Defects in programs are commonly called "bugs." Individual modules and procedures are first examined for bugs independently of each other, and then the entire program is tested to find bugs that appear when the modules interact. When a bug is found, its causes are isolated so that they can be resolved. This process is called debugging. The programmer must ensure that solving one particular bug does not create other bugs elsewhere in the program. Step 5: Implementing and maintaining the program During the maintenance phase, any errors and deficiencies in the program are identified and any necessary improvements are made, while preserving the program's integrity. The use of design notes, well-commented code, and understandable variable names can aid future maintenance of the program. You have now learned about the five steps involved in the software life cycle.
2. Programming development roles One person on their own can guide simple programs through each stage in the software life cycle. But this is usually the exception, as most programs today are large and complex. A software company usually employs a number of different teams, each of which is responsible for a different phase in a program's development.
1072
A programming development team typically consists of several programmers, as well as a programmer analyst and a systems analyst. An assistant programmer is usually an inexperienced, entry-level programmer. Assistant programmers do not write any new programs. Instead, they perform routine maintenance tasks on other programs. A programmer will initially perform the same tasks as an assistant programmer. When the programmer has gained some experience, they may then be asked to write new programs. The specifications for these programs would already have been created. Senior programmers are given the program specifications and write the new programs. They don't maintain any old code but focus on generating new code. A programmer analyst works closely with the program designers. In addition to programming new code, programmer analysts begin to learn the techniques and skills of program design.
Question Systems analysts and programmers have different roles within a development team. See if you can complete the statement about these different roles. Options: 1. Programmers 2. System analysts Targets: A. Programs are designed by B. But they are written by
Answer Programs are designed by system analysts, but they are written by programmers. A systems analyst is an intermediary between the client and the programmers. Clients communicate their needs to the systems analyst. The analyst translates these requirements into program designs and communicates these to the programmers, who then do the actual programming.
1073
Question Match the programming development roles with the relevant responsibilities. Options: 1. Programmer 2. Programmer analyst 3. Systems analyst Targets: A.
This person liaises with clients B. This person designs programs C. This person codes the design
Answer A systems analyst analyses client requirements. A programming analyst designs a code-based architecture, while programmers actually write the code. Programmers are responsible for developing code, often in several different languages like C, C++, and Java. This is because most companies must maintain codebases in all the popular languages. Programmers are often involved in unit-testing the code they write. Unit tests are basic tests, performed before an application goes for full-scale testing with the QA (Quality Assurance) team. A programming analyst develops a high-level architecture, based on client requirements. In so doing, he or she must consider the language used and the abilities of the programming team. While a particular task may be technically possible, it may be practically impossible due to the implementation language. A systems analyst is a senior role. This person must liaise with clients at a high level and yet be capable of translating their requirements at the technical level. Moreover, a systems analyst should possess a low-level overview of the completed system.
Summary To simplify software development, a series of logical steps known as the software life cycle is followed. This life cycle involves understanding the problem that needs to be solved, designing the program, coding and testing the program, and then maintaining the program. Programs are usually large and complex, so they are guided through each stage in the software life cycle by a development team. The team consists of several programmers, a programmer analyst, and a systems analyst.
1074
Program development Learning objective
After completing this topic, you should be able to describe the phases of program development.
1. Coding a program Writing a program involves a series of separate processes.
Question The process of writing a program involves six steps. See if you can place these steps in the correct order.
Options Option
Description
A
Compiling the program
B
Running the program
C
Understanding the program specification
D
Coding the program
E
Designing the program
F
Debugging the program
Answer Correct ranking Option
Description
C
Understanding the program specification
E
Designing the program
1075
Correct ranking Option
Description
D
Coding the program
A
Compiling the program
B
Running the program
F
Debugging the program
When writing a program, the programmer must complete each of these steps.
Understanding the program specification Designing the program Coding the program Compiling the program Running the program Debugging the program
Understanding the program specification The programmer must understand the program's input data, output data, and the logical processing of this data, including all calculations. Designing the program The programmer designs the program using design tools, such as pseudocode or a structured flowchart. These tools detail the program's logical tasks and the order in which they must be executed. The programmer must thoroughly analyze the design to ensure that it yields the correct results. Coding the program A programmer codes a program by writing it in a particular computer language. Code can first be written on paper – recommended for novice programmers – or it can be written directly on the computer using an "editor." The programmer checks the code's logic and syntax to ensure that they are correct. They do this by desk-checking – manually checking the code for errors. Desk-checking usually uncovers several errors that can be corrected before the code is compiled. Sometimes programmers review each other's code. This encourages good programming practice and double-checks the code for errors.
1076
Compiling the program Computers can execute machine language code only. The process of translating higher-level programming language code into machine language code is called compiling or interpreting the program. Special programs, called compilers and interpreters, perform this task. Compilers are more commonly used than interpreters. Code that has errors in it cannot be compiled. The compiler will flag the error, and the programmer must fix the error before trying to compile the code again. Running the program Once a program is compiled, it can be executed. Debugging the program The programmer checks the program's output to ensure that it is correct. Even though there may not be any syntactical errors in the code, logical errors in the program's design can produce incorrect output. There are many possible errors in a program, from more serious design errors or incorrect syntax to simple typing errors. Any errors prevent a program doing what it is supposed to do. The debugging process should continue until all the bugs have been removed. You have now learned about the steps involved in writing a program.
2. Editors Editors are software applications that allow programmers to type the text for programs into a computer. Unlike word processors, editors don't allow words to "wrap" onto the next line because word wrapping could cause problems in the program code. The two types of editors are
line editors full-screen editors
Line editors predate full-screen editors. They allow only one line of code to be edited at a time. The programmer must specify which line will be edited. Two popular line editors are
1077
vi Edlin
vi Short for "visual," vi is a UNIX-based editor. Edlin Short for "edit lines," Edlin is an editor for MS-DOS.
Question Word processors can be used to write code. Which of the following formats do you think you should use to save code created in a word processor? Options: 1. Word 2. Rich text 3. Text only (ASCII)
Answer Word-processed documents contain formatting information that can create errors in code, so program files should be saved as text only or ASCII files. These files contain only the text that is typed. Full-screen editors are easier to use than line editors because they allow the programmer to edit any line at any time. They may provide a number of tools to make editing the code easier:
drop-down menus integration with compilers and interpreters colored text IntelliSense
drop-down menus Full-screen editors make commands available through drop-down menus, so the programmer doesn't have to memorize them. integration with compilers and interpreters The integration of program compilers and interpreters with editors offers major advantages for programmers. It means that code can be typed, edited, compiled or interpreted, and executed from within the same program.
1078
This differs from line editors, in which a separate program performs each function. colored text Some editors can display specified words in a particular color to distinguish them from the remaining code. These words are called reserved words, for example, "BEGIN" in Pascal. Color-coded reserved words are easy to locate improving the readability of the program. IntelliSense IntelliSense enables the programmer to begin typing a command and the editor "senses" which command the user requires and completes the remainder of the word. For example, when the programmer types be, the editor may complete this to "begin." If this word is not the command required, the programmer continues by typing over it.
3. Compilers and interpreters A source file contains the code written by the programmer. Computers can execute only instructions in machine language, so source files cannot be executed directly. A compiler first converts a source file into an intermediate file called an object file or object code file. The object file contains a translation of the program code in machine language, but it is not yet a complete program. A linker program combines the modules in the object file to form an executable file. An executable file is complete in itself and does not need to refer to the original source code. This means that it runs quickly. An interpreter translates program code into machine language. It differs from a compiler in that it executes each statement as it is translated. This process can slow down a program significantly, so interpreters are not as widely used as compilers.
Question What does a compiler do? Options: 1. It creates executable binary code 2. It enables you to write source code 3. It links object modules
1079
4. It translates source code into object code
Answer A compiler translates source code, written in a programming language, into binary object code that the machine can interpret. Option 1 is incorrect. A compiler creates binary code, but this code is not directly executable by the machine. In particular, the machine still needs to be told how the object modules interact and where the memory starting point for the program lies. Option 2 is incorrect. A compiler is not a source code editor. The source code must exist before a compiler can be invoked. You can write source code using any text editor, like Notepad, or a specialized programming editor like those found in Visual Studio or Netbeans for Java. Option 3 is incorrect. The final stage in creating an executable program involves running a linker against the object modules created by a compiler. For example, you can use Blinker – a fast, compact linker – to link C, C++, or Clipper object files. Option 4 is correct. A compiler is usually a command line utility that runs against existing source modules. It outputs files in binary code. For large systems, you can include multiple source files in a script file. You can then invoke a utility like Ant to orchestrate the compilation process.
4. Debuggers, code errors, and comments Debugging code involves removing errors from it. All errors must be removed before the program can be said to be complete. The two main types of errors in code are
syntax errors logic errors
syntax errors Syntax errors occur when a programmer writes code that does not conform to the rules of a computer language. They are like errors of grammar in English. Unless the syntax of a line of code is correct, it cannot be translated into machine language. logic errors Logic errors are errors in the design of the program. The line of code conforms to the necessary rules of the language, but the code is based on flawed logic. Logic errors are less obvious than syntax errors, so programs can be compiled or be interpreted
1080
without reporting this type of error. The errors are often discovered only when the program is run and the output studied. A debugger runs a program one line at a time so that the programmer can examine it for errors. This is particularly useful for picking up and repairing logical errors. Code should be readable and understandable in order to be maintained. Comments can be written into the code to ensure that it meets these requirements.
Question It is good practice to insert comments into program code. For whose benefit do you think comments are written into the program code? Options: 1. 2. 3. 4.
The programmer The systems analyst The vendor of the program The end-user of the program
Answer Comments help programmers to understand the code when they want to maintain or change the program code. Comments are used to provide explanatory notes to the programmer about the function of specific parts of the program code. Comments are placed between opening and closing tags, such as /* and */ in C. Everything in comments is ignored by the computer.
Summary The process of writing a program involves a number of steps, from first understanding the program's specification and designing the program, to coding and compiling the program, and finally running and debugging the program. A programmer can use a line editor or a full-screen editor to enter the text for a program into a computer. Code can also be typed into a word processor and saved in ASCII format. Compilers and interpreters convert program code into executable files. Compilers are more popular because they create faster-running executable files than interpreters.
1081
Debuggers are better at finding syntax errors – such as spelling mistakes – than errors in a program's logic. However, the logic errors in a program must be removed before it can run properly. The program code can be made more understandable by adding comments.
1082
Defining algorithms Learning objective
After completing this topic, you should be able to define algorithms and explain how they are constructed.
1. Introducing algorithms An algorithm is a set of instructions for solving a problem. It takes input, processes it according to a set of instructions, and generates output. A cake recipe is an example of an algorithm. In this example, the problem is that you want to bake a cake and the input is the list of ingredients. You follow the instructions to generate the cake as output. The problem defines the desired output, which in turn determines the inputs and instructions. For example, you decide what type of cake you want, which in turn determines the ingredients and the directions. Suppose that you decide to write an algorithm to boil water. The input is a quantity of water at any temperature below boiling point and the output is boiling water. An algorithm must provide correct output for every possible input condition.
Question Say you want to write an algorithm to boil water. Rank the steps of this algorithm in the correct order.
Options Option
Description
A
When the kettle is boiling, switch off the kettle
B
Switch on the kettle
C
Plug in the kettle
D
Check that the kettle contains at least 1 quart of water
1083
Options Option
Description
E
If the kettle contains less than 1 quart of water, fill it with water
Answer Correct ranking Option
Description
D
Check that the kettle contains at least 1 quart of water
E
If the kettle contains less than 1 quart of water, fill it with water
C
Plug in the kettle
B
Switch on the kettle
A
When the kettle is boiling, switch off the kettle
You can write algorithms in ordinary English. To produce consistent results, the language used must be free from ambiguities. A statement such as Check that the kettle has enough water is ambiguous because "enough water" has different meanings in different situations. The statement Check that the kettle contains at least 1 quart of water is preferable because it defines what "enough" water is. In the following example in the algorithm box, you must include a step to fill the kettle with water under specific conditions. Check that the kettle contains at least 1 quart of water If the kettle contains less than 1 quart of water, fill it with water And you add instructions to plug in the kettle and switch it on.
1084
Plug in the kettle Switch on the kettle An algorithm must have a definite end point so that when the input has been processed and the desired output achieved, the process stops. You add the final instruction to complete the algorithm. When the water is boiling, switch off the kettle
2. Top-down design The solution to a problem can be complex and the detail involved overwhelming. For programs that are thousands of lines long, it is impossible to keep all the program details in mind when developing an algorithm. The top-down design approach is a well-known algorithm design tool that first presents a solution to an overall problem using three or four steps only. Each step in the first solution is then broken down into further substeps. The process is repeated several times, with each iteration producing a more detailed solution to the original problem. When the steps cannot be broken down further, the algorithm is complete.
Note The top-down design approach is also called functional decomposition or stepwise refinement.
Question Top-down design is a specific approach to a problem. Which method do you think top-down design encourages? Options: 1. Starting with the details 2. Starting with the overall problem 3. Considering the overall problem and the details at the same time
Answer Top-down design encourages the developer to start with the overall problem. Top-down design automaftically produces modules in an algorithm.
1085
Note Modules are groups of instructions that perform specific functions. Let's say that you want to write an algorithm to print invoices and identify these tasks in the first iteration of top-down design. The step calculate the total invoice amount can be further refined. retrieve customer details retrieve all order details for that customer calculate the total invoice amount add 5 percent interest to orders one month overdue add 10 percent interest two months and older sum the orders add sales tax print the invoice By decomposing the original instruction, modules – such as the calculate the total invoice amount step – become evident. retrieve customer details retrieve all order details for that customer calculate the total invoice amount add 5 percent interest to orders one month overdue add 10 percent interest two months and older sum the orders add sales tax print the invoice For each customer that is retrieved, the main algorithm calls a module and the invoice amount is calculated.
3. Pseudocode Pseudocode is used to bridge the gap between algorithms and programming languages – it is an outline of a computer program, written in a format that can easily be converted into programming statements.
Question Pseudocode enables you to write algorithms in a defined and consistent way Which of the following do you think is true of pseudocode? Options:
1086
1. It can run as a program in its own right 2. It must adhere to a recognized standards 3. There is no absolute standard for pseudocode
Answer There is no absolute standard for pseudocode. There is no absolute standard for pseudocode, but you can follow these guidelines:
use simple English write each instruction on a separate line use indentation where appropriate provide only one entry and one exit point for an algorithm group instructions into modules
You can make your pseudocode clear and concise by using simple English. The statement Find the difference between numbers A and B is more clearly expressed as Difference = A - B. Having multiple instructions in one line makes your algorithm harder to follow. BEGIN READ A READ B CALCULATE Difference = A-B PRINT Difference END By allowing one line per instruction, your code is easier to follow. BEGIN READ A READ B CALCULATE DIFFERENCE = A-B PRINT DIFFERENCE END If the sequence in which instructions are performed is subject to such control structures as IF statements, you should use indentation for clarity. When the execution sequence returns to normal, the indentation should return to its previous level. IF B = 10 THEN A = A-B ENDIF C = A-B To avoid having to keep track of code that will not execute, you should ensure that your algorithm has only one entry and one exit point.
1087
Sometimes, a set of instructions performs the same operation repeatedly at different points in the algorithm, and instructions can be grouped together into a module with its own name.
Question Suppose that you are writing a piece of software to address circulars, and you have a piece of code to print and format an address. You want to reuse the code to print and format addresses in the algorithm for addressing circulars. Which of the following do you think you should do? Which of the following do you think you should do? Options: 1. 2. 3. 4.
Place the code in a separate module and call it as required Modify the code for each instance it is called upon Copy and paste the code each time it is needed Indent the code
Answer If you want to reuse a piece of code that performs a certain operation, you should place the code in a separate module and call it as required. Pseudocode is not a programming language – it will not run or execute. Rather it is a design tool you can use to plan your code.
4. Transforming input Computer code uses specific language conventions for basic computer operations.
Question Computers receive input from sources such as a file or modem. Which of the following statements do you think you would use to initiate input operations? Options: 1. 2. 3. 4.
GET SEND READ FORMAT
1088
Answer GET and READ are the statements that initiate input operations. You can use the GET statement to acquire input from the keyboard, whereas the READ statement acquires input from any other source, such as a file. Computers can output data to the screen, other devices, or files. The PUT, OUTPUT, or DISPLAY statements send data to the screen. And you use the WRITE statement to store data on a computer file. In statements, a noun usually follows an input or output command. This noun can be the name of a variable in which you can store values. You can use the INITIALIZE, SET, STORE, or SAVE statements to assign values. For example, the command SET total TO 10 stores the value 10 in the variable total.
Note INITIALIZE sets a value at the beginning of a program. You can use a variable to store an input value. The code GET total will assign the value typed on the keyboard to the variable total The code PRINT total will output the value stored in total to a printer. However, you can enclose text in single quotation marks to output specific text. For example, the code PRINT 'total'
1089
will output the text 'total' to the printer. Arithmetic operations are central to computer operations. In code, you can use these symbols to describe arithmetic operations.
= + * / ()
= = (equal to) You can use = to assign a value. For example, the code total = 4 assigns the value stored in total to 4. + + (plus sign) You can use + to add values. For example, the code total = total + 1 adds one to the value stored in total. - (minus sign) You can use - for subtraction. For example, the code total = total - 1 subtracts one from the value stored in total.
1090
* * (asterisk) You can use * for multiplication. For example, the code total = total * 2 multiplies the value stored in total by two. / / (forward slash) You can use / for division. For example, the code Total = total / 2 divides the value of total by two. () () (parentheses) You can use () to indicate order of precedence. The code Total = total 3 * (2+4) will set the value of the total to 18. The addition is performed prior to the multiplication. You have now learnt about arithmetic operations.
Summary An algorithm is a set of instructions designed to solve a specific problem. Every algorithm must take input, perform some action on that input, and then generate output. You can use top-down design to simplify a problem into steps and substeps. This process reveals a modular structure for your code. You can use pseudocode to structure an algorithm. Pseudocode is a useful design tool – it clarifies design problems and reveals errors in logic.
1091
Specific language conventions are used for basic computer operations. Algorithms can express the arithmetic operations that you require a computer to perform.
1092
Construction an algorithm Learning objective
After completing this topic, you should be able to describe the GOTO statement, the Structure Theorem, and how to write an algorithm.
1. The GOTO statement Before structured programming was developed in the 1960s, programmers used the GOTO statement to pass control to a part of the program other than the next statement. Depending on the programming language, code lines were identified by names or numbers. For example, to transfer control to the code at line 151 in a program, programmers used the statement GOTO 151. The problem with the GOTO statement is that it results in a program that jumps backward and forward, making the logic difficult to follow. This is known as "spaghetti code." Because of the difficulties in following the logic, programs that use many GOTO statements are prone to errors and tend to be unreliable. Let's suppose that you want to write a program that prints address labels. Some people have street addresses, whereas others have mailboxes. You need to cater for both possibilities in your algorithm. The following code is used to print address labels using the GOTO statement.
21: 22: 23: 24: 25: 26: 27: 28:
PRINT name IF street IS empty GOTO 25 PRINT street GOTO 26 PRINT postbox PRINT city PRINT state GOTO 17
The following code is used to print address labels uses the IF…THEN…ELSE statement. This code is simpler and easier to follow.
1093
IF street IS empty THEN PRINT postbox ELSE PRINT street ENDIF PRINT city PRINT state The structured program reads and executes each line of code sequentially. The logic and outcome of both the GOTO and IF…THEN…ELSE programs is the same, but it is easier to follow the logic of the structured program's code.
2. Introducing the Structure Theorem In 1966, mathematicians Böhm and Jacopini published an article outlining what is now known as the Structure Theorem. The Structure Theorem shows how any program can be written using three control structures:
sequence selection repetition
sequence A computer program executing in sequence performs each instruction once only. The instructions are executed in the sequence in which they appear, and the program does not skip or repeat any of the instructions. selection Selection implies that a choice will be made, which depends on the value of a condition specified by the programmer. repetition Repetition repeats a section of code while a certain condition holds true. One form of selection is IF…THEN…ELSE.
If I = (a condition) THEN Response.Write(i) ELSE
1094
EXIT ENDIF In most programming languages, an IF statement ends with some form of the corresponding keyword for example ENDIF. IF…THEN…ELSE makes a selection from two options.
Question In this example, selection is made based on the variable "age." Which statement do you think is executed if age equals 18?
IF age < 18 THEN OUTPUT 'You cannot vote yet' ELSE OUTPUT 'You can vote ' ENDIF Options: 1. 2. 3. 4.
Both output statements Neither output statement The first output statement The second output statement
Answer The second output statement is executed if age equals 18. Because the code is written so as to make a choice between the two options, both statements cannot be executed at once. Because the code is written so as to make a choice between two options, one of the two statements must execute. The first output statement will execute when the value of age is less than 18. The second output statement will execute when the value of age is 18 or more.
1095
You may want no action to be taken when the condition in the IF statement is false. To do this, you can use a null ELSE statement. A null ELSE statement has no code associated with it, so you can leave it out. The following code is an example of a null ELSE statement.
IF age >=18 THEN STORE name IN voters_roll ENDIF In this case, no code will be executed for those under 18. Repetition repeats a section of code while a certain condition holds true. A WHILE…DO loop is used to initiate the statement block to be repeated. The statement block ends with ENDWHILE.
seats_allocated = 0 WHILE seats_allocated < 5 DO GET booking PRINT ticket ADD 1 to seats_allocated ENDWHILE Here is an example of repetition that prints tickets for six child seats on a minibus. The program initializes seats_allocated before it enters the loop. If you omit this statement, the loop cannot run, as seats_allocated has no value that can be judged to be less than 5.
seats_allocated = 0 WHILE seats_allocated < 5 DO GET booking PRINT ticket ADD 1 TO seats_allocated ENDWHILE While seats_allocated is less than five, the program executes the code in the repetition block, which is the code up to the ENDWHILE statement. You should note that the control variable seats_allocated changes every time that the statement block executes. If the control variable stayed the same during the loop execution, the loop would not end.
1096
When five seats have been allocated, the program moves to ENDWHILE, ending the loop.
seats_allocated = 0 WHILE seats_allocated < 5 DO GET booking PRINT ticket ADD 1 TO seats_allocated ENDWHILE
3. Defining a problem You must understand a problem before you can write an algorithm that solves the problem. A problem is normally presented in the form of a statement or a requirement.
Question See if you can identify the three defining elements of an algorithm. Options: 1. 2. 3. 4.
Input Output Process Questions
Answer Input, process, and output are the three defining elements of a programming problem. Option 1 is correct. For example, an algorithm for performing automatic updates on database records would take record field data types as input. Instead of passing an unknown number of parameters to the algorithm, a smarter version would take an array as input and process the array. You can extend this concept to multi-dimensional arrays. Option 2 is correct. Typically, an algorithm will return a true or false value indicating success or failure. It can also return values, allowing it to interact with the calling routines. Using OO (object oriented) languages, it is particularly useful to be able to return whole objects, where necessary. Option 3 is correct. Processes vary, depending on the purpose of the algorithm. However, a generic algorithm involves one or more loop statements and an operation on its arguments. A well-designed algorithm should perform its own housekeeping – such as freeing memory and disk resources – and error handling.
1097
Option 4 is incorrect. Each algorithm should perform a well-defined, basic task. In this way, you avoid overly complex code and facilitate code reuse. To allow a single algorithm to respond to diverse questions limits the flexibility of the code by involving too many hard-coding practices. The process comprises the actions that transform the given input into the desired output. Verbs such as "find," "calculate," and "sort" are used to identify processes. Nouns, adjectives, and adverbs in the problem statement normally describe input and output. Nouns, adjectives, and adverbs in the problem statement normally describe input and output. When you have identified all the elements of a problem, you list them in a defining table. The table has three columns – Input, Process, and Output. You can use the table to write an algorithm – its processes become statements in the algorithm. And the input and output elements become arguments for the statements.
Note A defining table is also known as an input-process-output table. In programming statements, arguments are comparable to objects in the grammar of human language sentences. So in this statement, GET is the verb and booking is the object, or argument.
seats_allocated = 0 WHILE seats_allocated < 6 DO GET booking PRINT ticket ADD 1 TO seats_allocated ENDWHILE Question Suppose that you need to calculate the speed a courier must drive at in order to cover a given distance within a given time. See if you can identify the input elements of the problem. Options: 1. The noun "time" 2. The noun "speed" 3. The noun "distance"
1098
4. The verb "calculate"
Answer The nouns "distance" and "time" are input elements of the problem. The noun "time" is an input element of the problem. The noun "speed" is an output element of the problem. The noun "distance" is an input element of the problem. The verb "calculate" is a problem process that calculates the value of the variable "speed." For every input element in the problem, there will be a statement such as GET distance. The final output element has to be presented to the user, so your defining table must include a process to deliver the output, such as DISPLAY speed. You can now use your table to write your algorithm.
4. Writing an algorithm Once you have defined the problem, you can write the algorithm. You will probably need to rework your algorithm several times in order to improve it. Algorithms have certain characteristics. Every algorithm starts with a name that describes what it does. It usually starts with a verb and ends with a noun as shown in this example. All the instructions between the algorithm name and the END statement should be indented for readability. Every time a new control structure is introduced, it must be left indented. At the end of the control structure, the indentation returns to the previous level.
CALCULATE overdraft_interest WHILE answer="Y" DO READ name READ address PRINT label DISPLAY "Print another?" ENDWHILE
1099
Each processing step in the defining table results in one or more pseudocode instructions. The items in the Input and Output columns become arguments for the instructions. The END statement concludes an algorithm.
WHILE answer="Y" DO READ name READ address PRINT label ENDWHILE Question Let's suppose that you want to write a program that converts a distance in kilometers to a distance in miles. There are 0.625 miles in every kilometer.. See if you can match each option to its correct place in the defining table Options: 1. miles 2. kilometers Targets: A.
Input column B. Output column
Answer Kilometres goes in the input column, and Miles goes in the output column. You need a process that gets the kilometers from the user. You need a process that gets the kilometers from the user. The verb "converts" in the problem statement indicates a process. So you have to calculate the number of miles that is equivalent to the given number of kilometers. And you need a process to display the calculated miles. You can use your table to write your algorithm. The algorithm first asks for a distance in kilometers from the user. Then it converts that number into miles.
1100
Finally, it displays the result.
Convert kilometers_to_miles DISPLAY 'Enter the distance in kilometers.' GET kilometers miles = kilometers * 0.625 DISPLAY kilometers 'kilometers = ' miles ''miles.' END The program that converts kilometers into miles would typically execute as follows.
Enter the distance in kilometers. 10 10 kilometers = 6.25 miles.
Summary The GOTO statement can be used to pass control to a part of the program other than the next statement. It is very difficult to follow the logic of programs that use many GOTO statements. The Structure Theorem shows how any program can be written using three control structures only – sequence, selection, and repetition. This eliminates the need for GOTO statements in programs. A problem is normally presented in the form of a statement or a requirement, which consists of three elements – input, output, and process. Once identified, the problems can be listed in a defining table. The defining table can be used to write an algorithm. Algorithms begin with a name and end with an END statement. Their instructions are indented for readability.
1101
Creating an algorithm Learning objective
After completing this topic, you should be able to structure an algorithm.
1. Exercise overview In this exercise, you are required to identify the input, process, and output elements of problem statements in order to construct an algorithm. This involves the following tasks:
using a defining table to create a letter-counting algorithm using a defining table to create a tax-calculating algorithm
2. Task 1: Structuring a letter counting algorithm Suppose that you want to write an algorithm that asks the user to enter two words and then displays the number of letters in the first word, the number of letters in the second word, and the total number of letters in both words.
Question In order to create your algorithm, you must first use a defining table to identify the input and output elements and the order in which they should appear in the algorithm. Rank the following options in their correct position in the Input and Output columns. Options: 1. 2. 3. 4. 5.
word_length1 total word_length2 word1 word2
Targets: A. B. C. D. E.
Input 1 Output 1 Input 2 Output 2 Output 3
1102
Answer Input 1 is word1,.Output 1 is word_length1, Input 2 is word2, Output 2 is word_length2, and Output 3 is total. word_length1 corresponds to the number of letters in the first input , word1. This algorithm is designed to output a result immediately following each input, and an additional total output at the end. After entering two words, the algorithm returns the total number of characters in the combination of both words. You could extend this algorithm to receive a variable number of words. word_length2 is the number of letters in the second input , word2. As the algorithm stands at the moment, the total number of characters is output straight after this result. word1 is the first input parameter. If the algorithm is well designed it will gracefully shut down if it encounters a problem, such as an invalid or missing input. A good algorithm does not assume the availability of required elements. word2 is the first input parameter. Note that, in this case, the algorithm is symmetric, in that you can reorder the inputs to get the same total.
Question Suppose that you want to structure the processes that will change the input elements to the desired output elements. Rank the following processes in the Process column of the table in the order in which they should appear in the algorithm.
Options Option
Description
A
ADD word_length1+word_length2=total
B
GET word1 GET word2
C
PRINT total
D
CALCULATE word_length1 CALCULATE word_length2
1103
Answer Correct ranking Option
Description
B
GET word1 GET word2 Once inside an algorithm, the first step is to retrieve the parameters passed to it. This step depends on the programming language used – in this case, you use the GET operation.
D
CALCULATE word_length1 CALCULATE word_length2 You calculate the length of each input once that parameter has been successfully retrieved from the calling routine. A letter-counting routine can be an algorithm in itself. You can refactorize this routine to further modularize your code.
A
ADD word_length1+word_length2=total The ADD operation takes two integral inputs and adds them together. Note that this operation can easily be expanded to accept more than two inputs, making the algorithm more dynamic and flexible.
C
PRINT total Every programming language has an equivalent of a PRINT operation that prints to the standard output – usually the screen. Standard output can be redirected to a printer, a file, or some other device.
The defining table has been completed and you can now create your algorithm.
3. Task 2: Structuring a tax-calculating algorithm Suppose that you have to write an algorithm that calculates and prints the tax payable on an invoice total. You also want to print the final invoice amount, including tax.
Question You have identified all the input, process, and output elements necessary for your algorithm. Rank the elements in the position they should appear in the Input, Process, and Output columns of the table and in the order in which they should appear in the algorithm.
Options
1104
Option
Description
A
tax / final_amount
B
PRINT tax / PRINT final_amount
C
GET invoice
D
ADD tax+invoice=final_amount
E
CALCULATE tax
F
invoice
Answer Correct ranking Option
Description
F
invoice This is the only necessary input to this algorithm. Normally, an invoice reference is in the form of a unique numeric or character ID which references a database record, based on a primary key.
C
GET invoice After passing an invoice reference into the algorithm, it looks up the invoice code in a memory table or database table. The result of this operation is the details of the invoice, such as the client, the products, and total cost.
E
CALCULATE tax Each invoice generates a different amount of tax, depending on how large the invoice is and its geographical location.
D
ADD tax+invoice=final_amount The tax that the algorithm calculates against a particular invoice must be added to the invoice amount. This gives the total billing amount to each client.
B
PRINT tax / PRINT final_amount The penultimate step in this algorithm is the printing of the tax and final amount. Printing results is merely an informative process – usually to aid debugging. Most algorithms return their results to the calling routines.
A
tax / final_amount The last step that this algorithm performs is to return the results it calculates to the calling
1105
Correct ranking Option
Description routine. The algorithm doesn't disturb any inputs passed to it – in fact, in most cases, parameters are passed by copy and not by reference.
1106
Variables, constants, and data types Learning objective
After completing this topic, you should be able to discuss the roles of variables, constants and data types in a program
1. Variables and constants Computers use data to perform tasks in a function called data processing. Data processing is made possible when data is stored in a computer's memory.
Question Data may be changed or remain the same during data processing. Which of the following terms do you think describes data that is preset and remains unchanged during processing? Options: 1. 2. 3. 4.
Variable Constant Operator Procedure
Answer The term constant describes data that is set before the program is used and will remain the same while the program is running. The term variable describes data that may change while the program is running. Although variables may change while the program is running, they are often given a starting value by programmers to allow them to be used within an application. This is known as initializing the variable.
2. Naming variables and constants During processing, an address is used to store data in a particular location in the computer's memory. Memory addresses are identified by hexadecimal numbers, such as 166D. However, in order to make the address more memorable, it can be given a name.
1107
Note Whereas the decimal system is a base 10 counting system, the hexadecimal system is a base 16 counting system. The hexadecimal system utilizes numbers from 0 to 9 and letters from A to F.
Question Programming languages have rules that govern how constants and variables are named. Which of the following rules do you think apply when naming variables and constants? Options: 1. 2. 3. 4. 5.
Names may not be the same as those reserved as keywords in a programming language Names may not begin with a digit Names may not begin with a letter Certain characters may not be used in variable names Names must have a minimum length of eight bytes, or characters
Answer Some programming languages do not allow the use of certain characters in constant and variable names. Names may not begin with digits, and they may not be the same as those reserved as keywords in a programming language. Certain languages don't allow the use of specific characters. BASIC, for example, does not allow the use of characters such as * (asterisk), + (plus sign), and () (parentheses). And variable or constant names may not begin with digits or certain characters. For example, the names "2jan" and "12month" would not be allowed because they begin with digits. But the names "jan2" and "month12" would be acceptable. Keywords, which are used in programming languages, may not be used as variable or constant names. For example, FOR is a keyword in BASIC and var is a keyword in Pascal. Neither of these words could be used as constant or variable names in their respective languages. Constant and variable names are allotted a maximum length depending on the language being used. In Pascal, a variable name may not exceed 32 characters.
Question To understand the purpose of a particular variable or constant, it is important to give it an appropriate, meaningful name.
1108
Which of the following naming conventions do you think result in an appropriate, meaningful variable or constant name? Options: 1. The name of a variable or constant should be transparent enough to describe the data it represents 2. The number of characters in each constant should be five or less 3. Each name must be unique within the part of the program in which it is used. 4. Each variable name should begin with the prefix "vari."
Answer The name of a variable or constant should be transparent enough to describe the data, and each name must be unique within the section of the program in which it's used. A variable referring to a company's sales for the month of January could be called "jansales." The variable name "rt545LL" could be used to refer to the same data, but it is more difficult to understand and less meaningful. Variables used in the same part of a program can't have the same name, or one variable may overwrite the other. This is known as name collision.
3. Data types These are the four main simple, or primitive, data types. There are other data types that represent more complex data. Data types limit which kind of data a variable can hold and determine which kinds of operations can be performed on it.
Char Integers Real Boolean
Char The char data type represents single characters, such as "m." A variable made up of a number of characters is called a string. The variable employee_name might contain the string "John Smith." Integers
1109
Integers are among the data types that most computers support. There are different sizes of integers available, including short integers and long integers. For example, in Java, the short data type holds an integer up to 8 bits in length and the long data type holds one of up to 64 bits in length. Integers are positive and negative whole numbers, for example -2 and 117954. Real Real data are numbers with a fractional part, for example 8.65 and -0.03. They also include numbers that have no fractional part but are expressed as a whole number with a decimal point, such as 4.0 or -1.0. Boolean Boolean values are logical values and can be either true or false. Booleans indicate true with a value of 1 and they indicate false with a value of 0. Some programming languages define subsets of the basic types of data. In Pascal, for example, long, short, and unsigned are variations of the basic integer type. Some languages use different names for the same type of data. Numbers with a decimal point, for example, are called "real" in Pascal and "floats" in C. You have now learnt about data types. Some programming languages define subsets of the basic types of data. In Pascal, for example, long, short, and unsigned are variation of the basic integer type. Some languages use different names for the same type of data. Numbers with a decimal point for example are called "real" in Pascal and "floats" in C.
Question Variables that are used in a piece of code need to be declared in a statement at the start of that code before they can be used in expressions. Which of the following do you think must be provided in a declaration statement for a variable? Options: 1. Its scope 2. Its name 3. Its type
1110
4. The number of times it will be used
Answer A variable's name and type must be included in a declaration statement before it is referenced in code statements. Declaration statements determine the variable's name and the type of data it will contain. Each language uses a different syntax for its declaration statements. In Pascal, the var keyword is used to indicate the start of variable declarations. Pascal uses the code var car: integer; to show that a variable car is an integer-type variable. And it uses the code var car: real; to show that a variable rate is a real-type variable.
Note The var keyword does not need to appear next to each variable being declared – it should appear once only at the beginning of the declaration statements. In the following Pascal example, the variables car and rate are declared at the beginning of the program.
program var car: integer; rate:real; begin End The C programming language uses int car; to show that the variable car is an integer. And float rate; is used to show that the variable rate will store floating point numbers.
1111
Note Java declare variables in a similar way, using the syntax datatype variablename; QBASIC doesn't require you to explicitly declare variable types. Instead, you simply initialize a variable using the required data type. So in QBASIC, car=9 to allocates an integer value to the variable car. And the statement rate=-7.32 allocates a real value to the variable rate.
Question Which data type is used to store individual letters? Options: 1. 2. 3. 4.
Boolean Char Integers Real
Answer You use the Char data type to store individual letters, like "a" and "Z". Option 1 is incorrect. Boolean data types are bit fields that store single bits, representing (on, off), (true, false), and so on. In low-level languages you can conserve memory space by using bit-wise arrays, whereas in Java, Boolean types take up 2 bytes (16 bits) in memory. Option 2 is correct. In most modern programming languages, a character value takes up 2 bytes. This type is able to store any character – both printable and non-visual – in the standard ASCII character set. This set represents characters with decimal values in the range 0-255, which include the digits 0-9 and the English alphabet, both lowercase and uppercase. Option 3 is incorrect. Integer types are used to store integral values – positive and negative whole numbers. In Java, for example, an integral type (int) takes up 4 bytes on all platforms. As the byte size is limited to each language, attempting to store too large a value will result in an overflow and data loss. Option 4 is incorrect. Real types are numeric values with a floating point segment. For example, 2.5573 is an example of a real value. Variables types for such values have become standardized as double and float.
1112
Summary Data that is preset and remains the same during data processing is called a constant, whereas variables represent data whose value may change while the program is running. During processing, data is stored in a specific address in the computer's memory. Memory addresses are represented by hexadecimal numbers, or they may be named to make them more memorable. Programming languages have rules that govern how variables and constants can be named. Data is classed according to four main simple types – integers, real numbers, char, and Booleans. Some languages use different names for the same type of data. Variables that are used in a program need to be declared at the start of the program before being referenced in code statements.
1113
Expressions and statements Learning objective
After completing this topic, you should be able to describe the functions of expressions and statements in programming.
1. Introducing expressions and statements An operator is a symbol that represents a specific action that must be performed on data.
Question Operators work with operands. Which of the following do you think is the best definition of an operand? Options: 1. 2. 3. 4.
Anything in a statement that isn't an operator The value that results after an action has been performed The value on which a specific action is being performed The address in the computer's memory where data pertaining to the operator is stored
Answer The values on which an action is being performed are known as operands. In the example expression 2 + 6, the values on either side of the + (plus sign) operator are the operands that are being added. Each operator is represented by a specific symbol.
Question The + operator indicates that two values must be added. See if you can complete the statements to identify which operator is represented by which symbol. Options: 1. * 2. 3. / Targets:
1114
A. The subtraction operator is represented by the _____symbol. B. The multiplication operator is represented by the _____symbol. C. The division operator is represented by the _____symbol.
Answer The - symbol represents the subtraction operator, the * symbol represents the multiplication operator, and the / symbol represents the division operator. An expression is a combination of operators and operands that ascertains a value. For example, in the expression 7 * 2, 7 and 2 are the operands and * is the operator. This expression gives a value of 14. A statement is an instruction in a computer language. Computer programs are made up of many statements. CLS Value = 7 * 2 PRINT value END As statements are executed, the program performs a particular task. Assignment operators are used in statements to instruct programs to assign values to data. When assigning a value to a variable, the variable is always placed on the left-hand side of the assignment operator. Total = sales1 + sales2; Different languages use different assignment operators. BASIC and C, as well as many other languages, use the = (equal to) symbol as the assignment operator. An example of an assignment statement in C is Total = sales1 + sales2; The following pseudocode demonstrates a typical assignment statement. It adds 2 to the present value of the variable num and stores the answer in num. CLS num = 5 num = num + 2 PRINT num END
1115
In both languages, the statement num = num + 2 adds 2 to the present value of the variable num and stores the answer in num. So if the variable num initially has a value of 5, after this statement executes, it will have a value of 7. Pascal uses the : (colon) and = in combination as the assignment operator. The code num := + 2 is an example of an assignment operator in Pascal.
2. Operator Precedence Operators are evaluated in a specific order according to operator precedence.
Question Operator precedence means that certain operators have precedence over others. See if you can put the operators and parentheses in the order in which they are evaluated according to operator precedence.
Options Option
Description
A
Multiplication and division
B
Addition and subtraction
C
Parentheses
Answer Correct ranking Option
Description
C
Parentheses
1116
Correct ranking Option
Description
A
Multiplication and division
B
Addition and subtraction
In the statement y = 7 + 3 * 2 the multiplication operator is executed before the addition operator, according to operator precedence. CLS y = 7 + 3 * 2 PRINT y END In this case, y has a value of 13. If there is more than one operator in an expression with the same precedence, the operators are executed from left to right. For example, in the statement amount = 4 / 2 * 3 the division operator is executed before the multiplication operator. CLS amount = 4 / 2 * 3 PRINT amount END The statement assigns a value of 6 to amount.
Question You can use () (parentheses) in statements. In code, which of the following do you think () are used for?
1117
Options: 1. 2. 3. 4.
As a division operator To group expressions As an addition operator To entirely exclude the rest of the statement from execution
Answer In code, () are used to group expressions. You use ( to indicate the start of the grouped expression and ) to indicate the end. Operators between () are given the highest precedence, and the result is used for further calculations. Terms within parentheses are evaluated according to standard operator precedence.
Question Expressions in () are given highest precedence. In the expression t=3 * (1 + 4) what do you think the value of t is?
CLS t = 3 * (1 + 4) PRINT t END Options: 1. 2. 3. 4.
7 13 15 18
Answer The value of the variable t is 15. In the statement y = 3 * (1+ 9 / 3)
1118
the expression in () is executed first. It equals "4," so y is assigned the value of 12. Relational operators compare two values. The mathematical symbols < (smaller than) and > (greater than) are used as operators in these comparisons.
Question The statement IF p > 5 THEN PRINT "true" compares the value of p with the numeric value 5 using the > operator. What do you think the statement denotes?
CLS p = 4 IF P < 5 THEN PRINT "false" END Options: 1. 2. 3. 4.
If the value of p is greater than 5, then the statement is true If the value of p is smaller than 5, then the statement is true That p is equal to 5 That p is less than or equal to 5
Answer If the value of p is greater than 5, then the statement is true. The expression y < 5 means that if the value of y is less than 5, then the statement is true. CLS y = 6 IF y > 5 THEN PRINT "true" IF y < 5 THEN PRINT "false" END
3. Building statements Certain rules prescribe how to build assignment statements.
1119
Question Select the rule that you think is applicable to building assignment statements. Options: 1. 2. 3. 4.
Statements may contain only operators Statements are executed from left to right Only one assignment operator per statement is permitted The same variable can't appear on both sides of an assignment operand
Answer Statements are executed from left to right. Option 1 is incorrect. Statements can contain as many operators as the programmer wishes to include, but operands are required for operators to work on. Option 2 is correct. In the statement red = 829 the variable red is assigned the value 829. Option 3 is incorrect. Statements such as m = r = 3 are allowed for many programming languages. Option 4 is incorrect. The same variable can appear on both sides of an assignment operand. In the statement a = a + 1, the value of a is incremented by 1. In complex calculations, statements can be broken down into several steps to aid code legibility. For example, the statement total = ( (price * 0.175) + price) * 1.2 may be broken down further to make it easier to read. total = ( (price * 0.175) + price) * 1.2 tax=price*0.175 cost=tax+price total=cost*1.2
Summary An operator represents a specific action that has to be performed on data. Each operator is represented by a specific symbol. The values on which an operator works on are known as operands. An expression is a combination of operators and operands that ascertains a value.
1120
Operators are evaluated in a specific order known as operator precedence. Parentheses take precedence over all other operators and multiplication and division operators take precedence over addition and subtraction operators. If there is more than one operator in an expression with the same precedence, the operators are executed from left to right. Statements are built according to certain rules. Multiple assignment operators are permitted per statement. Statements are executed from left to right.
1121
Building expressions Learning objective
After completing this topic, you should be able to understand the elements that are used in code, recognize different data types, and construct simple expressions.
1. Exercise overview In this exercise, you're required to recognize different data types and convert expressions written in words to expressions written in operators and operands and calculate their answers. This involves the following tasks:
providing appropriate definitions for code elements and recognizing the syntax of different languages evaluating the answer to expressions using operator precedence and converting expressions written in words to expressions written in operators and operands identifying different data types
2. Task 1: Processing data Computer languages use a number of data types and specialized symbols to represent and manipulate the data they process.
Question In data processing, there are a number of data types, symbols, and values that are used to write computer programs. Complete the sentences to define terms. Options: 1. 2. 3. 4.
Operators Constants Variables Operands
Targets: A. represent data that remains the same while the program is running B. represent data that may change while the program is running C. are symbols that represent specific actions that are performed on data
1122
D. are the values or variables on which a specific action is being performed
Answer Data that remains the same while the program is running is represented by constants, data that may change while the program is running is represented by variables, symbols that represent specific actions that are performed on data are operators, and the values or variables on which a specific action is being performed are operands. * and / are examples of the multiplication and division operators, respectively. These symbols are standard across most programming languages. You can group operators using appropriate parentheses., This is sometimes necessary in complex expressions because operators obey order precedence rules. Constants are values that don't change throughout an application's lifetime. Because you don't want these values being inadvertently changed, you define them as being constant at the programming level. For example, the mathematical symbols pi and e have well-defined values, which are invariant. Variables are programmable placeholders for holding character, string, numeric, and boolean values. Typically, you declare, initialize, and process variables, in that order. You can change a variable's value at any point in a program. However, each new value must be of the initial type. For example, you will generate an error by attempting to store "abcd" in an integral type. Operands are the values – variable or constant – used in a processing instruction. For example, in the code total = (first + second) * third, first is added to second, the result is multiplied by third and assigned to the total variable. first, second, and third are all operands.
Question Declaration statements state the variable's name and the type of data it will contain. Many languages use different syntax for declaration statements. Select the declaration statement written in QBASIC from those listed. Options: 1. 2. 3. 4.
item=9 float rate; int car; var car: integer;
1123
Answer QBASIC declares variables to be integers by allocating integer values to them. Option 1 is correct. Most programming languages force you to declare a variable's type before assigning values to it. These are called type-safe languages, which compilers can optimize because they know the type of each variable. Some languages, however, like QBASIC and Clipper, can automatically assign a type at runtime, allowing you to reassign types as well as values. Option 2 is incorrect. In languages like C, C++, and Java, float rate declares a floating point variable, like 10.2342. In this example, the variable must be initialized in C and C++ to avoid random memory values and unpredictable results. In Java, rate is automatically assigned 0.0, if it's a member variable. Option 3 is incorrect. int is an integral type, representing positive and negative whole numbers, like –2 and 634. QBASIC automatically recognizes variable types from the assignment code – you don't have to declare specific types in QBASIC. Option 4 is incorrect. Some languages, like Pascal, use this form of declaration syntax. You are declaring car to be a variable capable of storing whole numbers. Don't forget to initialize variables to default values before processing them. This helps to prevent memory corruptions, which can be difficult to detect and debug.
Question Programming languages articulate variable declarations in different ways. Which of the following assignment statements would be valid in Java? Options: 1. var number=123 2. dim number=123 3. int myNumber=123;
Answer An example of an assignment statement in Java is int number; Option 1 is incorrect. var stands for "variable" and is used in languages like Javascript to declare variables of generic type – variables that can hold any data type. This means that variables can be reassigned at will and you don't have to track their usage – when you are finished with them, you simply forget about them.
1124
Option 2 is incorrect. In Visual Basic and VBScript, you use the dim keyword to declare a variable that can hold random values. This is useful in processing arrays and other memory structures, where data types are anonymous. Generic types like dim allow you to take full advantage of polymorphism. Option 3 is correct. Java borrows much of its syntax from C++ which, in turn, draws from the C language. For example, to declare character, string, and floating types in Java, you use char, String, and float respectively. Note that misusing these keywords will result in compilation errors.
3. Task 2: Examining operator precedence Much computer programming depends on operator precedence, which are rules that govern how the computer reads formulae.
Question In an expression, certain operators have precedence over others. Match each expression with the result it will produce. Options: 1. 2. 3. 4. 5.
7+3*5 7*(3+5) 4*6-4 4*(6-4) 8/4-3+20-4
Targets: A. B. C. D. E.
=8 = 22 = 20 = 56 = 15
Answer The correct results are 8 = 4*(6-4) 22 = 7+3*5 20 = 4*6-4 26 = 7*5+3 15 = 8/4-3+20-4
1125
Multiplication (*) takes precedence over addition, unless you override this precedence using parentheses – (). Here, 5 is multiplied by 3 to give 15. Finally, 15 is added to the 7 to give 22. In this example, parantheses override the normal precedence of multiplication. 5 is added to 3 to give 8, which is multiplied by the 7 to give a final answer of 56. 6 multiplied by 4 gives 24. Subtracting the 4 gives 20. This shows that operator precedence holds, whichever positions the operators occur. In general, operations in parentheses are processed first, from the inside out. This means that the innermost nested parentheses are calculated first, followed by the outer parentheses. Here, 6 minus 4 gives 2, which is multiplied by the 4 to give 8. 8 is divided by 4 to give 2. (2+20) – (4 +3) is then calculated to give a result of 15. Note here, however, that (8/4)-3+20-4 also gives 15, whereas 8/(4-3+20-4) gives 8/17.
Question Conditions or calculations can be written in operators and operands. Convert the expression written in words to an expression written in operators and operands by completing the expressions. Options: 1. 2. 3. 4.
+ * /
Targets: A. B. m_5 C. 12_5 D. 5_7
m_m
Answer The correct answers are Add variable m to five times m is m + m * 5 and Divide 12 by 5 and subtract 7 is 12 / 5 - 7
1126
Note here, that both references to m are merely placeholders – each variable refers to a separate value. One m refers to the original value, while the second represents the original value multiplied by 5. These two values must now be added using the + operator. The specification stipulates that the original value of m is to be multiplied by 5. This is accomplished using the * operator. 12 is divided by 7 before subtraction occurs. In reality, there is no need to specify this because operator precedence will ensure it – multiplication and division assume higher priority than both addition and subtraction. The operation of subtraction occurs last. You can guarantee that this operation is carried out first, by enclosing it in parentheses. You are recommended to use bracketing, to make your code legible to others – not all programmers are comfortable with operator rules and precedence.
4. Task 3: Identifying data types The four main simple types of data are integers, real numbers, char, and Boolean.
Question Integers are a specific subset of positive and negative numbers. Which of the following are integers? Options: 1. 2. 3. 4.
1 -1.5 -1348 5
Answer Integers are positive and negative whole numbers, for example 1, -1348, and 5. Option 1 is correct. Integers are positive or negative whole numbers – that is, non-decimal numbers. For very large whole numbers, programming languages support long types. Longs are 4 bytes in length, whereas int types are 2 bytes. Option 2 is incorrect. You cannot store decimal numbers in an integral type. You can, however, cast a decimal number to an integer, in which case you will lose the decimal portion of the number. You do this in Java, for example, with code like int myInt = (int) 2.34.
1127
Option 3 is correct. -1348 is within the range of integral values, so there is no data loss in storing this as an integer. You should familiarize yourself with the value limits of each data type, rather than relying on compilers to warn you – they don't always. Option 4 is correct. Generally, any integral multiple of an integer is, itself, an integer, allowing for the natural limits of each data type. Thus, trying to store 12 divided by 5 as an integer, will result in either a compiler warning or a runtime error. To avoid this situation, you can use casting.
Question Real numbers are a subset of positive and negative numbers. Select the real numbers from the list. Options: 1. 2. 3. 4.
0.25 4 4.0 -6.378
Answer Numbers with fractional parts and whole numbers expressed with decimal points are known as real numbers. Real numbers include 0.25, 4.0, and -6.378. Option 1 is correct. Real numbers can be positive or negative, and they form a continuous range, about zero. In particular, every number between -1 and 1 is a real number, including -1.0, 1.0, and 0.0. In this sense, the set of integers is a subset of the set of real numbers. Option 2 is incorrect. In programming terms – as distinct from mathematical terms – 4 is treated differently from 4.0 because 4.0 represents a float or a double data type and 4 is a proper integer. Option 3 is correct. When a compiler sees a decimal specified, it knows that the number should be treated as a real number. Memory space is allocated, in this instance, to allow 4.0 to change to 4.12, for example. Integers, like 4, cannot be freely manipulated in this fashion. Option 4 is correct. You can store practically any length decimals as real numbers, for use in engineering and scientific applications. Precision is a function of the chipset. For example, when Pentium 3 first came out, there was a floating point bug that affected precision at the sixty-fourth decimal.
Question A variable may be made up of a number of characters.
1128
What is a variable made up of a number of characters called? Options: 1. 2. 3. 4.
String Operand Operator Float
Answer A variable made up of a number of characters is called a string. Option 1 is correct. In Java, for example, there is a String data type built into the language. The Java designers considered string types to be important enough to make them a native data type. You also have string libraries for C++ and other languages. These libraries facilitate string manipulation. Normally, strings are treated as character arrays. Option 2 is incorrect. An operand is any value acted upon by an operator such as *, /, +, and -. For example, in the operation A+B, both A and B are operands of the addition operation. An operand must comply with rules of the particular operation being processed. For example, a division operation is only allowed where the denominator operand is nonzero. Option 3 is incorrect. Apart from the standard arithmetic operations, programming languages allow for custom operations, such as bitwise manipulation using the OR, XOR, and AND operators. In C++, for example, you can even redefine operators to suit your objects – a feature deliberately excluded in Java's design. Option 4 is incorrect. Floating point numbers – or decimal numbers – are a feature of all modern programming languages. They are described by the float and double data types. While they store numbers rather than characters, in Java there are specially designed values to denote positive and negative infinity – NaN and -NaN, respectively.
Question Booleans are used to test whether an expression is true or false. See if you can complete the statements to identify which value is indicated by what number. Options: 1. true 2. false Targets:
1129
A.
Booleans indicate_with a value of 1. B. Booleans indicate_with a value of 0.
Answer Booleans indicate true with a value of 1, and they indicate false with a value of 0. In C and C++, booleans record true and false values. True has the value 1. Boolean conditions are used to perform code branching, depending on input values. For example, to print out all invoices with numbers between 100 and 200, you might use the code if (invNo >= 100 && invNO <= 200) print(invNo);. The conditional expression evaluates either to true or false (1 or 0). That is, a given invoice number is either in the range or it isn't. In Java, you use the keywords true or false, instead of 1 and 0. Sometimes, you need to use code to test for negative conditions. That is, you are interested in an event set that doesn't satisfy a supplied condition. In these cases, you can use the ! operator to test boolean expressions. For example, to divide by a random variable, you might use the code if (!(d==0) print(n/d);. This code performs a division only if the denominator is not equal to 0. Note that true is equal to !false.
1130
Variables, Constants, and Data Types Learning Objectives
After completing this topic, you should be able to
recognize how to create a variable
recognize the conventions for naming a variable
identify the types of data stored in variables 1. Creating variables At the simplest level, a program is a set of instructions that processes inputs and outputs. Input data can take many forms and can come from various sources. For instance, data can be captured from keyboard or mouse input.
Graphic The diagram of a program shows the input of data – from a keyboard or mouse, for example – that is then processed. The data can be saved to and retrieved from storage. The processing of the data produces output in the form of information. This output can be displayed on a screen or printed on paper. Input data is stored in a computer's memory and is accessible to a program via its memory address. However, memory addresses are represented in hexadecimal format and are very unwieldy for humans to use. Variables solve this problem by assigning user-friendly names to data. A program then performs the hard work by keeping track of each variable in memory. The trade-off for this convenience is reduced processing speed. Every time you want to read a variable's data from memory, a computer has to look up the memory address to access the data. However, some programming languages – like C++ and Assembler – allow you to access data directly using its memory address. Programming languages also support the use of constants, which is data that is set and remains the same while a program runs. One example of a constant could be the mathematical number pi. Creating a variable usually involves three steps: declaring the variable
1131
Naming a variable is known as declaring the variable. All variables have names that you use to access the data they store. The name of a variable should describe the data it will contain, but must also adhere to specific naming conventions. defining the data type, and A data type defines the kind of data a variable can contain, which can include text, special characters, or numbers. Most programming languages require that a variable be assigned a certain data type. This helps ensure that data is stored correctly and prevents incompatible types of data from being used together. initializing the variable The process of assigning data, or a value, to a variable so it can be stored in memory is known as initializing the variable. A variable can typically contain only one piece of data at a time. If you assign another value to it, the new value will replace the existing data. One way around this, however, is to use arrays, which are designed to store a number of variables together under the same name. It's best practice to declare variables at the start of code. However, some programming languages do allow you to declare variables anywhere in code, as long as they're declared before they're used. Each variable must be given a unique name to ensure that the correct data is stored and can be retrieved using that name. Computer memory used to be relatively expensive, which meant that variables were typically given very short names to save on space. Simple variable names like X or Y were commonly used. This made it difficult to remember which variable names represented which values, and you had to go back and check your source code to figure out what a particular variable was used for. Modern variable names, however, can be longer and more descriptive.
Code Dim markupPercentage As Integer = 10 When naming variables, it's important to adhere to three basic naming conventions:
a variable name shouldn't consist of any keywords that are reserved in the programming language you're using
a variable name can't begin with a number, and
a variable name can't contain special characters that are disallowed by the programming language
1132
Keywords have particular code meanings in programming languages and so may not be used as variable or constant names. For example, FOR is a keyword in BASIC and var is a keyword in PASCAL. Neither of these words could be used as constant or variable names in the respective languages. Variable or constant names may not begin with digits or certain characters. For example, the variable name "2ndName" wouldn't be allowed because it begins with a digit. Instead you could name this variable "name2." Certain languages don't allow the use of special characters. BASIC, for example, doesn't allow the use of characters such as the asterisk (*), plus sign (+), or parentheses (()). Using these characters would result in errors. To make variables easier to distinguish, you can name them using strings of words that describe the data they store. For example, if your program needed to calculate sales totals using Value Added Tax, you could combine the words to name a variable "valueAddedTax." Two casing styles commonly used in programming are camel case, and When you string together a name using camel casing, the first letter of the variable name is written in lowercase. The first letter of each subsequent word is written in uppercase. An example is valueAddedTax. Pascal case Pascal casing is similar to camel casing except that the first letter of each word, including the first word, is written in uppercase. An example is ValueAddedTax. Some programming languages like C++ are case sensitive, so it's important to be consistent with capitalization throughout the program. For example in C++, you can use both ValueAddedTax and valueAddedTax as variable names. However, C++ will assume that you're referring to two different variables. The maximum length of a variable name depends on the programming language being used. In PASCAL, for example, the maximum length is 32 characters.
Question Which naming conventions apply to variable names? Options: 1. They can't consist of keywords
1133
2. They can't begin with a number 3. They can't contain special characters 4. They must be at least eight characters long 5. They have to start with a capital letter
Answer Option 1: Correct. Variable names can't be keywords, which have particular code meanings in a programming language and are reserved for performing specific functions. Option 2: Correct. Variable names can't begin with numbers, although they can contain numbers. Option 3: Correct. Variable names can't contain special characters that are disallowed by the programming language you're using. Option 4: Incorrect. There is no minimum limit on the number of characters in a variable name. However, a maximum length restriction may be imposed by the programming language. Option 5: Incorrect. Variable names can start with uppercase or lowercase letters. In languages that are case-sensitive, you need always to use the same capitalization when naming and referring to a particular variable. Correct answer(s): 1. They can't consist of keywords 2. They can't begin with a number 3. They can't contain special characters
2. Data types and values Variables can contain various types of data, ranging from character strings and numbers to combinations of strings and numbers. Data can take the form of numbers A variable of the Integer data type can store whole numbers. You can use different sub-types depending on the size, or length, of the numeric data you need to store. For example, a variable of the Byte data type is 8 bits long and can store numbers from 0 to 255. Another sub-type is also called Integer and is usually declared using int. This stores a larger integer number range than the Byte data type, but less than the Long integer data type, which can store the largest range of integer numbers.
1134
The Real data type stores floating point numbers, which are numbers that have decimal values. There are two Real sub-types – Single Precision and Double Precision. A Single Precision variable requires 4 bytes of storage and a Double Precision variable uses 8 bytes. text, or The String data type is the main data type you'll use for text and can house a virtually unlimited number of characters at a time. It can store letters, special characters, and numbers. It's important to note than even though you can store a number in a String variable, you can't then use this number in a calculation. You'd have to convert the String variable to the Integer or Real data type before doing so. A variable of the Char data type can store only one character at a time. Boolean values The Boolean data type includes two values – such as 0 and 1, or true and false – to represent logical conditions. When you assign a value to a Boolean variable in programming, you typically use the term true or false. Note that if you enclose either value in quotation marks – using "true", for example – it will be interpreted as a literal string. If you do this for a Boolean variable, a program will return an error. The sizes of the numerical data types and the range of numbers they can store depend on the programming language you use. It's advisable to research this before you start writing a program. Some programming languages define subsets of the basic types of data. In PASCAL for example, the Long, Short, and Unsigned data types are variations of the basic Integer data type. Also, some languages use different names for the same types of data. For instance, numbers with a decimal point are of the Real type in PASCAL but are defined as of the Float type in C. Both the Real and Integer data types can be positive or negative. Values without a minus sign are assumed to be positive values. It's important to find the right data type for the data you want to store. This helps ensure that the data is correctly identified and used. It also enables you to be economical with storage space and memory. If you want to store a person's age in a variable, for example, using the Integer sub-type would be unnecessarily large. In this case, the Byte data type would be more efficient. Similarly, if you use a variable of the Byte data type to store a phone number, only the first few digits of the number will be saved and the rest will be discarded. And if you use a variable of the Integer data type to store a real number, the decimal value of the real number will be discarded.
1135
Question Which data types can contain only numerical values? Options: 1. Integer 2. Real 3. Char 4. String
Answer Option 1: Correct. You can store only whole numbers in variables of the Integer data type. Option 2: Correct. You can store real and whole numbers in a variable of the Real data type, but a whole number will have two decimal digits added to its end. Option 3: Incorrect. You can store only ASCII characters in a variable of the Char data type. Option 4: Incorrect. You can store text, special characters, and numbers in a variable of the String data type. Correct answer(s): 1. Integer 2. Real Many programming languages perform an operation called type-checking, which validates data to ensure that the data is compatible with the associated variable's data type. Type-checking returns an error if a program attempts to store data that doesn't match the variables data type, like trying to store a text string in a number variable. To prevent typechecking errors, the programmer writes code to validate input and thus filter out potentially troublesome data. For example, if you've declared a variable that stores a person's age, you should write commands that validate the age number input by the user. You would need to create a function that checks if the input number is a positive number and below or equal to the maximum age humans are generally expected to reach. Failure to program these input checks often lead to type-checking errors. Variables are initialized when values are assigned to them. It's good practice to assign a value to a variable when you declare it, even if this is a zero for a numerical variable or "" for a string.
1136
Note Some programming languages will automatically assign 0 – or "" for a string – if you don't assign a value when declaring a variable. The way that values are assigned to variables differs from one programming language to another. In C and C++, for example, you specify a data type, then the variable name, and then the variable's initial value in parenthesis.
Code int i(0); In Java and JavaScript, you use var followed by the variable name. You then include a colon and specify the data type. Finally you assign an initial value using an equals sign.
Code var i:int = 0;
Note In C, C++, Java, and JavaScript, the end of any line is indicated by a semi-colon (;). In Visual Basic, you use Dim followed by the variable name. You follow this with As and the variables' data type, an equals sign, and then the value you want to assign to the variable.
Code Dim i As Integer = 0 When you assign a string value to a variable, you enclose the text in quotation marks.
Code String FirstName(""); Say you're using C++ to write a program and want to store the name John in a string variable named FirstName. You start by declaring the data type and the variable name, and follow it with the value, in quotation marks and inside parentheses.
Code 1137
String FirstName("John");
Question Which are valid variable declarations in C++, JavaScript, or Visual Basic? Options: 1. Boolean status(true); 2. var status:Boolean = true; 3. Dim status As Boolean = true; 4. Boolean status = "true"; 5. var status:Boolean = "true";
Answer Option 1: Correct. In C++, you declare a variable by specifying its data type, then its name, and then its value in parentheses. Option 2: Correct. In JavaScript, you declare a variable by specifying the var keyword, followed by the name of the variable, a colon, the variable's data type, an equals sign, and finally the value you want to assign to the variable. Option 3: Correct. In Visual Basic, you declare a variable with Dim, followed by the name of the variable, the As operator, the required data type, and an equals sign followed by the initial value of the variable. Option 4: Incorrect. The Boolean data type can accept only true or false as its value. When either of these values is enclosed in quotation marks, it's identified as a string value and can't be stored in the Boolean data type. Option 5: Incorrect. If you use quotation marks while assigning a value, you indicate that the value is a string. However, the Boolean data type doesn't accept strings. It accepts only true or false, without the quotation marks, as values. Correct answer(s): 1. Boolean status(true); 2. var status:Boolean = true; 3. Dim status As Boolean = true;
1138
Summary The data processed by programs is stored in variables or as constants. A constant is declared at the beginning of a program and is a value that remains unchanged, whereas the value of a variable can change during normal program execution. To create a variable, you declare it by naming it, define its data type, and initialize it by assigning it a value. You need to adhere to a number of naming conventions for variables to ensure correct program execution. Programming languages use a number of data types and sub-types to identify which data particular variables can store. It's important to set variables to the correct data types so that values are stored correctly, and for program efficiency. Many programming languages provide type-checking, which raises an error if the wrong data type is assigned to a particular variable. Properly written programs include code to validate input data thus preventing type-checking errors.
1139
Expressions and Statements Learning Objectives
After completing this topic, you should be able to
identify the functions of mathematical and comparison operators
recognize how operators are evaluated 1. Mathematical expressions and operators Expressions and statements form a large part of developed applications. An expression is a combination of operators and operands that determines a value. This example expression shows 22 divided by 7.
Graphic An example is 22 / 7. A statement is an instruction in a computer language that performs a task. Assignment operators are used to instruct the program to assign values to data. In the example, the variable X equals 3.14.
Graphic An example is X = 3.14. You can use an expression with a statement to calculate a value and store it in a variable. When you do this, the variable name is always placed on the left of the operator. The expression is written on the right of the operator. In the example X equals 22 divided by 7, X is the variable and 22 divided by 7 is the expression.
Graphic An example is X = 22 / 7. The simplest operator is the equals sign, or =. It's used to assign values. In this example, the variable variableOne is assigned the value 22. You can assign a numerical or string value, or the result of a mathematical expression, to a variable.
Graphic The example is variableOne = 22.
1140
The term operands refers to everything in a statement that isn't an operator. In this example, variableOne and 7 are operands, whereas = and / are operators.
Graphic The example is result = variableOne / 7. Assignment operators in a program function differently from operators in mathematics. In programming, the compiler returns an error because it will try to assign the value on the right of the operator to the expression on the left. In this example, X multiplied by 2 equals 10.
Graphic An example is X * 2 = 10. To remedy this, the statement is written the other way around with the expression on the right of the assignment operator. In this case, the example is changed to X equals 5 multiplied by 2.
Graphic The example is changed to X = 5 * 2. You can assign a new value to a variable by using it as an operand in the expression and performing an operation on it. In this example, X equals X multiplied by 2. If X has an initial value of 10, the new value of X will be 20 when the statement is executed.
Graphic The example is X = X * 2. The operators you'll use most often are mathematical operators. () Parentheses are used to prioritize expressions within other expressions. The result of an expression in parentheses is used as an operand in the main expression. Operators and terms within parentheses are evaluated according to standard operator precedence. In the example p = (X + 2) / 7, the expression in parentheses, X + 2, is prioritized. The example shown is p = (X + 2) / 7. ^ The caret symbol is the exponentiation operator. It's used to multiply a number exponentially a specified number of times. In the example s = p * r ^ 2, r is the base number and 2 is the
1141
exponent. The example s = p * r ^ 2 is shown. * The asterisk is the multiplication operator, used to multiply one number or variable by another. As in the example, d equals r multiplied by 2. The example d = r * 2 is shown. / The forward slash character is used for division operations using integers or floating point numbers. The result will be rounded to an integer if p is an integer data type, otherwise, the result will be a Real number with a quotient. In the example, p equals X divided by 7. The example is: p = X / 7. \ The backslash character is used for integer division operations. Integer division returns a whole number and any decimal value will be discarded, even if the result is stored in a variable of the Real data type. In the example, q equals the integer value of 22 divided by 7, q has a value of 3 once the statement is executed. The example q = 22 \ 7 is shown. + The plus sign is used for addition operations. In this example the value of X is replaced by the result of the expression X plus 2. If you have an expression like X = 10 + -2, the result will be 8. The statement X = X + 2 is shown. The minus sign is used to subtract one number or variable from another. If you use two characters, like in Y = 22 -- 7, the operation will be changed to addition and Y will be 29. The example is Y = 22 - 7. % A modulo operation divides one number with another and returns the remainder. In the example Z equals Y % 2. if Y is 15, Z will have the value of 0.5 when the statement is executed. The percentage symbol represents a modulo operation in languages such as C#, Java, and Visual Basic. In other languages, the mod command is often used. Two examples are shown – Z = Y % 2 and Z = Y mod 2. Programming languages use particular rules of precedence when there's more than one operator in an expression. Operations will be executed in this order: 1.
expressions in parentheses
2. exponentiation 3. multiplication and division
1142
4. integer division 5. modula, and 6. addition and subtraction Operators that use two different operands to produce a result are called binary operators.
Graphic The example is: int a; int b; int c; a = 10; b = a++; c = --b; The three integer declarations are highlighted. In C++, you can use unary operators, which operate on a single operand. You can use either ++ to increment a value by one, or -- to decrement a value by one. The result of using these operators in statements depends on which side of the operand you place them on.
Graphic The highlighted example is a = 10.
Note C++ was developed from C and gets its name from the ++ operator, which essentially means "one more." In the first example, the unary operator is on the right – so when this expression is executed, b equals 10 and a is increased to 11. This is because the value of b is assigned before the unary operation is performed. If the unary operator is written on the left of the operand, the unary operation is performed before the value is assigned. So in the second example, both b and c will be 9 because the value of b is decreased before it's assigned.
Graphic
1143
The highlighted examples are: b = a++; c = --b; Mathematical operators are used to change numbers but comparison operators are used to compare values. The result of a comparison is returned as a Boolean value – either true or false.
Graphic Example of comparison operators include = or == which means equal to, <> or != =which means not equal to, < which means less than, > which means greater than, <= which means less than or equal to, and >= which means greater than or equal to. Comparison expressions are often used to make decisions on which step a program should perform next. There are a number of comparison operators.
Graphic The example is a = 12, b = 10, and c=10. = or == The equal comparison operator is denoted by one or two = signs. You use it to check whether two values are equal. The single = sign is usually used to assign a value, but in some languages this is also a comparison operator. In Java, JavaScript, and C++, == is distinguished as the equal operator. In this example, the expression will be true. The example is b == c. Both b and c equal 10. <> or != The not equal to operator is represented by the <> or != set of characters, depending on the programming language. You use it to check if one value is not equal to another. In this example the expression will be true. The example is a != c. Variable a = 12 and variable c = 10. < The less than operator is represented by the < sign. You use it to check if the operand on the left of the operator is less than the one on the right. In this example, the expression will be false. The example is a < b. Variable b = 10 and variable a = 12. > The greater than operator is represented by the > sign. You use it to check if the operand on the left of the operator is larger than the one on the right. In this example, the expression will be
1144
true. The example is a > c. Variable a = 12 and variable c = 10. <= The less than or equal to operator is represented by the <= set of characters. You use it to check if the operand on the left of the operator is less than or equal to the one on the right. In this example, the expression will be true. The example is b <= c. Both b and c equal 10. >= The greater than or equal to operator is represented by the >= set of characters. You use it to check if the operand on the left of the operator is greater than or equal to the one on the right. In this example, the expression will be true. The example is a >= b. Variable a = 12 and variable b = 10. You can also use comparison operators to compare strings. Each character corresponds with a numerical value in the ASCII character set used by computers. When you compare two characters, the ASCII or Unicode numerical values of the characters are compared. In the example, "j" is greater than "J".
Graphic The example is "j" > "J". In this example, the ASCII values for the characters are shown. The expression 106 > 74 will return true.
Graphic The examples are "j" > "J" and 106 > 74. When comparing two strings, a program compares each character in one string with the character in the same position in the other string. If the first characters are the same, it moves through the strings one character at a time until a true or false result is achieved. The example 74, 75 > 74, 107 will return false when the expression is executed.
Graphic The examples are "JK" > "Jk" and 74, 75 > 74, 107. Programming languages also use Boolean operators to calculate Boolean values. Because the results of Boolean expressions are either true or false, they are often used with comparison expressions to return the results of the comparisons.
1145
Most programming languages use four main Boolean operators. AND The AND operator compares two Boolean values and returns a single Boolean value. If both values are true, it returns true, but if one or both is false, it returns false. In this example, payment = 550, therefore both comparison expressions will return true, so the result of this Boolean expression will also be true. The example shown on screen is: (payment < 650) AND (payment > 450) OR The OR operator is the opposite of the AND operator and will return true if any of the compared values are true. For a false result, both Boolean values have to be false. In this example, payment = 550, therefore the second comparison expression is true, so the result will also be true. The example is (payment < 450) OR (payment >= 500). XOR The XOR operator, also known as the exclusive or operator, returns a true value if one but not both of the operands is true. So if you compare two true or two false values, the result will be false – but if one value is true, it returns true. In this example, payment = 500, therefore the first expression is false and the second true, so the result will be true. The example is (payment != 500) XOR (payment == 500). NOT The NOT operator changes a Boolean value to its opposite. In this example, payment = 500, therefore the result will be false because the comparison expression is true. The example is NOT (payment < 650). An example in which Boolean operations are used is an automated road toll system where drivers buy credit before using a road. In this example, a car is allowed through with true expression results.
Graphic The example statements are restricted = false; registered = true; credit = false; VIP = true; When a driver approaches, the first evaluation determines whether the car is restricted and so not allowed to enter the toll road. If it's NOT restricted, the program passes to the next evaluation.
1146
Graphic The statement is NOT(restricted). Then if a car is registered AND has available credit, it's allowed to pass. In addition, if credit is false but the car is marked as VIP, the car will be allowed through as result of the OR operation.
Graphic The statement is (registered AND credit) OR VIP. Along with basic mathematical operators, most programming languages have built-in math functions for performing more complex calculations. Functions like square root or logarithm are either incorporated natively or can be added using math libraries. These functions work on the same principles as other programming functions and take numerical values as parameters.
Graphic An example is X = sqrt(360).
Question Match the mathematical and comparison operators with their descriptions. Options: ^
A. B.
\
C.
/
D.
%
E.
!=
F.
<
Targets: 1. Multiplies a number exponentially 2. Divides a number into another and returns a whole number 3. Divides a number into another and returns a real number with a decimal value if the variable has been assigned as Real 4. Computes the remainder of a division operation
1147
5. Compares two values and checks if they aren't equal 6. Compares two values and checks if the first is smaller than the second
Answer You use the caret symbol, or exponentiation operator, to multiply a number exponentially. You use the backslash for integer division. It returns a whole number and discards decimal values. You use the forward slash for division. It returns a real number with a decimal value if the variable has been assigned as Real. You use either the percentage symbol or mod keyword to divide two numbers and return the remainder. You use != or <> for not equal comparison operations. The result is returned as a Boolean value. You use the less than symbol to check whether one value is smaller than another. The result is returned as a Boolean value. Correct answer(s): Target 1 = Option A Target 2 = Option B Target 3 = Option C Target 4 = Option D Target 5 = Option E Target 6 = Option F
2. Operator precedence Operators are evaluated in a specific order according to operator precedence. This means that certain operators have precedence over others when written in an expression. Operators between parentheses are given the highest precedence, and the results are used for further calculations. Terms within parentheses are evaluated according to standard operator precedence. Two common mnemonics can help you remember the order of operator precedence: PEMDAS, and
1148
PEMDAS is an acronym for parenthesis, exponentiation, multiplication, division, addition, and subtraction. BEDMAS BEDMAS is an acronym for brackets, exponentiation, division, multiplication, addition, and subtraction. Integer division and modulo are omitted from this list because these are more obscure operators and not often used in programming. The words "brackets" and "parentheses" are interchangeable and have the same meaning. The order in which multiplication and division, or addition and subtraction occur is also irrelevant, because the results will be the same. If operators in an expression have equal precedence, calculation occurs from left to right. Say you want to buy something from a web store based in another country. You want to calculate the total cost in dollars before buying the item.
Graphic Two expressions are shown - unitCost equals unitPrice plus shipping, and dollarValue equals unitCost multiplied by exchangeRate. These are represented as: unitCost = unitPrice + shipping dollarValue = unitCost * exchangeRate You can use two expressions to do this, but combining them into one expression would be more efficient. If the two expressions are simply combined, however, you won't get an accurate answer because operator precedence dictates that multiplication will occur before addition.
Graphic The expression dollarvalue equals unitPrice plus shipping multiplied by exchange rate. This is represented as dollarValue = unitPrice + shipping * exchangeRate If you add parentheses to the first expression, the cost of shipping the unit will be added to the unit price before the exchange rate is multiplied. This will return the correct answer.
Graphic The expression dollarvalue equals open parenthesis unitPrice plus shipping closing parenthesis multiplied by exchange rate. This is represented as dollarValue = (unitPrice + shipping) * exchangeRate
1149
You can construct complex statements as long as you factor in operator precedence. Say you want to find the exponential result of a base value using a variable exponent. Currently the value of the exponent is 2.
Graphic The expression is exp = 2. When the statement in this example is executed, value will be 100 because the ++ unary operation will occur only after the exponential operation is performed.
Graphic The expression is value = 10^exp++. However, if you include parentheses in the expression, value will be 1000 because the operation inside the parentheses will be performed before the exponentiation operation.
Graphic The expression is value = 10^(exp++). Strings play a major role in computer programming. As with numbers, you can perform addition and subtraction operations on strings. Some programming languages also enable you to search a string for a character or set of characters, and replace or remove them. More complex operations are usually performed using functions, but some operators will also work with strings. Say you want to print a person's name on the screen.
Graphic Two variable values are shown – FirstName = "Emily" and LastName = "Novak". To do this, you add the two variables to form a new string variable, and print this to screen. It's important to remember to add a space between the variables, which you do by using a set of quotation marks surrounding a space.
Graphic
1150
The example statements are person = FirstName + " " + LastName and PrintToScreen person. Alternatively, you can combine the two statements into one print statement.
Graphic The example statement is PrintToScreen FirstName + " " + LastName. You can also add text to an existing string variable using the addition operator.
Graphic The expression Name equals FirstName plus Novak. This expression is represented as Name = FirstName + " Novak".
Question Using standard operator precedence, match each expression with the correct result. Options: A.
X=8-3+7 B.
Y = (34 + 7) * 89
C.
Z=7+7*7
D.
V = 882 / 3^2
Targets: 1. 12 2. 3,649 3. 56 4. 98
Answer In this statement, the - and + operators have equal precedence. So the expression is simply calculated from left to right. In this statement, the expression between parentheses takes precedence. So the result is calculated as 41 multiplied by 89. In this statement, the multiplication operator takes precedence. So the result is calculated as 7 plus 49, which equals 56.
1151
In this statement, the exponentiation operation takes precedence. So 882 is divided by 9 to give the result of 98. Correct answer(s): Target 1 = Option A Target 2 = Option B Target 3 = Option C Target 4 = Option D
Summary Programs typically contain a large number of expressions and it's vital that they're accurate. A number of different types of operators are used to form expressions. Of these, mathematical operators are the most common. A number of mathematical functions are also generally available. Comparison operators are used to compare two values and return a Boolean value. In programming, Boolean operators are most often used for decision making. It's important to know the rules of operator precedence when creating expressions. Two common mnemonics for remembering these rules are PEMDAS and BEDMAS. In some languages, you can manipulate strings in ways similar to those you use to manipulate numerical values.
1152
Building Expressions Learning Objectives
After completing this topic, you should be able to
recognize how variables, operators, and values are used to construct expressions
recognize how to build expressions Exercise overview In this exercise, you're required to demonstrate a basic understanding of variables and expressions in programming. This involves the following tasks:
recognizing how to declare variables, and
recognizing how to build expressions
Declaring variables Question Which term describes data that is preset and remains unchanged during processing? Options: 1. Constant 2. Variable 3. Operator
Answer Option 1: Correct. A constant is a value that is declared in source code and remains unchanged during processing. Option 2: Incorrect. A variable is a placeholder for data that is declared in the source code. The value it stores can change during program execution – the variable may receive a value from user input or as the result of an expression. Option 3: Incorrect. An operator is a character that represents a mathematical or logical operation to be performed on data. Correct answer(s):
1153
1. Constant
Question Which variable names follow the standard naming conventions? Options: 1. secondNumber 2. SecondNumber 3. 2ndNumber 4. second() 5. *Numbers
Answer Option 1: Correct. It's acceptable to write a variable name with an initial word in all lowercase and subsequent words beginning with an initial uppercase letter. This is known as camel case. The name in this example also doesn't violate any other conventions for variable names. Option 2: Correct. It's acceptable to include an initial capital for each word in a variable name. This is known as Pascal case. The name in this example also doesn't violate any other conventions for variable names. Option 3: Incorrect. Variables may not start with a number. You can add the number after the name if required. Option 4: Incorrect. Parentheses, or brackets, aren't allowed in variable names. Option 5: Incorrect. The asterisk is a special character – it's used as an operator in programming languages and so can't be included in the names of variables. Correct answer(s): 1. secondNumber 2. SecondNumber
Question Match each data example with its data type. Options: A.
true
1154
B.
254
C.
a
D.
17.2553
Targets: 1. Boolean 2. Byte 3. Char 4. Real
Answer The Boolean data type can represent true or false values. It stores 1 or 0 to reflect the value. The Byte data type can store up to eight bits of data and a number in the range from zero to 255. You can also save the number 254 in a variable of the Integer type, but good programming conventions dictate that the size of the data type should be as closely matched to the value as possible. The Char data type can store a single character at a time. You can also use the String data type for this value – but if the value of this variable will always be only one character, using Char is the better solution. The Real data type can store real numbers that have decimal values. Whole numbers can also be stored, but will be written with a decimal value of .0. Correct answer(s): Target 1 = Option A Target 2 = Option B Target 3 = Option C Target 4 = Option D
Question When you name a variable, what are you actually doing? Options: 1. Declaring the variable 2. Initializing the variable
1155
3. Validating the data type
Answer Option 1: Correct. When you declare a variable, you give the variable a name and specify its data type. Option 2: Incorrect. A variable is initialized when it's given a value. Some programming languages will assign 0, or "" for strings, if you don't assign a value explicitly. Option 3: Incorrect. Data type validation is done automatically by a programming language when data is entered. Correct answer(s): 1. Declaring the variable
Building expressions Question Using standard operator precedence, match each expression with the correct result. Options: A.
2+3*2 B.
(2 + 3) * 2
C.
2+3^2
D.
(2 + 3) / 2
E.
(2 + 3) \ 2
F.
2+3/2
Targets: 1. 8 2. 10 3. 11 4. 2.5 5. 2 6. 3.5
Answer
1156
In this statement, the multiplication operator takes precedence. So the result is calculated as 2 plus 6. In this statement, the expression between the parentheses takes precedence. So the result is calculated as 5 multiplied by 2. In this statement, the exponentiation operator takes precedence. So the result is calculated as 2 plus 9. In this statement, the expression between the parentheses takes precedence. So the result is calculated as 5 divided by 2. In this statement, the expression between the parentheses takes precedence. The backslash character is used for integer division operations and returns the integer value of 5 divided by 2, which equals 2. In this statement, the division operator takes precedence. So the result is calculated as 2 plus 1.5. Correct answer(s): Target 1 = Option A Target 2 = Option B Target 3 = Option C Target 4 = Option D Target 5 = Option E Target 6 = Option F
Question Identify the order in which the components of expressions are evaluated, from first to last. Options: A.
Expressions in parentheses B.
Exponentiation
C.
Multiplication and division
D.
Addition and subtraction
Answer Correct answer(s):
1157
Expressions in parentheses is ranked the first place. Parentheses take precedence over all other operators, so the expressions they contain will always be evaluated first. Exponentiation is ranked the second place. Operations involving exponentiation are performed after any expressions in parentheses have been evaluated, but before operations involving multiplication or division. Multiplication and division is ranked the third place. Multiplication and division are performed after exponentiation but before addition and subtraction. Addition and subtraction is ranked the fourth place. Addition and subtraction are at the lowest level of precedence and are performed last. Data types and naming conventions for variables have been detailed and mathematical operators have been used to build expressions.
1158
Arrays Learning Objectives
After completing this topic, you should be able to
recognize how to use arrays in programs
recognize how to create arrays in BASIC, C++, and Revolution 1. Using arrays All computer programs need to store data and variables are the most common way to do this. However, variables are limited to storing only one piece of data at a time. For example, if you want to store an employee's first name, last name, and telephone number, you'd have to create three variables – which isn't very efficient. Structures and arrays were created as two ways to store several pieces of related data in one place. Structures provide a way to group several variables, and can be described as variables that can contain several other variables. Arrays offer a better solution. They can be described as "super" variables to which you can add as many pieces of related data as you want. For example, if you want a program to store the names of all 20 employees in a company, you can create one array to store them. When you create an array, you need to define a variable name When you create an array, you have to give it a name. It's best to give arrays descriptive names so you know what kind of data they store. the array size, and The advantage of arrays is that they can each hold many pieces of data. Each piece is stored in an element of the array. When you create an array, you have to specify how many elements it will contain. This is known as the size of the array. the type of data you want to store All the elements in an array must have the same data type. You specify the data type when you create the array, although there are commands that let you convert to a different data type later. If an array is for storing names, for example, you should specify the data type as String. Other data types you can set are Integer and Boolean. Storing numbers is, however, not limited to the
1159
Integer data type. For example, if you want to store names and telephone numbers in one array, you can set the data type as String and store the numbers as strings. It's important to plan before you start creating an array so you can specify its size. You set the size by specifying the bounds of an array. The lower bound defines the number of the first array element and the upper bound defines the number of the last array element. Depending on which program language you're using, the default lower bound can be either zero or one. It's important to know what the default lower bound is so that you can specify enough elements for your data. Programs such as BASIC, Java, and C – and any language derived from the C language – always define the lower bound of an array as zero. These are called zero-based arrays. To specify the number of an element, you have to start counting at zero. Other programs use one-based arrays. To set the size of a one-based array, you have to start counting at one. Some programs, such as Pascal, enable you to define both the lower and upper bounds of an array. The advantage of this is that the lower bound doesn't have to start at zero or one, but can start at any number you want. This is useful when you want to link each element to a meaningful number. For example, if your company uses employee numbers and you're creating an array to store employee names, you can set the lower bound to correspond to the first employee number. Most arrays are one-dimensional and store data in the form of a list. So they are defined only in terms of their length. You can, however, create multi-dimensional arrays. These are more flexible and enable you to store more complex data. The most common multi-dimensional array is a two-dimensional array, which can be represented as a grid with either two columns or two rows. You can create arrays that are two-, four-, or even nine-dimensional. But the more dimensions arrays have, the more complex they are. With too many dimensions, working with arrays can be rather confusing.
Question Identify what you need to specify when creating an array. Options: 1. A name for the array
1160
2. The size of the array 3. The type of data the array will store 4. How the data will be entered 5. The language used for data in the array
Answer Option 1: Correct. When you create an array, you need to give it a name – preferably a name that describes the data it will store. Option 2: Correct. When you create an array, you have to specify how many elements it should contain. Option 3: Correct. All the elements in an array must have the same data type, which you need to specify when you create the array. Option 4: Incorrect. You don't have to consider how the data will be entered when creating an array. You need to give an array its name and specify its size and data type. Option 5: Incorrect. You don't need to specify language settings when creating an array, although you do need to consider what type of data the array will contain so you can specify the right data type. Correct answer(s): 1. A name for the array 2. The size of the array 3. The type of data the array will store
2. BASIC, C++, and Revolution Although the general method for creating an array is the same no matter which programming language you use, some of the details vary. To create arrays in LibertyBASIC, you use the DIM keyword.
Code DIM You specify a name for the array, without using spaces or special characters.
Code
1161
DIM EmployeeNames In LibertyBASIC, an array can accept either strings or numbers. To define the data type as String, you need to add a dollar sign – $ – at the end of the array name. If you don't add the dollar sign, the data type will be defined as Integer by default.
Code DIM EmployeeNames$ To define the size of the array, you provide the upper bound, which defines the number of the last array element in brackets. Arrays in LibertyBASIC are zero-based so you start counting from zero to number the elements. In the example, the number four indicates that the array has five elements. The first element is zero, the second is one, and so on.
Code DIM EmployeeNames$(4) To create an array in REALbasic, you also use the DIM keyword.
Code DIM You specify a name for the array and specify the size of the array by providing the number for the last element in brackets after the name. Arrays are zero-based in REALbasic.
Code DIM EmployeeNames(4) To specify the data type of the array, you use a declaration with the DIM command. After the name and size, you simply state As and then provide the data type, such as Integer or String.
Code DIM EmployeeNames(4) As String To create an array in C++, you start by specifying the data type. You provide the name of the data type, such as String or Integer.
1162
Code String Next you provide the array name.
Code String EmployeeNames You then specify the array size. C++ is different from other languages in that you specify the number of elements in the array rather than the upper bound. Also, in C++ you specify the size in square brackets instead of in parentheses. In the example, the number five indicates that the array should contain five elements.
Code String EmployeeNames[5]
Note Arrays in C++ are zero-based so the index numbers start from zero. The way you create arrays in Revolution is different from in the other programming languages. You don't have to create an array in advance – by declaring its name, size, and data type – before you can start adding data. Revolution enables you to add data as you create arrays using the put command.
Code put Another difference is that items in a Revolution array aren't identified by an index number. Instead Revolution identifies array items by a key, which can be any string or unique number. In the example, the array named EmployeeNames is created. It stores the name Jonathan Gold and associates it with the key Sales.
Code put Jonathan Gold into EmployeeNames["Sales"]
1163
Creating two-dimensional arrays in LibertyBASIC and REALbasic is similar to creating onedimensional arrays. You also use the DIM keyword, specifying the array name and data type.
Code DIM EmployeeNames$() DIM EmployeeNames() As String Specifying the size is different. For a two-dimensional array, you use two integers to indicate the array's size. The first specifies the upper bound of the elements in the horizontal dimension – row – of the grid and the second specifies the upper bound of the elements in the vertical dimension – column. Because LibertyBASIC and REALbasic are zero-based arrays, you start counting from zero.
Code DIM EmployeeNames$(2,1) DIM EmployeeNames(2,1) As String The first example here is in LibertyBASIC, and the second is in REALbasic. Both create a twodimensional array named EmployeeNames that's designed to hold six string elements. This array could be represented as a grid with three rows and two columns.
Code DIM EmployeeNames$(2,1) DIM EmployeeNames(2,1) As String Creating two-dimensional arrays in C++ is similar to creating two-dimensional arrays in LibertyBASIC and REALbasic. However, you need to supply two values to specify the number of elements in both dimensions of the grid. Each of these values is specified in its own set of square brackets. This example shows the code for creating a two-dimensional array, which has three rows and two columns when represented as a grid.
Code String EmployeeNames[3][2]
1164
Using Revolution, you can enter data as you create two-dimensional arrays, just as you can when creating one-dimensional arrays.
Code put put put put put put
"Jonathan Gold" into EmployeeNames[0,0] "Alison Baker" into NameArray[0,1] "Eleanor Davis" into NameArray[1,0] "Luke Foster" into NameArray[1,1] "Werner Horowitz" into NameArray[2,0] "Maggie Chung" into NameArray[2,1] The difference is that where elements in one-dimensional arrays are identified with a key, you have to define each element's place on the grid when creating two-dimensional arrays. Revolution is a zero-based language. This means, for example, that the first element in both the horizontal and vertical dimensions of the grid will be numbered (0,0). This example shows a two-dimensional array called EmployeeNames that contains six name elements.
Question Match the programming languages to corresponding examples of the statements used to create an array. One of the languages doesn't match to a statement. Options: A.
LibertyBASIC
B.
REALbasic
C.
C++
D.
Revolution
Targets: 1. DIM ClassArray$(10) 2. string ClassArray[11] 3. put Pilates into ClassArray("P")
Answer Using LibertyBASIC, you create an array of the String data type by specifying the DIM keyword, an array name, a dollar sign – which identifies the String data type, and the size of the array in parentheses.
1165
Using C++, you start by specifying the data type and then specify the number of elements in square brackets. In Revolution, you can add data as you create arrays, and you identify array items by keys rather than index numbers. Correct answer(s): Target 1 = Option A Target 2 = Option C Target 3 = Option D
3. Implementing arrays You assign values to the elements of an array in the same way that you assign values to variables. In ANSI C, you can initialize the contents of an array when you declare the array. ANSI – short for the American National Standards Institute – published a standard for use with C to make C programs more portable. The declaration in the example is used to initialize an array of vowels.
Code char vowel [5] = {'a', 'e', 'i', 'o', 'u' }; When you want to initialize the array of vowels in BASIC or Pascal, you have to assign a value to each element separately.
Code vowel[1]="a"..vowel[5]="u" To insert an element into an array that is already filled, you can copy and move all the elements forward one place to the right of the insert position. So the very last element in the array falls away. If you move all the elements back one place, to the left of the insert position, the very first element in the array falls away.
1166
This may seem easy if you have a small array with only a few elements. But for a large array with thousands of elements, this could be an extremely cumbersome job, especially if you have to do it regularly. Another way to insert an element in an array is to overwrite the current array element with the new element. Consider an array of four integers – {19,20,21,22} – called year. You want to insert 0 between 20 and 21 – at position 2, assuming the index numbers in the array start at zero. The C code inserts 0 at position 2 in the array. The program starts at the end of the array and copies the element to the left of the current position onto the element at the current position. This process repeats until the insert position – which is 2 – is reached. At this point, the array contains the values {19,20,20,21}.
Code for (index = 3; index >= 2; index--) { year [index] = year [index - 1]; } The last statement in the code assigns the value 0 to the third element in the array. Now the array contains the integers {19,20,0,21}.
Code year [2] = 0; Now you want to delete 20 from the array {19,20,0,21}. You can do so by overwriting 20 with a null value. After the code has been executed, the array contains the four values {19, ,0,21}.
Code year [2] = 0; To empty an array in BASIC, you can use the command ERASE. So this code replaces all the integers in the array called "year" with null values.
Code ERASE year
1167
In C and Pascal, you use a loop to empty an array.
Code for (index = 0; index <= 4; index++) { vowel [index] = ""; }
Question Identify the correct methods for inserting an element into an array that is already filled. Options: 1. Move all the elements up or down one place 2. Re-create the array with the new element 3. Overwrite a current array element with a new element 4. Have the array determine which item to replace
Answer Option 1: Correct. If you move the elements up or down one place, the first or last element falls away to make space for the new element. Option 2: Incorrect. It's inefficient to re-create an array simply to replace an element. You can either move the elements up or down, or overwrite the element you want to replace. Option 3: Correct. You can insert an element in an array by overwriting the current array element with the new element. Option 4: Incorrect. An array can't determine which item to replace. You have to overwrite a specified location in the array with a new value. Correct answer(s): 1. Move all the elements up or down one place 3. Overwrite a current array element with a new element
Summary Variables are the most common way for programs to store data but they are limited to storing only one piece of data at a time. An array can store multiple pieces of related data in one place. When you create an array, you give it a name and specify its size and data type.
1168
The basic method of creating an array is common to all programming languages, although the details may differ. Some of the common programming languages are BASIC, C++, and Revolution. Once you've created an array, you need to implement it by assigning values to it. You assign values to the elements of an array in the same way that you assign values to variables.
1169
Procedures and Functions Learning Objectives
After completing this topic, you should be able to
recognize called procedures in code examples
recognize the difference between local and global variables 1. Using procedures in programs Most modern programs are long and complex. So it's hard to organize all the different tasks a program must perform. To make this process a little easier, it's a good idea to divide a program into major tasks and subtasks.
Code Enter_competitors() WHILE more records GET current_date age = current_date - date_of_birth SET valid_age to true IF age <18 or age >50 THEN PRINT "You must be between 18 and 50 to enter" valid_age = false ENDIF IF valid_age = true THEN GET entrant_name ADD entrant_name to entrant_list PRINT receipt ENDIF ENDWHILE END Top-down design – or functional programming – involves identifying the tasks and subtasks in a program. In this process, each program is broken down into modules, which are separate elements of functionality. Each of these modules, or procedures, should be used to perform a single, specific task. And all the modules should work together to achieve the desired program output. Procedures can be regarded as programs within programs. They are also known as functions or subroutines. They can be part of a main program file or part of a separate file.
1170
Functions and subroutines normally work in exactly the same way, with a few exceptions. In some programming languages – like Visual Basic – functions need to return a value but subroutines don't. The programmer decides where it's logical to create procedures in software. However, it's very important that the overall program structure, as set out in the planning phase of the software development process, is maintained. When creating a procedure or function, you begin by deciding what task it should perform. You also need to decide whether the procedure must return a value to the main program. Then you can give the procedure or function a meaningful name that reflects the task it performs. It's considered good form to begin with a verb followed by an object. For example, a procedure that prints labels could be named "Print_labels." Procedure names are followed by parentheses, so the full procedure would be Print_labels(). Consider writing a program to calculate the total cost of your grocery bill and to print the average cost of each item. You could write all the code in one programming block, as in this example. However, as a program gets larger, it becomes more difficult to work with.
Code Process_grocery_bill() FOR I=1 TO no_of_items PROMPT FOR item_cost GET item_cost total = total + item_cost END FOR Average = total/no_of_items PRINT average END A more efficient approach is to create procedures for each of the tasks that has to be performed. In this case, the first procedure accepts the cost of each item and calculates the total cost of the bill. The second procedure calculates the average cost of the items you've purchased.
Graphic The name of the first procedure is Get_amounts() and the name of the second procedure is Calculate_and_print_average().
Code 1171
Get_amounts() FOR I=1 TO no_of_items PROMPT FOR item_cost GET item_cost total = total + item_cost END FOR END Calculate_and_print_average() Average = total/no_of_items PRINT average END
The main body of the program now simply includes calls to the two procedures.
Code Process_grocery_bill() Get_amounts() Calculate_and_print_average() END The key benefits of creating procedures are that it enables you to keep a main program small and nimble If you use procedures to perform the main functions of a program, the main body of the program will usually consist largely of function calls. It will be small and so run efficiently. create a modular program Each procedure is responsible for a specific task. It contains only the statements that allow it to perform that task. This makes debugging and maintenance of a program easier because it's easier to isolate a problem in a single module than in a large block of code. re-use components, and Procedures can be reused in other programs or applications. You can store procedures in a repository and retrieve them as they're needed. make a program easier to understand Using procedures makes a program much easier to read and understand, because the program can then consist mostly of calls to these procedures – which should have meaningful names that describe the tasks they perform. It's also much easier to locate a procedure for a program than to look for particular lines of code
1172
within all the source code. Because the code for each procedure is separate from other procedures, it's also easier to maintain. When you use procedures in your programming, you should aim to ensure that the different procedures are as loosely coupled as possible. Coupling refers to the dependencies among the procedures in a program. With tight coupling, many procedures are dependent on others to function well. A loose coupling indicates that each procedure can perform well on its own, without relying heavily on other procedures. When procedures are very tightly coupled, a failure in one procedure could cause an entire program to fail. When procedures are loosely coupled, this is unlikely to occur.
Question What are some benefits of using procedures in programming? Options: 1. It lets you create modular programs that are easier to maintain 2. It keeps a main program small and nimble 3. It makes a program easier to understand 4. It enables you to create reusable components 5. It ensures that all code is included in the main body of a program 6. It ensures that values are always returned to a main program
Answer Option 1: Correct. Procedures break the program up into smaller sections, or modules. Each task in a program can then be easily isolated and fixed if there are errors. Option 2: Correct. The main program becomes simpler to maintain because it doesn't contain large chunks of code. Instead it will consist mainly of calls to procedures. Option 3: Correct. If you give procedures meaningful names, anyone who looks at the main program will have a clear picture of what the program does. Option 4: Correct. You can store procedures you've created for use in other programs. Option 5: Incorrect. The main goal of using procedures in programming is to create a simpler main program, which will generally include only calls to procedures – rather than large chunks of code.
1173
Option 6: Incorrect. Procedures don't always need to return values to a main program. Correct answer(s): 1. It lets you create modular programs that are easier to maintain 2. It keeps a main program small and nimble 3. It makes a program easier to understand 4. It enables you to create reusable components
2. Called procedures A program executes each procedure as it's required. A procedure can be called multiple times from a single program. It can also be called from multiple locations in a program, and even from within other procedures.
Code Enter_competitors() WHILE more records Calculate_age(age) Validate_age(age, valid_age) IF valid_age = true THEN Add_entrant() ENDIF ENDWHILE END The flow of execution, or controlling logic, in a program is called the mainline, or main program loop.
Code Enter_competitors() WHILE more records Calculate_age(age) Validate_age(age, valid_age) IF valid_age = true THEN Add_entrant() ENDIF ENDWHILE END To call a procedure, the programmer uses the procedure name as a command. In this example, the highlighted lines of code will cause the specified procedures to be executed.
1174
Graphic The first highlighted line is Get_amounts() and the second line is Calculate_and_print_average().
Code Process_grocery_bill() Get_amounts() Calculate_and_print_average() END Get_amounts() The logic used depends on the type of programming, which can be either procedural programming, or In procedural programming, programs have a mainline procedure that ties other procedures together and provides master control over them. Applications are structured in terms of the actions the program must carry out and the procedures used to implement those actions. object-oriented programming In object-oriented programming, or OOP, the mainline is the starting point for a program. Examples of OOP languages are Java and C++. OOP applications comprise numerous interacting objects, each with their own data and functions. The data in an object is encapsulated. In Java, the main method is always executed first. Similarly, the main function is always executed first in C++. Consider writing a program that adds users' names to a list of competition entrants and prints a receipt for each entrant. The mainline of the program is Enter_competitors().
Code Enter_competitors() WHILE more records Calculate_age(age) Validate_age(age, valid_age) IF valid_age = true THEN Add_entrant() ENDIF
1175
ENDWHILE END When the program runs, it calls three procedures.
Graphic The subprocedures listed are Calculate_age ( age ), Validate_age ( age, valid_age ), and Add_entrant ().
Code Enter_competitors() WHILE more records Calculate_age(age) Validate_age(age, valid_age) IF valid_age = true THEN Add_entrant() ENDIF ENDWHILE END The Calculate_age() procedure is called first. So control of the program passes to this procedure. That means that the main program halts at that point and jumps to the procedure to execute its instructions.
Code Calculate_age (entrant_name, date_of_birth) GET current_date age = current_date - date_of_birth END When the Calculate_age() procedure is completed, control is transferred back to the main program. The next program instruction is then executed, In this case, it's a call to the Validate_age() procedure.
Code Validate_age(entrant_name.age) SET valid_age to true IF age <18 or age >50 THEN PRINT "You must be between 18 and 50 to enter" valid_age = false
1176
ENDIF END After this procedure has executed, control returns to the mainline. A condition is tested and, if it evaluates to true, the Add_entrant() procedure is called.
Code Enter_competitors() WHILE more records Calculate_age(age) Validate_age(age, valid_age) IF valid_age = true THEN Add_entrant() ENDIF ENDWHILE END The Add_entrant() procedure completes the entry process and prints the receipt for the competitor.
Code Add_entrant (entrant_name, date_of_birth) GET entrant_name ADD entrant_name to entrant_list PRINT receipt END
Question You're writing a program that checks the availability of theater tickets requested by clients. If the tickets are available, you want the program to calculate their cost and print the results. Which are the called procedures in this program? Code Process_ticket_request() SET more_records to yes DOWHILE more_records get_details(no_of_tickets, section) check_availability(no_of_tickets, section, available) IF available = true THEN calculate_cost(no_of_tickets, section,
1177
price) print_ticket(no_of_tickets, section, price) ENDIF ENDDO Options: 1. get_details 2. check_availability 3. calculate_cost 4. print_ticket 5. Process_ticket_request 6. more_records
Answer Option 1: Correct. get_details is a called procedure for checking how many tickets a person requires. Option 2: Correct. check_availability is a called procedure for checking if tickets are still available. Option 3: Correct. calculate_cost is a called procedure for determining the cost of the tickets. Option 4: Correct. print_ticket is a called procedure for printing the tickets that have been booked. Option 5: Incorrect. This is the mainline of the program, rather than a called procedure. Option 6: Incorrect. more_records is a variable rather than a procedure. Correct answer(s): 1. get_details 2. check_availability 3. calculate_cost 4. print_ticket
3. Local and global variables Constants in a program are values that are specified and remain the same for the entire time that the program is running.
1178
Variables hold values that can change while the program is running. This can be due to user input or results generated during processing. Each variable used in a program has a given scope, which controls when and where the variable can be used. There are two types of variables:
Code Process_grocery_bill() PROMPT FOR store_name GET store_name Get_amounts() END Get_amounts() FOR I=1 TO no_of_items PRINT store_name PROMPT FOR item_cost GET item_cost total = total + item_cost END FOR END global, and Global variables are available to procedures throughout a program, and so have a global scope. They can be used more than once, and they can be created at any point in a main program. In this case, store_name is a global variable. local Local variables are used only within a procedure and have local scope only. They aren't visible to or usable by procedures in the rest of the program. If you try to access a local variable outside of its specific function, you'll get an error. In this example, total is a local variable. It can be used only within the Get_amounts()procedure. A disadvantage of global variables is the potential problem of side effects. Side effects occur when one procedure alters a global variable or makes other changes to its environment. If the altered global variable is used by another procedure, the result returned by that procedure will change. This is undesirable when you want it always to return the same result.
Code
1179
Process_grocery_bill() PROMPT FOR store_name GET store_name Get_amounts() END Get_amounts() FOR I=1 TO no_of_items PRINT store_name PROMPT FOR item_cost GET item_cost total = total + item_cost END FOR END Side effects can cause confusion because they make it hard to identify which procedures are changing variables. This can make maintaining and debugging code very difficult.
Code Process_grocery_bill() PROMPT FOR store_name GET store_name Get_amounts() END Get_amounts() FOR I=1 TO no_of_items PRINT store_name PROMPT FOR item_cost GET item_cost total = total + item_cost END FOR END One way of dealing with side effects is to use local variables whenever possible in procedures.
Code Process_grocery_bill() PROMPT FOR store_name GET store_name Get_amounts() END Get_amounts()
1180
FOR I=1 TO no_of_items PRINT store_name PROMPT FOR item_cost GET item_cost total = total + item_cost END FOR END So the advantage of using local variables is that you won't have the problem of incorrect values being used in different sections of a program. Consider this example. The loop inside the function is supposed to loop ten times using the variable i. In this instance, i is a local variable. When the loop executes, it will start at zero and end when i is equal to 9.
Code display() i=0 WHILE (i < 10) println ("i = ", i) i=i+1 ENDWHILE END Here the code has been modified slightly – i is now a global variable, which has a value of 5. When i is referenced in the procedure, it will have a value of 5 rather than zero.
Code Program_main() i=5 display(i) END display(i) WHILE (i < 10) println ("i = ", i) i=i+1 ENDWHILE END When the loop executes, the value of i will change according to the processing of the loop and may cause the rest of the program to use a new value for i.
1181
Once data has been processed in a procedure, it may need to be passed to another part of the program. A parameter is any variable or constant that is passed between parts of a program. In many programming languages, including C and Java, parameter names are placed in parentheses after a procedure name. The set of parameters for a procedure is referred to as a parameter list. In this example, the Java println method prints a string that is passed to it as a parameter.
Code println(String x) It's very important that the parameters in a parameter list match in both a main program that calls a procedure and in the procedure itself. The parameters in each case must be of the same type. The number of parameters has to be the same, and they have to be in the same order – based on the order in which they're needed for processing.
Code Process_ticket_request() SET more_records to yes DOWHILE more_records get_details(no_of_tickets, section) check_availability(no_of_tickets, section, available) In this code sample, the procedure is being called with three parameters, no_of_tickets, section, and available.
Code Process_ticket_request() SET more_records to yes DOWHILE more_records get_details(no_of_tickets, section) check_availability(no_of_tickets, section, available) The actual procedure uses the same three parameters in the same order.
Code
1182
Check_availability(no_of_tickets, section, available) IF no_tickets <= section_seats_left THEN available = true section_seats_left = section_seats_left no_of_tickets ELSE available = false ENDIF END Parameters don't process and change data. Instead they provide a way to control procedures. The procedures themselves access the specified data and modify it according to the instructions it contains.
Code Process_ticket_request() SET more_records to yes DOWHILE more_records get_details(no_of_tickets, section) check_availability(no_of_tickets, section, available) IF available = true THEN calculate_cost(no_of_tickets, section, price) print_ticket(no_of_tickets, section, price) ENDIF ENDDO END Passing parameters to a procedure ensures that the same procedure can be used many times with different values. The values of the parameters passed to the procedure can simply be changed. This is a better method than creating a new procedure each time it's necessary to process a new value.
Graphic The parameters that will be passed to the get_details() procedure are no_of_tickets and section.
Code Process_ticket_request() SET more_records to yes DOWHILE more_records get_details(no_of_tickets, section) check_availability(no_of_tickets, section, available) IF available = true THEN
1183
calculate_cost(no_of_tickets, section, price) print_ticket(no_of_tickets, section, price) ENDIF ENDDO END Parameters are passed from a calling procedure to a called procedure, and returned from a called procedure to a calling procedure. In this example, Process_ticket_request() is the calling procedure and get_details() is the called procedure.
Code Process_ticket_request() SET more_records to yes DOWHILE more_records get_details(no_of_tickets, section) check_availability(no_of_tickets, section, available) IF available = true THEN calculate_cost(no_of_tickets, section, price) print_ticket(no_of_tickets, section, price) ENDIF ENDDO END
Question Match each variable type to its characteristics. Each type may match to more than one characteristic. Options: A. B.
Local
Global
Targets: 1. Used within a procedure 2. Not visible to or usable by other procedures 3. Available throughout a program 4. Accessible to a variety of procedures 5. Occur in a number of places in a program
Answer
1184
A local variable is used only within the procedure in which it was created. You need to use global variables to allow access from any procedure. A local variable can't be seen or accessed from any procedure except the procedure in which you create it. A global variable is created in the main program and can be used at any point. A global variable can be re-used by different procedures. This makes it unnecessary to create the variable each time it's needed. Global variables can be declared at any point in a main program and referenced in the main program or in any procedure. Correct answer(s): Target 1 = Option A Target 2 = Option A Target 3 = Option B Target 4 = Option B Target 5 = Option B
Summary Top-down design divides a program into major tasks and subtasks. In this process, each program is broken down into modules, or separate, workable sections. Modules are further divided into procedures, each of which addresses a separate task. In many programming languages, the flow of execution of a program is controlled by a procedure called the mainline, or main loop. The mainline controls execution by calling procedures as they're required. Once a called procedure has executed, control passes back to the mainline. Variables used in a program have a given scope – either local or global. Side effects occur when a procedure alters a global variable or other parts of its environment. Parameters are variables or constants passed between parts of a program. Passing parameters to a procedure ensures that the same procedure can be used many times with different values.
1185
Using Arrays and Procedures Learning Objectives
After completing this topic, you should be able to
use arrays in programs
use procedures in programs Exercise overview In this exercise, you're required to recognize how to use arrays and procedures in programming. This involves the following tasks:
using arrays in programs, and
using procedures in programs
Using arrays in programs Question You're using LibertyBASIC and want to create an array that contains 21 elements. The data you want to store is test scores, so you have to give the array the Integer data type. You decide to name the array "TestScores." Identify the correct array declaration. Options: 1. DIM TestScores$(20) 2. DIM TestScores(20) 3. DIM TestScores(21) 4. DIM TestScores(20) As Integer
Answer Option 1: Incorrect. The dollar sign specifies the data type as String. The correct data type is Integer. Option 2: Correct. In LibertyBASIC, you create an array by specifying the DIM keyword, the array name, and the array size in parentheses. To specify the size, you identify the required upper bound – which is 20 in this case because LibertyBASIC uses zero-based arrays.
1186
Option 3: Incorrect. LibertyBASIC is a zero-based array so the index number of the twenty-first element should be identified as 20. Option 4: Incorrect. You use a declaration with the DIM keyword to specify the data type of the array in REALbasic rather than in LibertyBASIC . Correct answer(s): 2. DIM TestScores(20)
Question You're using C++ and want to create an array that contains 21 elements. The data you want to store is the names of test subjects, so the array must be of the String data type. You decide to name the array "SubjectNames." Identify the correct array declaration. Options: 1. String SubjectNames[21] 2. SubjectNames$[20] 3. String SubjectNames[20] 4. String SubjectNames(21)
Answer Option 1: Correct. To create an array in C++, you specify the data type, then the array name, and finally the size in square brackets. To indicate the size, you supply the number of elements. Option 2: Incorrect. In C++, you specify the data type by providing the name of the data type. You use a dollar sign to specify the String data type in LibertyBASIC. Also, array size in C++ isn't indicated by the highest index number but by the number of elements. Option 3: Incorrect. The array size in C++ isn't indicated by the highest index number but by the number of elements. Option 4: Incorrect. In C++, the size of the array is indicated in square brackets rather than parentheses. Correct answer(s): 1. String SubjectNames[21]
1187
Question You're using REALbasic and want to create a two-dimensional array that contains eight elements, in a grid with four rows and two columns. The required data type is String, and you've decided to name the array "Doctors." Identify the correct array declaration. Options: 1. Dim Doctors(1,3) as string 2. Dim Doctors(3,1) as string 3. Dim Doctors(2,4) as string 4. Dim Doctors[1][3] as string
Answer Option 1: Incorrect. You use the DIM keyword with a declaration at the end to specify the data type. You specify the array name and provide two numbers for the size. The first is the horizontal upper bound, for rows, and the second is the vertical upper bound, for columns. Option 2: Correct. When you specify the size of a two-dimensional array, the first number indicates the horizontal upper bound – for rows – and the second number indicates the vertical upper bound, for columns. Option 3: Incorrect. REALbasic uses zero-based arrays so you provide index numbers to specify the array size. Option 4: Incorrect. You'd provide the size of each dimension separately in square brackets in C++, rather than in REALbasic. Correct answer(s): 2. Dim Doctors(3,1) as string
Using procedures in programs Question What happens when a program calls a procedure? Options: 1. Control passes to the called procedure, which executes and then returns control to the calling procedure
1188
2. Control passes to the called procedure, which loops repeatedly until the main program signals that it should halt 3. Control passes to the called procedure after all the calling procedure's instructions are executed
Answer Option 1: Correct. When a procedure is called, the calling procedure transfers control to the called procedure. The called procedure executes and then transfers control back to the calling procedure. The called procedure may or may not return a value to the calling procedure. Option 2: Incorrect. When a procedure is called, the calling procedure passes control to the called procedure, which completes its execution. Then control is passed back to the calling procedure. Option 3: Incorrect. When a procedure is called, the calling procedure immediately jumps to the called procedure. Control is passed back to the calling procedure once the called procedure completes its execution. Correct answer(s): 1. Control passes to the called procedure, which executes and then returns control to the calling procedure
Question This is an example of the main body of a program. Which are the procedures being called in this example? Code Enter_competitors() WHILE more records Calculate_age(age) Validate_age(age, valid_age) IF Valid_age = true THEN Add_entrant() Print_tags() PRINT "Age is:", Valid_age ENDIF ENDWHILE END Options: 1. Enter_competitors 2. Validate_age 3. Calculate_age
1189
4. Add_entrant 5. Print_tags 6. Valid_age
Answer Option 1: Incorrect. Enter_competitors() is the mainline of the program, rather than a called procedure. Option 2: Correct. Validate_age() is a called procedure. Option 3: Correct. Calculate_age() is a called procedure. Option 4: Correct. Add_entrant() is a called procedure. Option 5: Correct. Print_tags() is a called procedure. Option 6: Incorrect. Valid_age is a variable name, rather than a called procedure. Correct answer(s): 2. Validate_age 3. Calculate_age 4. Add_entrant 5. Print_tags
Question In the main body of the program, you need to insert a procedure call to the Print_ticket() procedure. Which procedure call do you use? The procedure to be called is: Print_ticket (no_of_tickets, section , price) PRINT "This is your ticket to enter the theater" PRINT no_of_seats, section , price END Code Process_ticket_request() SET more_records to yes DOWHILE more_records
1190
Get_details(no_of_tickets, section) Check_availability(no_of_tickets, section, available) IF available = true THEN Calculate_cost(no_of_tickets, section, price) INSERT THE MISSING CODE ENDIF ENDDO END Print_ticket(no_of_tickets, section , price) PRINT "This is your ticket to enter the theater" PRINT no_of_seats, section , price END Options: 1. Print_ticket(no_of_tickets, section, price) 2. Print_ticket( ) 3. Print_ticket(section, price, no_of_tickets) 4. Print_ticket(no_of_tickets, section)
Answer Option 1: Correct. You need to specify the parameters being used in the correct sequence when you call a procedure. Option 2: Incorrect. You need to specify the parameters within the parentheses of the procedure call. Option 3: Incorrect. You need to specify the parameters in your procedure call in the same order as in the procedure itself. Option 4: Incorrect. You need to specify the same number of parameters in your procedure call as the procedure is expecting. Correct answer(s): 1. Print_ticket(no_of_tickets, section, price)
Question You want to access a value at multiple points in your program. Which program element should you use?
1191
Options: 1. Local variable 2. Global variable 3. Procedure
Answer Option 1: Incorrect. A local variable can be accessed only in the procedure in which it's created. Option 2: Correct. A global variable can be accessed at any point in a program. It's created in the main body of the program so that all procedures can access it. Option 3: Incorrect. A procedure is used to perform a specific task. It's not used to pass values. Correct answer(s): 2. Global variable You have answered questions about using arrays and procedures in programming.
1192
Software Engineering concepts Analyzing Requirements Using Models SkillBriefs Use Case Modeling Learn how to analyze user requirements by creating usage models. Usage Modeling Techniques Discover the techniques used to create usage models. Entity Relationship Diagrams Learn how to create entity relationship diagrams. Data and Behavior Modeling Techniques Discover the techniques used to create data and behavior models. Class Diagrams Discover how class diagrams are used in data and behavior modeling. Solution Development Methodologies Learn about solution development methodologies. Business Rules Discover how business rules help business analysts model a solution. Data Flow Diagrams Learn how to create data flow diagrams. Process and Flow Modeling Techniques Discover the techniques used to create process and flow models. Activity Diagrams Learn how to use activity diagrams as a modeling technique.
1193
SkillBrief
Use Case Modeling Business analysts effectively analyze user requirements for software projects by creating usage models. Usage models are the analysis techniques of choice because they focus on describing requirements from the user's perspective; if the user's requirements are not fulfilled, the project cannot succeed.
Popular usage models Typically, more than one usage model is used to analyze or discover requirements during business analysis on a project. Three usage models are most often used during business analysis:
User stories are the most informal of the three models. User stories are written by the intended end users of the system and drive development based on user needs for features, function, and behavior. User stories are used when there will be a close relationship between end users and developers.
Use case descriptions are written descriptions of how a user interacts with the solution being modeled to achieve a goal. They provide a structured approach to requirement analysis. This structured approach can help ensure the necessary information is gathered about each requirement.
Use case diagrams are probably the most common and important usage model because they provide a comprehensive, graphical depiction of the problem domain. Use case diagrams do not stand alone; they must be supported by either user stories or use case descriptions.
User stories User stories are written descriptions of functionality requirements. Written by end users, they describe how and what the system must do to allow users to successfully accomplish their goals. Because user stories are written by the intended users of the solution they place increased ownership on the end users, they help achieve agreement on the features that are most important to users, and they help prioritize the attention features should receive during development. User story development is a collaborative process that begins with the business analyst working with end users to identify key features. As each need is identified by the user, a story is written to describe the need. A user story has five key elements:
A story card is used to record a user story – a user requirement – and story cards are maintained throughout solution development.
The story card includes a brief, high-level description of the requirement. Written by the end user, it contains only enough information to allow developers to accurately estimate the effort required to implement the requirement.
1194
The estimate tells what development resources will be needed to code the feature and pass an acceptance test.
The priority is set by the user and expresses the importance of the requirement described by the user story relative to all other user stories.
A unique identifier is assigned to each user story so it can be tracked throughout development.
The business analyst will return to the user to gather more detailed user task information when the development team is ready to implement the user story. There are standards or guidelines for how the additional information will be gathered. A big advantage of user stories is that they facilitate just-in-time development. Having developers and end users working more closely can speed development time and reduces the need for detailed documentation. However, user stories are not the best technique to use on projects that must conform to regulatory guidelines or projects that require documentation.
Use case descriptions The information required to develop use case descriptions is elicited from project stakeholders and the intended end users of the solution or system. The process for developing use case descriptions involves these five steps: 1. Before use cases can be created, the business analyst must first identify which user goals to expand into use cases. Business analysts use an agreed-upon list of stakeholders and a set of user profiles to determine which stakeholders (actors) will interact directly with the solution to achieve which goals. These goals can now be expanded into use cases. 2. Pre-conditions – conditions that must be true or things that must have already occurred before the use case can begin – must be identified and documented. 3. The business analyst will then define the basic flow of the use case. The basic flow is described by the user and defines the typical, simplest path to successful completion of the use case. 4. The business analyst must then work with end users to define all possible alternate and exception flows. Alternate flows define different but also successful scenarios. Exception flows define circumstances that lead to abandonment of the goal represented by the use case. 5. Post-conditions must be identified and documented. For successfully completed use cases, the post-conditions will describe conditions that must be true when the use case is complete. Post-conditions on failure describe the conditions that must be true when a use case completes unsuccessfully in abandonment of the goal. Use case descriptions, often referred to simply as use cases, are written descriptions of how a user - a person or system external to the system being modeled - interacts with the system to achieve a goal. Use case descriptions combine the "who" (actors), the "what" (behavioral requirements), and the "how" (events and conditions) with the "why" (use case goals) to clarify scope and provide a high-level understanding of the problem to be solved or the goal to be accomplished.
1195
While the detail and the format of the documentation used to express use cases will vary depending on the project, some elements are mandatory for all use case descriptions.
The use case must be given a name that uniquely identifies it within the project and should describe the goal the use case is meant to satisfy.
In use case modeling, an actor is any person, external computer system, or event that interacts with the solution through a use case. Actors should also be given unique names that describe the role they play in interactions with the system.
Pre-conditions are facts that are assumed to be true when the use case begins.
Post-conditions are facts that must be true when the use case is complete.
The flow of events describes the steps the actor and the system take during the execution of the use case. The use case description breaks the flow into a basic flow and alternate flows. The basic flow describes the simplest, most efficient path to successfully complete the use case and achieve the goal it represents. Alternate flows describe logic and error handling. If the actor can still achieve the goal of the use case, it is defined as an alternate. If the actor cannot achieve the goal of the use case, the use case is abandoned and is defined as an exception.
Some strengths of the use case description technique are its ability to determine scope and communicate behavioral goals, and to describe basic and alternative ways a use case can be executed. Each of the ways a use case can play out is known as a scenario. Use case descriptions are able to combine the who, what, how and why of use case goals and describe the dynamics of a solution. Because this technique focuses on requirements from a user's perspective, it is not the best technique to describe the functional requirements of systems with limited end-user interaction. Also, it is not the best technique to use to analyze projects that are data intensive.
Use case diagrams A use case diagram is a graphical depiction of the problem domain, including system boundaries, use cases, and actors. The use case diagram is used during requirements analysis to show the problem and gain stakeholder agreement on the scope of the project. Business analysts can begin the process of use case diagram creation in one of two ways. A business analyst can work from an agreed upon list of actors and completed use case descriptions and then employ the use case diagram to show the problem domain or she can begin modeling a use case diagram as a way to discover actors and use cases. A use case diagram employs certain key elements to visually depict the use case and show the problem or goal to be solved or achieved. Three key elements are represented in the use case diagram using symbols or shapes.
An actor is represented with a stick figure. If the actor is a system or an event, a rectangle may be used to represent it.
An oval is used to represent a use case.
1196
A rectangle is used to represent a boundary. A boundary is used to define the scope of the system being modeled. Boundaries may also be used to convey or highlight important information such as phases of system development or a grouping of related functions. The use of boundaries is optional.
Actor relationships include associations and generalizations. The associations that exist between actors and use cases are represented with a solid line and indicate that the actor supplies information to the use case, receives information as a result of the use case, or initiates the use case. The associations between actors and use cases are nondirectional; meaning they do not imply a process flow. A generalization relationship between two actors indicates that the two actors perform similar roles in the use case. A solid line with a filled arrowhead at one end represents a generalization relationship between actors in a use case diagram. The filled arrowhead points to the primary actor. Relationships between two use cases include associations and generalizations. The two associations, extend and include, are represented by a dashed line with an open arrowhead at one end. In an include association, the arrow points to the including use case, and in an extend association, it points to the base use case. The stereotype "include" or "extend" is added to the connecting arrow to identify the association. Each association has a different impact on the base use case:
The logic in the extend use case may be required by the base use case to complete a task. An extend use case may be invoked by the base use case at any time during its execution and can even execute parallel to the base use case, without impacting the base use cases logic.
The logic in the include use case is required by the base use case to complete a task. Include associations can exist between multiple use cases that require the same business logic. An include use case is invoked by another use case at a specific point during the business flow.
The generalization relationship indicates that the two use cases are similar; that one is like the other. The inheriting use case has similar logic but not exactly the same logic of the base use case. The inheriting use case contains steps that have to be rewritten to support its ability to achieve the specific user goal. A line with a filled arrowhead at one end represents a generalization relationship between two use cases in a use case diagram. The filled arrowhead points to the base use case.
Analyzing use cases As with the other models, the business analyst will choose the usage modeling technique that best suits the project being modeled or the use case being analyzed. Regardless of the models used, use case analysis will generally involve an analysis method that involves these six steps: 1. identify actors 2. identify use cases 3. create use case diagrams
1197
4. describe context 5. describe basic flow 6. describe alternate and exception flows Most projects benefit from the structure provided by use case descriptions and the effectiveness of a use case diagram. Because this combination of usage models is often used during business analysis, it is important to understand how this approach fits within the six-step analysis method. Step one, identify actors, is done early in the project. This is accomplished through using the information gathered during interviews with stakeholders or taken from previously developed user profiles. Identifying actors can help determine project scope and help focus requirements interviews. An actor is any person, external computer system, or event that interacts with the system through a use case. Step two, identify use cases, is done with actors. During interviews with each group of actors, as defined by user profiles, the business analyst must find out about three types of use cases:
Tasks are the goals an actor accomplishes through interaction with the system; each task is a system use case.
Events are anything to which the system must respond. Each response is a use case.
Automated requests originate from other systems. Each request is a use case.
Step three is to create use case diagrams. The business analyst can begin by adding the actors and the use cases to the diagram. More information is needed to describe the relationships between the use case diagram elements. The remaining steps will be driven by the creation of the use case diagram. In step four, describe context, the business analyst returns to the stakeholders to get more details about the use cases - the context information. Context includes information about actors, pre-conditions, and post-conditions. These details are gathered as part of use case description creation and could have been done during initial interviews. If use case descriptions are being used to support the use case diagram this step will have already been completed. Steps five and six may also have been completed during the creation of use case descriptions. Step five, describe the basic flow, is also done with stakeholders. Here the focus is on the typical success scenario. The business analyst asks the stakeholder to describe the typical success scenario and documents it in the use case description. Step six, describe alternate and exception flows, deals with scenarios other than the basic flow. Stakeholders are asked to describe possible variations to the basic flow. Alternate flows still lead to success, but if exception flows lead to the abandonment of the use case goal, the use case ends in failure. Each flow is documented in the use case description. Detailed information about each use case and the possible scenarios – basic, alternate, and exception flows – is documented in the use case descriptions. Much of the detail about context is not added to the use case diagram because it would complicate the diagram and reduce its effectiveness as a clear and accessible communication tool.
1198
The most popular usage models are user stories, use case descriptions, and use case diagrams. Essentially, user stories define the problem from the user's perspective, use case descriptions describe the problem, and use case diagrams graphically depict the problem. Often, these models are combined to provide the business analyst and the project team with an understanding of the problem domain. For instance, user stories and use case diagrams may be used to analyze and communicate user requirements on an in-house project or extreme programming environment, where the project can succeed and will even benefit from the less structured approach provided by user stories. Alternatively, use case descriptions and use case diagrams may be used together on projects that demand a structured and more detailed approach to requirements analysis.
Usage Modeling Techniques Usage models are analysis techniques used to describe how users – a person or system external to the system being modeled – interact with the system or solution to fulfill requirements and achieve goals. Various usage models are likely to be used together to model and analyze requirements for a project. When deciding which usage models to employ, you will need to focus on which models will work together to provide the information you need, rather than what type of project they are best suited for use on. What distinguishes usage models from other requirements analysis models is their focus on the user. Usage models provide business analysts with valuable information about the solution or system from the user's perspective. Usage models are typically used to
describe how users interact with a system or solution to fulfill requirements
describe the system or solution from the user's perspective
describe system or solution features visible to the user
Usage models describe only what is visible to external users during their interaction with the system. Nothing else within the solution scope is modeled; not system components or processes.
Usage model types The usage models most commonly used during business analysis are
prototypes
user interface designs
user profiles
1199
user stories
use case descriptions
use case diagrams
Prototypes A prototype can be developed for products or software to represent how the thing being created will work or behave when it is complete. A product prototype consists of a physical, tangible model of the product. A software prototype may be a series of hand, or digitally, drawn user interfaces approximating what the system will look like or how it will behave when complete. A software prototype may also evolve into a functioning, coded software component. When prototyping is used to model user interaction with a system, the intended end users of the solution use the prototype and then provide feedback on it. This gives the users a chance to provide valuable feedback, especially if their requirements have not been met. A business analyst is likely to use a prototype to reduce project risk when working in an unfamiliar business domain or when end-user needs are difficult to understand. Prototyping is usually performed for features of the solution that present the highest risk and not for the entire solution. High-risk features are features that are critically important to the success of the solution; failure to meet them will negatively impact the project or even lead to project failure. Risk may also be prioritized based on a feature's value to the end user or by the degree of difficulty in understanding the feature. Business analysts use prototypes to
gain a visual understanding of how an end user interacts with a system
gain end-user input about whether or not the software solution meets their requirements
capture end-user input on how to improve the software solution
demonstrate technical feasibility
gain stakeholder consensus on hard to understand requirements
Storyboards are often used during the early stages of prototype development. Storyboards provide early design feedback from intended end users of the user interface. This feedback is incorporated into the solution design, improving usability and ultimately reducing project risk. Storyboards are an efficient and effective way to present and gather design input without the expense of developing a software prototype with working code. Each storyboard must include a screen shot of the feature or screen intended for development. Storyboarding can be used whenever appropriate, such as during end-user consultation on usability or features.
User interface designs User interface designs are written descriptions or models that describe end-user preferences for interface usability. End users are given the opportunity to express their preferences for system usability – how they want to navigate specific system features, achieve their goals, or complete work tasks. Involving
1200
end users early in the design process helps to make sure the system will meet user requirements because user preferences are designed into the solution from the beginning. User interface design is an appropriate technique to use when usage will vary by type of user, when the system is interface intense, or when the user type or market is unfamiliar to the project team. Business analysts use user interface designs to
focus on system usage
gain stakeholder agreement on user goals
gain understanding of how the system can be designed to better help users achieve their goals
reveal different usages from different user types
The level of detail and the format of the documentation used to express user interface design will depend on the specific needs of the stakeholders and the project team. However, all user interfaces must
include user profiles or user type documentation that provide information about the end users that will interact with the system
include a list of unclear system requirements prioritized for further discussion and clarification
comply with company standards, thereby ensuring that the output of the documentation will be useful during design and development
User profiles User profiles are written descriptions of a system's end users. User profiles are used to help ensure that solutions provide positive and effective user experiences. When reengineering projects, the goal of user profiles is to improve end-user interactions. User profiles enable analysts to identify, study, and model both the current and future end users of the system. During user profile analysis, information is gathered about end users and then they are categorized into types. To effectively exploit user profiles, business analysts need to know when they are the appropriate technique to use and how they are typically used.
User profiles are the appropriate technique to use when the project team, including the business analyst, is unfamiliar or inexperienced with the problem domain area. User profiles are also a good choice when there are a variety of user types with different user requirements.
User profiles are typically used to check the analysis provided by other techniques, to document requirements for end user types, and to identify user workflow and user task improvements.
The level of detail and the format of the documentation used to express user profiles will depend on the specific needs of the project. However all user profiles must include information on user types, user type attributes, elicitations, and revised user types.
1201
User stories User stories are written descriptions of a system's functionality requirements, as described by users. User stories express what it is that end users need the system to be capable of in order to support them in achieving their goals. This technique places increased ownership for the discovery of requirements on the end user. User stories are used to
identify key features
reach stakeholder agreement on the key features and functions that must be included in the system and their priority
determine estimates of the time it will take to code each feature
User stories are the appropriate technique to use to document requirements when the system being developed requires iterative, incremental, extreme programming (XP). User stories can be used to support use case diagrams, providing information about user expectations for functionality. The level of detail and the format of the documentation used to express user stories will differ from project to project; however, all user story documentation must include a story card and a description, and should include an estimate, priority, and a unique identifier.
Use case descriptions Use case descriptions (use cases) are written descriptions of how a user - a person or system external to the system being modeled - interacts with the solution to achieve a goal. The goal represents a system requirement. Use case descriptions are created through combining the information provided by user profiles and a list of stakeholder goals. Use cases are a good choice when the solution requires an understanding of who does what, and the dynamic behavior of a solution from the user's perspective. Use cases are used to
gain stakeholder agreement on expected system behavior
communicate the proposed functionality, and therefore the scope, of the system
describe how end users interact with the solution to achieve a goal
identify technical or complex requirements that require prototypes to reduce project risk
perform feasibility analysis
provide detail for other usage models
1202
The detail and the format of the documentation used to express use cases will depend on the project. However all use cases must have a unique name and include information on actors (users), preconditions, flow of events, and post-conditions.
Use case diagrams A use case diagram is a graphical depiction of the solution domain, including system boundaries, use cases, and actors. Use case diagrams are used when the business analyst wants to show how actors (users) interact with use cases and the relationships that exist between users and use cases or between use cases. The information depicted is taken from use case descriptions and user stories. Alternatively, use case diagrams can be used to discover actors and use cases. Use case diagrams can also depict the solution boundaries. During business analysis, use case diagrams are used to
express the requirements documented in use cases or user stories
build an understanding of the problem domain and the components within the scope of the domain
get agreement on the scope of the project
Usage models show how systems are used by end users. Usage models used during business analysis include prototypes, user interface designs, user profiles, user stories, use case descriptions, and use case diagrams. These models are grouped together as usage models because common to them is the ability to describe solutions from a user's perspective.
Usage Modeling Techniques Usage models are analysis techniques used to describe how users – a person or system external to the system being modeled – interact with the system or solution to fulfill requirements and achieve goals. Various usage models are likely to be used together to model and analyze requirements for a project. When deciding which usage models to employ, you will need to focus on which models will work together to provide the information you need, rather than what type of project they are best suited for use on. What distinguishes usage models from other requirements analysis models is their focus on the user. Usage models provide business analysts with valuable information about the solution or system from the user's perspective. Usage models are typically used to
describe how users interact with a system or solution to fulfill requirements
describe the system or solution from the user's perspective
1203
describe system or solution features visible to the user
Usage models describe only what is visible to external users during their interaction with the system. Nothing else within the solution scope is modeled; not system components or processes.
Usage model types The usage models most commonly used during business analysis are
prototypes
user interface designs
user profiles
user stories
use case descriptions
use case diagrams
Prototypes A prototype can be developed for products or software to represent how the thing being created will work or behave when it is complete. A product prototype consists of a physical, tangible model of the product. A software prototype may be a series of hand, or digitally, drawn user interfaces approximating what the system will look like or how it will behave when complete. A software prototype may also evolve into a functioning, coded software component. When prototyping is used to model user interaction with a system, the intended end users of the solution use the prototype and then provide feedback on it. This gives the users a chance to provide valuable feedback, especially if their requirements have not been met. A business analyst is likely to use a prototype to reduce project risk when working in an unfamiliar business domain or when end-user needs are difficult to understand. Prototyping is usually performed for features of the solution that present the highest risk and not for the entire solution. High-risk features are features that are critically important to the success of the solution; failure to meet them will negatively impact the project or even lead to project failure. Risk may also be prioritized based on a feature's value to the end user or by the degree of difficulty in understanding the feature. Business analysts use prototypes to
gain a visual understanding of how an end user interacts with a system
gain end-user input about whether or not the software solution meets their requirements
capture end-user input on how to improve the software solution
demonstrate technical feasibility
gain stakeholder consensus on hard to understand requirements
1204
Storyboards are often used during the early stages of prototype development. Storyboards provide early design feedback from intended end users of the user interface. This feedback is incorporated into the solution design, improving usability and ultimately reducing project risk. Storyboards are an efficient and effective way to present and gather design input without the expense of developing a software prototype with working code. Each storyboard must include a screen shot of the feature or screen intended for development. Storyboarding can be used whenever appropriate, such as during end-user consultation on usability or features.
User interface designs User interface designs are written descriptions or models that describe end-user preferences for interface usability. End users are given the opportunity to express their preferences for system usability – how they want to navigate specific system features, achieve their goals, or complete work tasks. Involving end users early in the design process helps to make sure the system will meet user requirements because user preferences are designed into the solution from the beginning. User interface design is an appropriate technique to use when usage will vary by type of user, when the system is interface intense, or when the user type or market is unfamiliar to the project team. Business analysts use user interface designs to
focus on system usage
gain stakeholder agreement on user goals
gain understanding of how the system can be designed to better help users achieve their goals
reveal different usages from different user types
The level of detail and the format of the documentation used to express user interface design will depend on the specific needs of the stakeholders and the project team. However, all user interfaces must
include user profiles or user type documentation that provide information about the end users that will interact with the system
include a list of unclear system requirements prioritized for further discussion and clarification
comply with company standards, thereby ensuring that the output of the documentation will be useful during design and development
User profiles User profiles are written descriptions of a system's end users. User profiles are used to help ensure that solutions provide positive and effective user experiences. When reengineering projects, the goal of user profiles is to improve end-user interactions. User profiles enable analysts to identify, study, and model both the current and future end users of the system. During user profile analysis, information is gathered about end users and then they are categorized into types.
1205
To effectively exploit user profiles, business analysts need to know when they are the appropriate technique to use and how they are typically used.
User profiles are the appropriate technique to use when the project team, including the business analyst, is unfamiliar or inexperienced with the problem domain area. User profiles are also a good choice when there are a variety of user types with different user requirements.
User profiles are typically used to check the analysis provided by other techniques, to document requirements for end user types, and to identify user workflow and user task improvements.
The level of detail and the format of the documentation used to express user profiles will depend on the specific needs of the project. However all user profiles must include information on user types, user type attributes, elicitations, and revised user types.
User stories User stories are written descriptions of a system's functionality requirements, as described by users. User stories express what it is that end users need the system to be capable of in order to support them in achieving their goals. This technique places increased ownership for the discovery of requirements on the end user. User stories are used to
identify key features
reach stakeholder agreement on the key features and functions that must be included in the system and their priority
determine estimates of the time it will take to code each feature
User stories are the appropriate technique to use to document requirements when the system being developed requires iterative, incremental, extreme programming (XP). User stories can be used to support use case diagrams, providing information about user expectations for functionality. The level of detail and the format of the documentation used to express user stories will differ from project to project; however, all user story documentation must include a story card and a description, and should include an estimate, priority, and a unique identifier.
Use case descriptions Use case descriptions (use cases) are written descriptions of how a user - a person or system external to the system being modeled - interacts with the solution to achieve a goal. The goal represents a system requirement. Use case descriptions are created through combining the information provided by user profiles and a list of stakeholder goals. Use cases are a good choice when the solution requires an understanding of who does what, and the dynamic behavior of a solution from the user's perspective.
1206
Use cases are used to
gain stakeholder agreement on expected system behavior
communicate the proposed functionality, and therefore the scope, of the system
describe how end users interact with the solution to achieve a goal
identify technical or complex requirements that require prototypes to reduce project risk
perform feasibility analysis
provide detail for other usage models
The detail and the format of the documentation used to express use cases will depend on the project. However all use cases must have a unique name and include information on actors (users), preconditions, flow of events, and post-conditions.
Use case diagrams A use case diagram is a graphical depiction of the solution domain, including system boundaries, use cases, and actors. Use case diagrams are used when the business analyst wants to show how actors (users) interact with use cases and the relationships that exist between users and use cases or between use cases. The information depicted is taken from use case descriptions and user stories. Alternatively, use case diagrams can be used to discover actors and use cases. Use case diagrams can also depict the solution boundaries. During business analysis, use case diagrams are used to
express the requirements documented in use cases or user stories
build an understanding of the problem domain and the components within the scope of the domain
get agreement on the scope of the project
Usage models show how systems are used by end users. Usage models used during business analysis include prototypes, user interface designs, user profiles, user stories, use case descriptions, and use case diagrams. These models are grouped together as usage models because common to them is the ability to describe solutions from a user's perspective.
Data and Behavior Modeling Techniques To ensure that you have the best requirements for a system, you need a clear understanding of what objects, data, and relationships exist in the current or target system. Data and behavior modeling provides you with a snapshot that covers these three areas, so that you know what direction to take and what to focus on when implementing a solution.
1207
Data and behavior modeling provides a static model – or a single moment in time – of the current or target system or of some aspect of that system. These models describe system objects within the confines of a project's scope. This description includes information recorded about these objects, their relationships, and the business rules that govern them. Thus this form of modeling provides a framework for analyzing requirements for system objects. Data and behavior modeling does not provide an overview of a system's behavior over time, nor does it reflect how users outside the system scope may interact with the system. Data and behavior modeling is useful in situations where you need to understand the data and how it fits together to create the system. Although this model outlines relationships between these data entities, it does not focus on how data flows from one entity to another. Additionally, it does not describe all possible user decisions or actions.
Useful techniques Most projects need some form of data and behavior modeling to ensure that requirements are clarified and to ensure that no requirements are omitted. So it is important for business analysts to be familiar with data and behavior modeling techniques. Entity relationship diagrams (ERDs) (ERDs) are probably the most widely used technique for data and behavior modeling. These diagrams allow you to identify entities and their relationships with one another, providing a structured analysis of business data and data relationships. ERDs depict data types or entities, the data that needs to be recorded for these entities, and how the entities are connected in terms of business rules and cardinality. These diagrams are useful because they are flexible enough to provide both a high-level overview of complex issues and detailed documentation of the data requirements of a business area. A detailed ERD can be given to relational database developers as a complete set of data specifications that can be used directly in database development. The technique, however, is data-centric and so, does not allow you to map business processes. Also, ERDs that are detailed and complex may be difficult for users to understand. Class diagrams are the most common object-oriented technique used to model data and behavior. These diagrams identify data object classes, operations, and the data that should be recorded within each class. The diagrams also depict a range of relationships between classes. The diagrams help business analysts to break down complex business systems into a series of simple business-data components that are easy to understand and communicate. These diagrams can only be used in object-oriented analysis and design approaches. However, within this setting, they create clear visualizations of implementations and code as well as simplifying the process of designing and building system architecture. Other common techniques associated with data and behavior modeling are
keeping data dictionaries
1208
using metadata definitions
using CRUD matrices
using data transformation and mapping
A data dictionary is a frequently used technique both in requirements elicitation and analysis. Data dictionaries are collections of terms and their definitions. These entries are used to identify business objects, processes, and behaviors. Data dictionaries ensure that stakeholders understand the terminology and use it consistently. They also help ensure that all stakeholders agree on the format and content of information relevant to the target system. With data dictionaries and metadata definitions, you generally use spreadsheets to represent the definitions. This allows you to structure the data consistently, to standardize how the data is recorded and stored, and to ensure that the data is traceable. Data dictionary entries should include
the term name and aliases
the term description
any values or meanings associated with the term
For composite data entries, you also need to include sequences and repetitions associated with the entry. Metadata definitions model data and behavior by describing the context in which data is used, thereby ensuring that data is easily understood. Metadata definitions describe the explicit and tacit information that is required to understand both technical and business data in a target system. They are also used to ensure that this data is valid. Thus it is a critical tool for understanding data. These definitions should be recorded within the target system and this system should be structured to capture and maintain metadata. A CRUD matrix – or a Create, Read, Update, Delete matrix – defines user group access rights to data stored within software solutions. It comprises a matrix-type table that depicts data elements, and how specific user groups can interact with these elements. A CRUD matrix is represented in matrix form that organizes access levels for user groups. The matrix provides stakeholders with a quick reference for validating what data is available to particular groups and it provides information for development teams that need to develop data security mechanisms. Each entity in a matrix must be able to be created, read, updated, and deleted by at least one user group. A CRUD matrix is useful in software development projects but is of little use in business process analysis. It is important that business analysts ensure that the matrix is consistent with user groups and entities described in other requirements.
1209
Data transformation and mapping is used to transfer data, business records, and processes from a legacy system to a target system. It is used in application development projects that intend to use existing business data records. It encompasses moving data from multiple sources, reformatting and cleansing data, and loading data into another system. Data transformation and mapping ensures that issues such as heterogeneous systems, differing data and definitions, and data quality are addressed. This is a complex process and requires input from business owners and subject matter experts to avoid complications and delays. When transforming and mapping data for application development projects, you need to follow a set process. 1. First you need to include a high-level data model describing the entity relationships. 2. Next you map each entity to its associated business rules and owner. Then you create a plan to cleanse data – ensuring that the data meets the needs of the proposed system and that unnecessary or invalid data is removed. 3. Finally, you create an environment plan for the migration of the cleansed data from its source, to a repository for analysis, and then to the production system. Data behavior and modeling describes system objects within the confines of a project's scope. Common techniques associated with this strategy include class diagrams, entity relationship diagrams (ERDs), data dictionaries, metadata definitions, CRUD matrices, and data transformation and mapping. An ERD is the most common technique used when conducting a structural analysis. A class diagram is typically used when conducting object-oriented analyses in software development projects. A CRUD matrix defines user group access rights to data stored within software solutions. Data dictionaries and metadata definitions should generally be used in all projects. Data transformation and mapping should be done in software development projects that need to use some of the original data in a new or updated system.
Class Diagrams Class diagrams are the most common and comprehensive modeling technique for object-oriented analysis in data and behavior modeling. Using these diagrams, business analysts can break down complex business systems into a series of simple components that are easy to understand and communicate. Class diagrams help to bridge the gap between business and technical processes and different stakeholder groups. This modeling technique provides a widely accepted standard for communicating business requirements to technical personnel. Class diagrams are similar to entity relationship diagrams (ERDs) in that they map entities – known as classes – and their relationships. Class diagrams differ from ERDs in that they map operations and they expand on the types of relationships that are mapped between classes.
1210
Class diagram components Class diagrams organize each instance – termed objects – into categories named classes, so that transactions and changes for a particular group can be handled consistently. A class diagram includes the following basic components:
Classes are categories that incorporate objects that are tracked by business and software processes. They are similar to entities in ERDs.
Each class is associated with a list of attributes that are recorded or tracked for each object in the class. Each object's attributes can be changed through the operations of a class.
Operations refer to actions or services that objects belonging to a particular class provide – operations describe what a class can do. Attributes are added, deleted, or modified through a class's operations.
Attributes and operations that are documented for each class apply to all objects in that class. This allows you to centralize business rules and related data for objects within a class, thereby reducing repetition in data storage, documentation, and data processes. When documenting each operation in a class diagram, you include information about three areas of the operation:
An operation pre-condition is the state that an object must hold, or what must be true, before an operation can begin.
An operation post-condition is the state that an object must hold, or what must be true, after an operation is complete.
The business logic for an operation describes the sequence of actions that are associated with a particular operation.
Classes in a class diagram are represented as labeled rectangles. Directly below the class name, attributes for the class can be listed. Operations are depicted directly below attributes within the class rectangle. The operation name is followed by an opening and a closing parenthesis – ( ). In some cases, when attributes do not need to be represented, operations are depicted directly below the class name.
Class diagram relationships Class diagrams list classes, their attributes, and their operations. They also depict the relationships between classes. Determining how each business entity is related to another helps you to identify shared documentation and shared requirements. It also identifies the shared business rules that an organization's IT system should support. The class relationships that can be depicted in a class diagram include the following:
1211
The association relationship is similar to a relationship depicted in an ERD. It explains how one class is linked or associated with another class via a business or software rule.
A generalization relationship has one generalized class and several specialized classes that fall under the generalized category.
An aggregation An aggregation relationship depicts a class that forms part of a whole or larger class. So, aggregation shows components that make up a class.
The multiplicity relationship in class diagrams is similar to that of cardinality in ERDs. Multiplicity specifies the minimum and maximum number of occurrences allowed within a relationship between two classes.
Aggregation and generalization relationships help you to distinguish between attributes that apply to one large category and those that apply to a component category or sub-category only. Identifying these relationships helps you to reduce requirement repetitions between related classes. Generalization is represented in a class diagram as an arrow that moves from the specialized class to the generalized class. Aggregation is represented as a line with a diamond positioned directly below the class that represents the whole category. Association relationships are depicted on a class diagram as an annotated line with a directional arrow that specifies in what direction the association should be read. Although the multiplicity relationship is similar to the cardinality relationship in an ERD, it is depicted differently on a class diagram.
A single integer, for example 1, specifies that that number and that number only applies to the relationship. This relationship is depicted immediately below or above the class using the appropriate integer.
A multiplicity relationship may involve integers x through y. This relationship is depicted immediately below or above the class using the appropriate integers separated by an ellipsis.
A multiplicity relationship may involve x or more instances. This relationship is depicted immediately below or above the class using the appropriate integer, an ellipsis, and an asterisk.
Class diagrams provide an object-oriented approach to breaking down complex business systems into a series of simple components that are easy to understand and communicate. The diagrams comprise classes, attributes, and operations. Classes are represented in terms of their relationships to one another. Potential relationships include aggregation, association, generalization, and multiplicity.
Solution Development Methodologies Before business analysts can effectively analyze requirements, they must have an accurate understanding of the enterprise and the solution development methodology (SDM) intended for the project.
1212
Business analysts create a business domain model to help them achieve an accurate understanding of the enterprise before they start analyzing requirements. While the business domain model of each business is unique, domain models for businesses belonging to the same industry, like the financial services industry, will be similar because they offer similar products and services.
Business domain model A business domain model is a conceptual model of an enterprise. Usually, the domain model focuses on the particular area of the business affected by the project, unless the project has important implications throughout the entire enterprise. Business domain models are valuable because they help ensure the solution will meet the business need by helping business analysts
accurately understand the current state of business within the enterprise
accurately understand the proposed future state of business within the enterprise
verify a common understanding of the proposed solution among stakeholders
When complete, the business domain model provides a complete description of an enterprise's current and proposed organizational structures, processes, and the information required to conduct business. The understanding gained by completing the business domain model will help ensure the requirements are accurate. Business domain models are highly conceptual and there are no guidelines or conventions for their creation. When creating the business domain model, be careful to include all the elements of the domain and show the interactions between them. Here is a simple representation of a business domain model for an organization.
Solution development methodologies With a clear understanding of the business domain, the business analyst can determine which techniques to use to analyze requirements. This decision will, in part, be decided by the solution development methodology being used. Solution development methodologies (SDMs) are the methods used to perform business analysis on a project, and the three broad types of SDMs are
business process analysis
object-oriented analysis
structured analysis
Each SDM relies on process and flow, data and behavior, and usage models to help model the solution. Each SDM also makes use of various analysis techniques to express requirements. Some analysis techniques are more closely associated with a particular SDM because they are better at representing the
1213
type of information the SDM needs to express. However, analysis techniques are not exclusive to specific SDMs. Business process analysis is the methodology primarily used when the project solution requires business process reengineering, which is intended to improve business processes and maximize business results. During business process analysis both the current and the proposed processes of the enterprise must be described. Three analysis techniques can provide this capability:
An activity diagram depicts workflow sequence – how a set of related activities or actions occur and the decisions that control the flow.
A flowchart depicts workflow sequence – how a set of related activities or actions occur and the decisions that control the flow.
A workflow model depicts the flow of work in a specific business area. Workflow models help to document work processes and to find opportunities for process improvement.
Object-oriented analysis is the methodology primarily used when the project solution requires objectoriented software development. In general, object-oriented methodologies describe how people interact with a system to achieve work goals. Object-oriented analysis views a system as a collection of objects that pass messages to one another and it models data and processes together. Several analysis techniques can provide this understanding:
A use case diagram depicts the problem domain by identifying the solution boundary, the actors and use cases involved in the solution, and the relationships between these two elements.
An activity diagram depicts workflow sequence – how a set of related activities or actions occur, and the decisions that control the flow.
A class diagram depicts the elements relevant to the solution. Class diagrams also depict the internal structure of each element and the relationships that exist between elements.
A sequence diagram depicts the logic of use case descriptions. It shows the information that passes between objects in the system and throughout the execution of the use case.
Structured analysis is the methodology primarily used when the project solution requires the development of data process analysis and data management capabilities. Structured analysis is processcentric and pays particular attention to the data that flows into and out of processes. Unlike objectoriented analysis, processes and data are usually modeled separately. Structured analysis relies on analysis techniques that can provide an understanding of the processes involved in the solution. Business analysts use different analysis techniques to understand the processes involved in a solution:
A flowchart depicts workflow sequence – how a set of related activities or actions occur, and the decisions that control the flow.
1214
A data flow diagram depicts how information flows through a system; how it is inputted, processed, stored, and outputted from a system.
An entity relationship diagram (ERD) depicts a data structure. ERDs show the entities – elements the business needs information about – that are important to the solution, the information that must be retained by the system about each entity, and the relationships between the entities.
The decision about which SDM and which analysis techniques to use may be decided prior to the business analyst's involvement with the project. Because of this, it is beneficial for business analysts to be familiar with the three solution development methodologies and the various analysis techniques associated with them. The SDM used will dictate the analysis techniques that will be used. While a business analyst may prefer certain techniques, he should be familiar with all the analysis techniques. This will give him greater flexibility in expressing requirements and will also allow him to understand work completed by colleagues using other techniques. In order to effectively analyze requirements, a business analyst must first clearly understand the business domain and know which solution development methodology (SDM) is being used on the project. Creating a business domain model provides a current understanding of the enterprise, as well as an understanding of the proposed future reality of the enterprise. An inaccurate understanding of the business domain can result in inaccurate requirements. Three SDMs are used to perform business analysis on a project. Business process analysis focuses on process improvement, and the analysis techniques closely associated with it are the activity diagram, the flowchart, and the workflow model. Object-oriented analysis focuses on software development, and the analysis techniques closely associated with it are the use case, activity, class, and sequence diagrams. Finally, structured analysis focuses on data process analysis and data management, and the analysis techniques closely associated with it are the flowchart, the data flow diagram, and the entity relationship diagram.
Business Rules As business analysts model a solution, they need to know how the enterprise conducts business. An enterprise's business activities and acceptable business practices are guided and defined by internal policies and guidelines as well as any internal or external standards and regulations. Business analysts learn about the things that might impact proposed solutions by identifying, documenting, and creating, if necessary, the business rules that govern the business. Business rules are essentially a written statement that exactly and unambiguously expresses all rules included in policies, guidelines, and relevant standards. In the absence of a standard definition for the term business rule, many in the business world have adopted the definition put forth by the Business Rules Group in 2000.
1215
"A business rule is a statement that defines or constrains some aspect of the business. It is intended to assert business structure or to control or influence the behavior of the business." Business rules define what data – the data that guides the activities of the business - is acceptable or expected and govern the interaction between the business and its customers, suppliers, employees, and systems. "An employee with less than six months' employment with the company is not entitled to health benefits" is an example of how a policy translates into a business rule. This rule expresses the acceptable interaction between an enterprise and its new employees. It will guide human resource, accounting, and payroll activities. A single business rule may impact many business activities, processes, information, and systems. This is why it is important to identify business rules before solutions are developed and requirements are analyzed. Business rules affect solution capabilities and therefore directly affect requirements. Analyzing requirements and planning a solution without taking business rules into consideration will likely result in an ineffective solution. There is no universally agreed upon business rules classification scheme. Nonetheless, the professionals who practice business analysis find it useful to classify business rules by type because it can have the following benefits:
Using a rules classification scheme to classify rules by type can help business analysts efficiently discover and validate rules by giving them a process to follow.
Using a rules classification scheme to classify rules by type can help business analysts document and maintain business rule information that will become a resource for future use throughout the enterprise. This makes it easier to update existing solutions or to identify the business rules that will impact other projects.
Business rule types A classification scheme that works well for business professionals consists of the following business rule types:
terms
facts
mandatory constraints
guidelines
action enablers
computations
inferences
1216
The first two types of rules – terms and facts – present information and are often referenced in other rules to give meaning to the other business rule types. They can stand alone in context, but may not be complete sentences. A term defines data concepts and details about concepts such as properties and values. Terms generally take the form of a noun, or a noun phrase, with an agreed-upon definition. Terms define words that have specific meaning to stakeholders, defining the word and identifying what is known about the thing in question. A term may be a definition of a concept, such as "stakeholder," or it may be a phrase identifying a value of a concept, like "end user." A fact is a statement that defines the relationships among terms. An example of a fact might be "Preferred customers qualify for discounts." The next two types of rules, mandatory constraints and guidelines, constrain information by testing data values and placing constraints on a business event. Mandatory constraints stop events from happening. Rules expressing mandatory constraints identify an unconditional circumstance that must be true for the business event to be allowed to complete. People interacting with the solution have no control over the event. Guidelines provide warnings about the completion of an event. Guidelines warn about circumstances that should be true in order for an event to complete in an acceptable way. Unlike mandatory constraints, people interacting with the solution or system can decide how to proceed. Action enablers initiate a new action that takes place outside the target system or business event. An action enabler rule tests conditions with a predetermined truth. If the conditions are true another business event, message, or activity is initiated. The final two types of business rules are computations and inferences. Both of these types of rules use existing information to create new information. Computations arrive at a data value using an algorithm. Common computations include sum, difference, product, quotient, count, maximum, minimum, and average. These are based on quantitative data and are necessary to the business event being completed. Inferences arrive at a data conclusion by testing conditions. Upon finding the conditions true, inferences establish the truth of a new fact. Inferences have an if "A" then "B" relationship. If the condition set forth in "A" is true, then it becomes the true condition of "B." Business rules are a written expression of data and details that must be followed in order for the business to operate as intended. With that in mind, it stands to reason that business analysts would be interested in discovering and validating business rules before requirements analysis is completed. Otherwise, the solution delivered may not support those business rules and therefore be ineffective. Business analysts often find it helpful to classify business rules. A classification scheme that works well for business audiences includes seven types of business rules. Terms and facts define and provide
1217
meaning for the other rule types. Constraint rules – mandatory constraints and guidelines – test data values. Action enablers initiate new action. And finally, computations and inferences create new information.
Data Flow Diagrams Constructing a data flow diagram (DFD) is an ideal way to understand your current IT system before attempting to upgrade it. A DFD is a process and flow modeling technique that shows how information flows through a system – how it is inputted, processed, stored, and outputted from a system. Business analysts use data flow diagrams to help them determine or verify the data requirements of the processes supported by a system. Data flow diagrams allow for structured analysis, which means they not only describe the system, but also describe each of the processes that make up the system. Data flow diagrams are an ideal choice when the solution involves complex data processes. Business analysts use data flow diagrams to
communicate information about system requirements to stakeholders
describe the data requirements of business processes supported by an IT system
document legacy system requirements
describe automated or business systems
What are the limitations of data flow diagrams? Data flow diagrams do not show how a system or business area works, only what the system does. This means decisions and user interactions are not described, making data flow diagrams ineffective on projects aiming to improve processes or create interactive user-based systems. Data flow diagrams provide a data-centric understanding of what a system does. They allow the business analyst to visually depict the
external entities that provide or receive data from a system
processes that transform data within the system
data flows that move data from external entities to processes, between processes and data stores, and from processes to external entities
data stores that store data within the system
Key elements These first two key elements of the data flow diagram show where the information comes from and what the system does with it.
An external entity is a key element of the data flow diagram. An external entity can both send and receive data from data processes within the system. An external entity is represented in the diagram by a labeled rectangle. The label identifies the external entity.
1218
A data process transforms or processes data so it can be used by the system. A data process can transform or process data in many ways including combining it with other data, recording, converting, or filtering it. The standard symbol used to represent a data process is a labeled circle, but a rounded rectangle is also an acceptable variation. Labels name or identify the process by describing the transformation the data process performs. The label-naming convention is to use a verb-object structure.
If an asterisk is included in the data process's name, it means that the process can be decomposed further. This means that more data flow diagrams will need to be developed or that they already exist and should be consulted to ensure a comprehensive understanding of the system. The other two key elements of the data flow diagram help to describe the flow of data within the system.
A data flow moves data through the system and identifies both the data being moved and where the data is moving to. Data flows move data between data processes and external entities, and between data stores and other data processes. A data flow is represented by a single, or forked, arrow-headed line, indicating where the data is moving. Preferably, the data flow label should be a noun phrase that describes the data being moved.
A data store is a location where data is stored or held for future use. While stored, the data is passive; that is, it remains as it was at the time it was stored – it is not processed or transformed in any way. A data store is represented as a label between two parallel lines. The label denotes the type of data it stores.
Understanding data flow diagrams DFDs allow a business analyst to define system boundaries, analyze the data flow through the main processes of a system, and break down the complex processes into their constituent processes. DFD analysis involves three steps: 1. designing a level 0 DFD 2. designing a level 1 DFD 3. breaking down complex processes A level 0 DFD, sometimes referred to as a context diagram, defines system boundaries. Each level 0 DFD depicts the system as a single, usually complex, process. In addition to defining boundaries, a level 0 DFD is used to analyze the requirements of processes supported by a system. The level 0 DFD shows the movement of data into and out of the system.
Designing a level 0 DFD To create the level 0 DFD, you need to know the
process involved
external entities involved
1219
information that flows in and out of the system
The processes involved in a system are the tasks a system performs. Data can flow both in and out of processes. Processes receive input data from the external entity and transform the data into output data. The data outputted by a process can flow to an external entity, a data store, or another process. Once the single, complex process has been identified, the next step in creating a level 0 DFD is to determine which external entities the process interacts with and how the data moves.
The external entities that interact with a system lie just outside the system and identifying them defines the system's boundaries or scope. External entities that interact with the system include people, organizations, and computer systems. External entities are sources or destinations of data. Information about the external entities is collected from stakeholders.
Data flows represent the information – the information that is received from and provided to external entities – that moves between the processes and the external entities. A data flow is shown as a line with an arrow indicating the direction the data is flowing and is labeled with a descriptor of the data being moved.
Designing a level 1 DFD Now that system boundaries have been successfully defined by creating a level 0 DFD, it is time to move on to the second step - designing a level 1 DFD. Designing a level 1 DFD allows you to analyze data flow through the main processes of a system. A level 1 DFD shows the main processes within the project's scope and the data that is required and produced by each process. If you are updating or adding to an existing system, be sure to determine if any processes are being added or revised. As you design the level 1 DFD, you will find that not all the data produced by a process is used right away by another process. When this happens, you must define a data store. A data store is a location where data is stored for future use. While stored, the data is passive. It remains as it was at the time it was stored – it is not processed or transformed in any way. The level 1 DFD uses the data store element – a label between two parallel lines – to represent a data store.
Breaking down complex processes If any of the processes can be broken down even further, you will need to proceed to the third step: break down complex processes. This is the only way to make sure you have discovered all the system's data requirements. When analyzing a system's data requirements, you must break down complex main processes into lowerlevel DFDs. Each process is deconstructed and broken down into as many DFDs as are necessary to represent the details of complex processes. For example, after the system boundaries are identified by the level 0 DFD and the main processes are identified on the level 1 DFD, the main processes may be broken down and identified on a level 2 DFD, a level 3 DFD, and so on, until the process cannot be broken down any further.
1220
Here are a few rules that will help you check the accuracy and completeness of your DFD:
each process must have at least one data flow going into it and one going out of it
every data store must have at least one data flow going into it and one going out of it
all data flows must either start or end at a process
every data item that appears on a data flow diagram must originate and be used somewhere within the related DFDs
Every analysis technique has its strengths and weaknesses that determine its appropriateness for use on various projects. DFDs have several strengths and weaknesses:
they are easy to understand
they constitute a useful analysis, deliverable to developers in a structured programming environment
they enable stakeholders to easily match requirements to technical specifications
they enable stakeholders to verify entity relationship diagrams (ERDs)
they are not effective as an analysis deliverable on an object-oriented analysis project
The data flow diagram is a process and flow analysis technique that works well on structured analysis projects. The key elements in a data flow diagram are external entities, data processes, data flows, and data stores. Depending on the complexity of the process involved, a business analyst will use at least two DFDs to analyze the data requirements of the system. A level 0 DFD, also commonly known as a context diagram, defines the boundaries of the system under review. A level 1 DFD analyzes the flow of information. DFDs are then used to break down each process into single processes or tasks that can't be broken down any further.
Data Flow Diagrams Constructing a data flow diagram (DFD) is an ideal way to understand your current IT system before attempting to upgrade it. A DFD is a process and flow modeling technique that shows how information flows through a system – how it is inputted, processed, stored, and outputted from a system. Business analysts use data flow diagrams to help them determine or verify the data requirements of the processes supported by a system. Data flow diagrams allow for structured analysis, which means they not only describe the system, but also describe each of the processes that make up the system. Data flow diagrams are an ideal choice when the solution involves complex data processes. Business analysts use data flow diagrams to
communicate information about system requirements to stakeholders
describe the data requirements of business processes supported by an IT system
1221
document legacy system requirements
describe automated or business systems
What are the limitations of data flow diagrams? Data flow diagrams do not show how a system or business area works, only what the system does. This means decisions and user interactions are not described, making data flow diagrams ineffective on projects aiming to improve processes or create interactive user-based systems. Data flow diagrams provide a data-centric understanding of what a system does. They allow the business analyst to visually depict the
external entities that provide or receive data from a system
processes that transform data within the system
data flows that move data from external entities to processes, between processes and data stores, and from processes to external entities
data stores that store data within the system
Key elements These first two key elements of the data flow diagram show where the information comes from and what the system does with it.
An external entity is a key element of the data flow diagram. An external entity can both send and receive data from data processes within the system. An external entity is represented in the diagram by a labeled rectangle. The label identifies the external entity.
A data process transforms or processes data so it can be used by the system. A data process can transform or process data in many ways including combining it with other data, recording, converting, or filtering it. The standard symbol used to represent a data process is a labeled circle, but a rounded rectangle is also an acceptable variation. Labels name or identify the process by describing the transformation the data process performs. The label-naming convention is to use a verb-object structure.
If an asterisk is included in the data process's name, it means that the process can be decomposed further. This means that more data flow diagrams will need to be developed or that they already exist and should be consulted to ensure a comprehensive understanding of the system. The other two key elements of the data flow diagram help to describe the flow of data within the system.
A data flow moves data through the system and identifies both the data being moved and where the data is moving to. Data flows move data between data processes and external entities, and between data stores and other data processes. A data flow is represented by a single, or forked, arrow-headed line, indicating where the data is moving. Preferably, the data flow label should be a noun phrase that describes the data being moved.
1222
A data store is a location where data is stored or held for future use. While stored, the data is passive; that is, it remains as it was at the time it was stored – it is not processed or transformed in any way. A data store is represented as a label between two parallel lines. The label denotes the type of data it stores.
Understanding data flow diagrams DFDs allow a business analyst to define system boundaries, analyze the data flow through the main processes of a system, and break down the complex processes into their constituent processes. DFD analysis involves three steps: 1. designing a level 0 DFD 2. designing a level 1 DFD 3. breaking down complex processes A level 0 DFD, sometimes referred to as a context diagram, defines system boundaries. Each level 0 DFD depicts the system as a single, usually complex, process. In addition to defining boundaries, a level 0 DFD is used to analyze the requirements of processes supported by a system. The level 0 DFD shows the movement of data into and out of the system.
Designing a level 0 DFD To create the level 0 DFD, you need to know the
process involved
external entities involved
information that flows in and out of the system
The processes involved in a system are the tasks a system performs. Data can flow both in and out of processes. Processes receive input data from the external entity and transform the data into output data. The data outputted by a process can flow to an external entity, a data store, or another process. Once the single, complex process has been identified, the next step in creating a level 0 DFD is to determine which external entities the process interacts with and how the data moves.
The external entities that interact with a system lie just outside the system and identifying them defines the system's boundaries or scope. External entities that interact with the system include people, organizations, and computer systems. External entities are sources or destinations of data. Information about the external entities is collected from stakeholders.
Data flows represent the information – the information that is received from and provided to external entities – that moves between the processes and the external entities. A data flow is shown as a line with an arrow indicating the direction the data is flowing and is labeled with a descriptor of the data being moved.
1223
Designing a level 1 DFD Now that system boundaries have been successfully defined by creating a level 0 DFD, it is time to move on to the second step - designing a level 1 DFD. Designing a level 1 DFD allows you to analyze data flow through the main processes of a system. A level 1 DFD shows the main processes within the project's scope and the data that is required and produced by each process. If you are updating or adding to an existing system, be sure to determine if any processes are being added or revised. As you design the level 1 DFD, you will find that not all the data produced by a process is used right away by another process. When this happens, you must define a data store. A data store is a location where data is stored for future use. While stored, the data is passive. It remains as it was at the time it was stored – it is not processed or transformed in any way. The level 1 DFD uses the data store element – a label between two parallel lines – to represent a data store.
Breaking down complex processes If any of the processes can be broken down even further, you will need to proceed to the third step: break down complex processes. This is the only way to make sure you have discovered all the system's data requirements. When analyzing a system's data requirements, you must break down complex main processes into lowerlevel DFDs. Each process is deconstructed and broken down into as many DFDs as are necessary to represent the details of complex processes. For example, after the system boundaries are identified by the level 0 DFD and the main processes are identified on the level 1 DFD, the main processes may be broken down and identified on a level 2 DFD, a level 3 DFD, and so on, until the process cannot be broken down any further. Here are a few rules that will help you check the accuracy and completeness of your DFD:
each process must have at least one data flow going into it and one going out of it
every data store must have at least one data flow going into it and one going out of it
all data flows must either start or end at a process
every data item that appears on a data flow diagram must originate and be used somewhere within the related DFDs
Every analysis technique has its strengths and weaknesses that determine its appropriateness for use on various projects. DFDs have several strengths and weaknesses:
they are easy to understand
they constitute a useful analysis, deliverable to developers in a structured programming environment
they enable stakeholders to easily match requirements to technical specifications
1224
they enable stakeholders to verify entity relationship diagrams (ERDs)
they are not effective as an analysis deliverable on an object-oriented analysis project
The data flow diagram is a process and flow analysis technique that works well on structured analysis projects. The key elements in a data flow diagram are external entities, data processes, data flows, and data stores. Depending on the complexity of the process involved, a business analyst will use at least two DFDs to analyze the data requirements of the system. A level 0 DFD, also commonly known as a context diagram, defines the boundaries of the system under review. A level 1 DFD analyzes the flow of information. DFDs are then used to break down each process into single processes or tasks that can't be broken down any further.
Activity Diagrams An activity diagram is a modeling technique that depicts workflow or a sequence of dynamic activities – how a set of related activities or actions occur and the decisions that control the flow. Like the data flow diagram, the activity diagram is a process and flow modeling technique, but it focuses on the actions and activities that are completed by the system. Activity diagrams are often used to describe complex processes and to gain consensus. Because they describe both the sequence of activities and the decisions that control the flow of the activities, they are able to describe logic and behavior. While performing business analysis it is important to use a model that will provide the most useful information. Activity diagrams are a good choice when
the details of complex processes involving actions or activities need to be communicated
a sequence of activities needs to be understood
it is important to understand the logic of the workflow
it is important to know about the decisions that can affect the order in which activities occur
An activity diagram is likely to be used to analyze and describe or document
complex use case scenarios
business workflows
complex algorithms
responsibility for the completion of activities
Key elements Activity diagrams use specific components to help describe a sequence of activities or workflow.
1225
The start point indicates the start of the sequence being modeled and is represented by a filled circle.
An arrow-headed line is used to represent the sequential flow of activities ; the order in which activities occur.
Each activity in the workflow is represented by a rounded rectangle. Activities are always labeled to denote the action taken by the system.
A branch is used to depict the splitting of one flow into two or more mutually exclusive alternate flows that the workflow could follow based on a decision. A diamond is used to represent a branch in the workflow.
A merge is used to depict the joining of mutually exclusive alternate flows back into one. A diamond is also used to represent the merge of the workflow. The merge symbol is not always used. A popular variation is to simply show the independent flows becoming one again. However, this convention is not compliant with the Unified Modeling Language (UML) 2 standards.
These components are also used in activity diagrams to help describe a sequence of activities or workflow.
A fork, represented by a bar, indicates where a single flow turns into two or more parallel flows.
A join, also represented by a bar, indicates where parallel flows become one.
Responsibility for completion of the activities in the modeled workflow can be represented by labeled swimlanes. Swimlanes are lines drawn in the activity diagram to indicate specific areas of responsibility. Swimlanes can be horizontal or vertical, depending on the layout of the activity diagram.
The end point indicates the end of the sequence being modeled and is represented by a filled circle with a border around it. When an end point occurs on an alternate flow, it is referred to as an exception because the sequence does not complete as it normally would on the basic flow.
Understanding activity diagrams In addition to knowing the components of an activity diagram, knowing how one is created can help build an understanding of the activity diagram. To create an activity diagram, you first need to find out some information from stakeholders:
Knowing where the sequence being modeled begins and ends sets the boundary for requirements analysis.
To accurately depict a sequential flow, you need to know which activities must happen before others, so the sequence dependencies must be known.
Any conditional logic that affects the flow of activities must also be accurately depicted in the activity diagram. Conditional logic describes the decisions that, when made, create an alternate flow.
On some projects, and in some workflows, it may be important to know who or what business area or group is responsible for the completion of activities.
1226
The information gathered from stakeholders helps you determine an activity diagram's basic flow, as well as any alternate flows and exceptions. The basic flow is the expected and most probable flow a sequence of activities will follow from beginning to end. Alternate flows depict how the flow will behave as a result of conditional logic. Exceptions can occur on basic or alternate flows and signify the premature end to the flow, for instance if a user's login fails to be verified by the system. When the required information has been gathered and organized, it needs to be expressed in the activity diagram. Components are coupled with notation to help make sense of alternate flows and exceptions within the activity diagram. The basic flow of activities arrows are not generally accompanied by notation because their flow is expected; however, flow of activities arrows receive notation in a couple of instances:
When decisions are necessary the branch component is used to start an alternate flow. The alternate flow exiting the branch component is labeled with notation that expresses the guard, or condition, that made the alternate flow necessary. This may be as simple as "yes" or "no" or it may be a complex algorithm.
An exception occurs at a decision point where the condition, or guard, specifies that if the condition is not met the flow must end.
Rules can help you complete an activity diagram and check that it is done properly. The rules are
only one start point per diagram
as many end points as required
one activity follows another
following a branch, either one activity or another happens next
following a fork, activities are parallel and may happen at the same time or one may start first
A recognized strength of activity diagrams is their ability to visually represent complex flows, decision points, and parallel flows. The ease with which they are developed and the potential for a wide audience to understand them. While their ability to show responsibility for activities can be seen as an advantage, if the sequence being modeled is complex, it can make the activity diagram difficult to both develop and understand. The activity diagram is a process and flow analysis technique that works well on business process and object-oriented analysis projects. The key components used to create an activity diagram are the start point, flow of activities arrows, activities, branches, merges, forks, joins, and the end points. Activity diagrams can also use swimlanes to denote responsibility for activities. However, the use of swimlanes is optional.
1227
Activity diagrams can model complex sequences of activities and workflows and still be understood by a variety of audiences. They are a good choice when it is important to communicate how a system behaves and the logic that controls its flow over time.
Refining and Documenting Requirements SkillBriefs Functional Requirements Explore techniques for documenting functional requirements. Quality of Service Requirements Discover ten types of quality of service requirements. Decomposing Requirements Learn key concepts associated with decomposition techniques. Constraints and Assumptions Learn about the influence of constraints and assumptions. Requirements Attributes Learn how to identify and determine requirements attributes. Types of Requirements Documents Explore the various types of requirements documents. Validating and Verifying Requirements Discover how to verify and validate requirements.
1228
Functional Requirements The set of core behaviors that must be supported by a business system is called functional requirements. Of the six requirement types, user requirements and functional requirements are similar and often confused. Functional requirements describe the required behavior of the solution. Functional requirements are required for all projects, and must be thoroughly documented and analyzed. The difference between functional and user requirements is that user requirements describe a specific set of stakeholder needs, and not all solutions require defined user requirements. The business analyst needs to be able to analyze different types of requirements. In order to do that, requirements must first be properly documented. Functional requirements can be presented using four documentation methods: textual documentation, matrix documentation, diagrams, and models.
Textual documentation Textual documentation is typically used to state uncomplicated functional requirements that are small in scope. This method is often used to describe business rules. The advantage of textual documentation is that it is simple and easy to search. Requirements should be stated in short paragraphs using simple terms, and each requirement must be documented separately. It's important to use consistent terminology and to write in the active voice when describing the requirement. Three things must be included when documenting functional requirements textually:
a description of the capabilities of the solution
a description of any conditions that must exist for the requirement to operate
a description of any constraints that may prevent the solution from being able to fulfill the requirement
Matrix documentation Matrix documentation is used when the business analyst needs to present a set of complex, uniform, functional requirements. A matrix may be used to document requirements attributes and data dictionaries, and for prioritizing requirements with respect to project objectives. The advantage of matrix documentation is that functional requirements are traceable and map to objectives. A matrix should not be used for requirements that are not uniform. Matrices are used to indicate how two or more elements relate to each other. The simplest form of matrix documentation is a single-column table. A more involved table contains related information across rows and columns.
1229
When constructing a matrix, the business analyst should use one row per requirements specification paragraph, and identify it by the paragraph number assigned in the requirements document. There should be one column per identified configuration item.
Diagrams Diagrams are another way to document functional requirements. Diagrams are used to visualize relationships between elements of a requirement. They should be simple and the graphical representations consistent. The benefit of a diagram over a textual requirement is that a diagram can often be easier to understand, presenting clear views of the structure and relationships of functional requirements. Diagrams can be used to show
the relationship between different elements of a solution
events that need to occur in a specific order, including parallel events
the physical location of elements of the solution
Models Models are used to represent functional requirements that are too complex to be effectively covered by a single document item. They may take the form of one or more of the other documentation methods. The benefits of modeling are that models simplify complex systems and concepts, and help eliminate less relevant information that may be confusing. This is why they are typically used for documenting very complex project or system requirements. Models depict requirements from different perspectives. Because of this, they help the business analyst examine all elements of a problem and devise a solution. Sometimes a model is unnecessary or undesirable. A business analyst may decide against modeling when
the problem domain is well known
the solution is simple
few people need to collaborate to plan or implement the
the solution requires minimal maintenance
the scope of future requirements is limited
When documenting functional requirements, it's important to do so in such a way that stakeholders are able to
1230
uniquely identify every statement of requirement - Each statement of requirement needs a unique identifier so that it can be referenced and tracked.
classify every statement of requirement in multiple ways - Functional requirements should be documented with enough information that stakeholders can classify them in different ways, such as in terms of importance, type, or urgency.
track the status of every statement of requirement solution - The status of each functional requirement must be traceable in different ways, such as review status, satisfaction status, and qualification status.
elaborate a requirement in multiple ways - Functional requirements must be defined in multiple ways, such as in terms of performance information, quantification, test criteria, rationale, and comments.
view a statement of requirement in the document context - A statement of requirement must be available to be reviewed in context alongside other relevant statements.
navigate through a requirements document to find requirements according to classification or context - Functional requirements must be documented in such a way that stakeholders can find what they need by searching either a requirement classification or by the context of the requirement.
trace to any individual statement of requirement - Every functional requirement must be associated with one of the requirements listed in the statement of requirement. These requirements have unique identifiers in order to be more easily referenced.
Functional requirements describe the required behavior of the solution. They need to be documented and analyzed for every project. Four different documentation methods can be used: textual documentation, matrix documentation, diagrams, and models. The business analyst must learn how and when to use each of these methods appropriately and effectively using best practices. Functional requirements need to be documented in such a way that they include all relevant information and so that stakeholders can find the information they need quickly and easily.
Quality of Service Requirements Just as business solutions must meet particular functional requirements, they must also maintain the expected quality of service under a variety of conditions. Quality of service requirements describe the conditions under which the solution must remain effective. Sometimes called non-functional requirements, quality of service requirements often describe solution constraints. There are ten types of quality of service requirements: Environmental requirements are constraints that come from outside the scope of the project, and must be specified by the business analyst. The three most common types are audit, globalization and localization, and legal and regulatory.
1231
Audit requirements involve information that isn't strictly needed by the system but that must be available if requested.
Globalization and localization requirements are things that need to be included for different countries and cultures.
Legal and regulatory requirements are those imposed by governments and external regulatory bodies.
Interface requirements deal with how the parts of a computer system interact.
Hardware interface requirements describe how the interface needs to interact with the hardware components of the system.
Software requirements describe how the interface interacts with other software components.
Operational requirements describe how a system functions, and how it needs to interact with other operators. Performance requirements establish the level of efficiency the system needs to be able to reach in a specific time frame. Privacy requirements define what information is private and the conditions under which it can be distributed, internally and externally. Quality requirements define the expectations of quality for a system. They describe specific, prioritized characteristics of a system, and must be qualitative and verifiable. There are various types of quality requirements:
Failure and disaster recovery requirements define the protections that need to be in place to help prevent full or partial system failure and data loss.
Maintainability requirements explain the way in which future changes to the solution must be implemented.
Scalability requirements describe how to plan for the growth of the solution over time.
Safety requirements define the requirements involved with potential losses or damages that may be incurred as a result of using the system. This includes safety measures and precautions that must be taken, as well as preventative measures. Security requirements deal with protecting the information used and produced by the system. This includes requirements for monitoring and restricting access to sensitive information, as well as defining the risk of the information being accessed illicitly. Training requirements define the level of knowledge required to interact with the solution, as well as any changes that may arise and who may be affected.
1232
A glossary is also a quality of service requirement. It describes terms and definitions relevant to the project. Quality of service requirements define conditions under which the solution must be able to operate. They are sometimes called non-functional requirements, and they can be used to define solution constraints. Quality of service requirements include environmental, interface, operational, performance, privacy, quality, safety, security, and training requirements, as well as a glossary. These requirements define how the solution must behave under different circumstances, which can help keep the project on track toward the expected solution.
Decomposing Requirements Requirements should be organized in such a way that stakeholders can easily find the information they need. Requirements decomposition is a way to group requirements into categories. A business analyst can use decomposition techniques to structure requirements into packages. This helps refine the problems and solutions initially identified during enterprise analysis. The business analyst needs to define the solution boundary and structure the solution definition.
Defining the solution boundary involves documenting the ownership of the solution, such as where other actors interact with the solution, where other systems provide or extract information from the solution, and where time initiates activities for the solution.
Structuring the solution definition involves describing the solution in manageable terms and breaking tasks down so they are as independent as possible.
Defining the solution boundary and structuring the solution definition can be done using any or all of three key decomposition techniques: goal decomposition, feature list decomposition, and functional decomposition.
Goal decomposition A goal is a textual business requirement. The purpose of goal decomposition is to focus the solution to meet high-priority stakeholder needs. Goal decomposition breaks high-level goals into lower-level goals. These lower-level goals must be measurable, must include objective criteria, and must be achieved by the solution or by an external source.
Goals need to be measurable in order to be properly met. If a goal is not measurable, stakeholders' expectations may differ.
In order for stakeholders to determine when the goal has been achieved, the lower-level goals need to include objective criteria that can be decisively met. Objective criteria are things like performance targets, costs, and aesthetics.
1233
Each goal must be addressed by the solution. If an actor outside the scope of the solution is responsible for achieving the goal, the solution must still be able to accommodate success or failure to achieve the goal.
Feature list decomposition Features are high-level descriptions of the desired behavior of the solution. They let the business analyst manage scope and priority at an early stage. They also validate stakeholder views of the solution. A feature can be textual or it can be graphical. For example, use cases are sometimes presented graphically. A use case is an examination of an actor's flow through a system. It is used to understand how a system will be used. For example, a feature in a use case might be that users can print reports from the system. Feature list decomposition involves breaking each feature into specific detail. This includes the feature
description and priority - Each feature should have a specific description and priority assigned to it.
stimulus/response sequences - The interaction between each component of the solution needs to be explained in order to understand the possible reactions.
functional requirements - The functional requirements of each feature should be included in the feature list. These are descriptions of the required behavior of the solution.
Functional decomposition Functional decomposition involves breaking down functions into smaller tasks. This enables detailed analysis of each task. When performing functional decomposition, the business analyst must follow these steps in order: 1. Identify the high-level functions of a solution. This allows the business analyst to ensure all of the key processes will be considered. 2. Break down the high-level functions into lower-level processes. Each high-level function can be broken down into smaller, more specific functions. The resulting functions are also broken down until a single identifiable task is reached that cannot be broken down any further. 3. Model the functions and processes. The components of the functions and processes can be presented in several ways, including a hierarchical diagram, a tree diagram, or by simply numbering each task. This allows each task to be understood in relation to the others. Requirements should be organized for easy access. Requirements decomposition is one way to do this. A business analyst uses techniques such as goal decomposition, feature list decomposition, and functional decomposition in order to break requirements down into manageable pieces.
1234
Constraints and Assumptions When you're working on a project, you need as much information as possible about anything that may influence it. This might include how much money you have to work with, how long before the project needs to be completed, and who can work on the project. Business analysts identify these influences as assumptions and constraints. They're usually documented textually since they don't present as well using a model.
Constraints Constraints are any restrictions or limitations to the solution. The specific nature of the constraints dictates the flexibility of the project to meet the solution requirements. This especially applies to things that would normally be allowable, but for some reason are not valid options for the project. A business analyst needs to break down constraints into two categories: business constraints and technical constraints. Business constraints define operational and organizational limitations on the solution. This includes restrictions on time, budget, and resources, as well as skills required by project team members and stakeholders. When considering business constraints, it's important to analyze them closely and ensure they are justified. Business constraints may differ in type, but they all have an impact on the solution. Some types of business constraints are
budget - Any financial restriction on the project is a business constraint. For example, if business leaders mandate a specific operating budget to which the solution must adhere, the project team must in turn implement a solution that adheres to this restriction.
time - Time and scheduling are critical to the success of a project. A business constraint might be when the use of a resource with limited availability is required during the project. In this case, it is important that the project schedule is prioritized in a way that puts this resource to use only when it is available.
resources - Resources can be either human resources or infrastructure resources. A business constraint on the solution could be a construction project obligated to use a specific supplier for building materials. The necessity for and availability of team members with specific skill sets is also a business constraint. If the project will require the services of a database performance expert, this needs to be addressed, since the unavailability of such an individual will impact the effectiveness of the solution.
policy - Company policies can impose business constraints on a project. For example, a company may insist that each new software product it develops passes a third-party security certification before being released.
Technical constraints also describe restrictions or limitations on the solution, but refer specifically to the technical environment under which the solution will be deployed. These constraints may include items
1235
such as hardware and software requirements, architectural design standards, and required application software. Like business constraints, technical constraints also come in a variety of types:
hardware - Hardware constraints put limits on what equipment must be used. For example, a company developing a portable global positioning system dictates that the new devices must use the same power adapters and chargers as wired GPS. The solution is technically constrained to use implementations that use the same adapters and chargers.
software - Technical constraints may be in the form of software restrictions, such as requiring compatibility with a specific software platform. For example, it may be required that a digital imaging application be compatible with other digital imaging applications.
architectural - Architectural constraints include restrictions such as resource utilization, number of files, and data record sizes. For example, a company is developing a software system that is intended to be deployed on a number of varying physical servers that cannot be upgraded. The application is technically constrained to work with the current amount of memory and disc space available on the system with the lowest specifications.
standards - Technical constraints may be in the form of specific standards that the solution must meet or adhere to. For example, for ease of maintainability, a software engineering group requires that all projects to which it contributes use a specific coding standard.
Assumptions Where constraints tend to limit a solution, assumptions open up possibilities. Assumptions are suppositions about conditions that apply the project. Assuming certain things about the project allows the project team to move forward in the face of a certain amount of uncertainty. Assumptions are based on the best knowledge or expectations at the time. Because they are not always known with certainty, they are a source of some project risk. Therefore, it is important to formally record assumptions as soon as possible. Assumptions can be one of two types:
an assumed but unverified condition - Some critical conditions may be assumed when designing a project solution, even if they are not verified when the requirements are specified.
a verified condition that is assumed will not change - A business analyst may identify an existing condition that is vital to the successful implementation of the solution. The assumption is that this condition will not change; if it does, it will have a detrimental effect on the project.
Business analysts identify assumptions and constraints that may influence the implementation of a project. Constraints put limits on a solution. They may be business constraints, such as restrictions on budget, time, and resources. Or they may be technical constraints, such as restrictions on hardware and software usage on the project.
1236
Assumptions make things possible on a project. A business analyst may assume certain conditions, such as material availability, in order to move a project forward. Or the business analyst may include an assumption that a critical condition for the project will not change, such as the retention of any key project team members.
Requirements Attributes Attributes provide necessary information about project requirements. They make it possible for requirements to be grouped according to different criteria. Being able to sort requirements in different ways enables more efficient requirements analysis. Two requirements may seem unrelated at first, but sorting by common attributes may reveal a relevant connection. Requirements and their attributes must be presented properly. Using a template is a good way to ensure accuracy and consistency when documenting requirements attributes. It's also important to use the right language when documenting requirements. The use of specific imperatives can add weight to the priority of the requirement, such as
shall and must - By using "shall" or "must" you are indicating that the requirement is mandatory.
should - The use of "should" indicates the requirement is desirable, but not mandatory.
may - Using "may" indicates that the requirement is optional.
will - The use of "will" indicates that the requirement is already expected to be fulfilled external to the solution.
Requirements may have several different attributes assigned. The ten most common requirements attributes can be grouped into three categories. Four of the ten most common requirements attributes identify or describe the requirements:
The unique identifier attribute is a numeric or textual reference that each requirement must have. It must be unique, and it must never change, even if the requirement is altered or even removed. Given a unique identifier, a requirement can be tracked through all versions of requirements documentation. Making it immutable improves document maintainability and consistency throughout the course of the project.
The author attribute is straightforward – it refers to the person who wrote the requirement. Noting the author of a requirement is important in the event that clarification is needed at a later project stage. The author attribute can be used to differentiate between the writer and the person who is ultimately responsible for the requirement. The author may have provided the requirement and is a good point of contact to get more information about a requirement or the purpose behind the requirement when performing analysis. But the author may not necessarily be the person responsible for ensuring the requirement is properly specified or satisfied.
The ownership attribute describes the person or group for whom the requirement is necessary. It may also refer to the business owner once the project is completed. It is especially useful if a project has requirements from several different sources. Ownership can be used to clarify a
1237
distinction between the author who writes the requirement and the person or organization ultimately responsible for specifying the requirement and ensuring it is satisfied.
The source attribute refers to the origin of the requirement. Each requirement must be traceable to an authorized source, in the event that the requirement changes or more information is needed during the course of the project. Business objectives or stakeholders are often the source of project requirements.
Attributes that identify or describe requirements are important in that they allow requirements to be properly traced and accessed at any time during the course of the project. Dealing with requirements that cannot be properly identified may result in wasted time and resources if a problem arises during the course of the project. Two of the ten most common requirements attributes deal with the significance of the requirement:
The priority attribute describes the order in which requirements must be implemented. Common priority levels are "low," "medium," and "high." Prioritizing requirements is a balancing act between schedules, resources, and quality. Some necessary requirements must be completed before others may begin; this is where priority is especially important. Some requirements will be non-negotiable, but some may fall into the "nice to have" category. The traditional tradeoffs during the course of any project are time, cost, and quality. "Nice to have" requirements need to be evaluated and prioritized in order to deliver an acceptable product in an achievable time frame at a reasonable cost.
The urgency attribute refers to how quickly the requirement is needed. This is documented separately from the priority attribute when there is a specific deadline for implementation of the requirement. Urgency is measured in terms of the date and time the requirement must be completed.
Attributes that deal with the significance of requirements are useful when deciding how to handle each requirement. Requirements with specific implementation deadlines can be planned for, and the highestpriority requirements can be given the attention they need. The final four of the ten most common requirement attributes indicate the state or condition of the requirement:
The stability attribute refers to the maturity of the requirement. The amount of change to a requirement since its origin indicates its stability – a requirement with many changes is less stable than one with only a few. Stability levels are often documented as "low," "medium," and "high." A version number should also be included to help track the evolution of the requirement. Stability should be used when requirements are in a state of flux, or when a requirement is subject to rapid changes. Unstable requirements are a sign that project team members need to perform frequent checks to ensure the latest modifications to the requirement are implemented and tested.
The complexity attribute refers simply to the difficulty expected in implementing the requirement. Complexity management is critical – it's important to know how much work will be required to satisfy the requirement. Complexity can be documented on a scale of one to five, with one being a simple requirement, and five being a complex requirement.
1238
The acceptance criteria attribute describes the conditions that indicate the requirement has been correctly implemented. It is a set of minimum behaviors to which the solution must adhere in order to be considered satisfied.
The status attribute indicates the state of the requirement. Requirements may be proposed, accepted, verified, or implemented.
Some attributes are mandatory for all requirements. Every requirement must have a unique identifier, status, and acceptance criteria assigned. This information is critical to effective requirements management. Knowing how to decide which attributes to assign is important to proper requirements documentation. When deciding which attributes to assign to a requirement, a business analyst must decide what information will be the most useful when dealing with the requirement. It isn't practical to assign every attribute to every requirement. Key attributes that are most often necessary include author, priority, and source. This is in addition to the mandatory attributes of a unique identifier, acceptance criteria, and status. Attributes offer important information about requirements. They allow requirements to be grouped based on different characteristics, enabling more efficient requirements analysis. When documenting these requirements attributes, use of imperatives can provide insight into the priority of the requirement. Terms like "shall" and "must" indicate a mandatory requirement, whereas "should" and "may" represent nonmandatory requirements, and "will" describes a requirement that is expected to be fulfilled external to the solution. More than one attribute may be assigned to a requirement. There are ten requirements attributes commonly used, which can be grouped into three categories. Attributes that identify or describe the requirement are unique identifier, author, ownership, and source. Attributes that deal with the significance of the requirement are priority and urgency. Finally, attributes that indicate the state or condition of the requirement are stability, acceptance criteria, complexity, and status. Of these ten attributes, three are mandatory for every requirement – unique identifier, status, and acceptance criteria.
Types of Requirements Documents When starting any project, whether it's charting unknown waters or building a house, you need to know exactly what is required for success. Requirements documents describe the functional and quality of service requirements for a project. Requirements documents contain all the information about each requirement and are used to define project tasks. They are statements of what the project needs to accomplish. There are no strict rules to follow when choosing how to write requirements documents. It's up to the business analyst to evaluate several factors – including the methodology adopted by the enterprise, the objective of the project, and the needs of stakeholders – and then make the best choice. A business analyst has five different formats to choose from when drafting requirements documents:
1239
A vision document can be created through enterprise analysis. It documents the overall scope of the solution domain, and should be the first requirements document the business analyst puts together. A business process description is a high-level summary of the problem and the solution. It addresses issues such as what the problem is and what the customer wants. It includes information about what the project is about, who will use the solution, and how the solution should behave. A business requirements document (BRD) is used to describe the business requirements defined through enterprise analysis. It is intended to be utilized by customers and users. In addition to a basic cover page, a business requirements document typically contains several components:
A version control table is used to track the history of the documents. It records the date, description, author, and authorization for each version, which is given a unique identifying number.
A RACI matrix – Responsible, Accountable, Consulted, and Informed – is used to describe how project team members and stakeholders interact with the business requirements document. It explains who is responsible for creating the document, who is accountable for the accuracy of the document, who is consulted during the development of the document, and who must be informed of any changes to the document.
The executive summary is a single page that summarizes the business requirements document. It should provide a brief overview of the project, including background and objectives, and summarize the requirements and the proposed solution. The executive summary also describes the project scope and any constraints that have been identified. The risk analysis, business case, and the impact of proposed changes should also be included in this document.
Software requirements specifications (SRS), also called system requirements specifications, describe the required behavior of a software system, and how it is to be implemented. It is used by the development team responsible for implementing the solution. Requests for proposal (RFPs) and requests for quotation (RFQs) are used to contract solution development services from external organizations. Specific objectives need to be stated to ensure the developers understand exactly what the solution requires. Each requirements documentation format offers specific information to the project team, the stakeholders, and the client. Vision documents, request for proposal documents, and request for quotation documents state the business requirements for the project. The business process description describes the current business model, as well as user and functional requirements. The business requirements document and software requirements specification both cover the requirements model; user, functional, and quality of service requirements; and assumptions and constraints. Software requirements specifications also cover requirements attributes and include a traceability matrix. Requirements documents are used to describe the functional and quality of service requirements for a project. They can be developed using five different formats: a vision document, a business process
1240
description, a business requirements document, a software requirements specification, and a request for proposal or quotation.
Validating and Verifying Requirements Validation and verification of requirements are similar, but different things. Understanding the difference is important to ensure requirements are handled properly. Requirements validation helps the business analyst answer the question "Are we producing the right product?" Requirements verification helps answer "Are we producing the product right?"
Requirements validation It's important to validate project requirements before work begins. Requirements validation helps ensure that the requirements have been sufficiently defined to allow the right solution to be developed. Three techniques that can be used for requirements validation are requirements reviews, prototyping and model validation, and acceptance testing. Requirements reviews are a type of peer review. They help identify any requirements that are ambiguous or incomplete, as well as any requirements that are unverifiable or improperly defined. The reviews can be performed formally or informally. Informal reviews can be used to introduce the project and its requirements to others, and to obtain general feedback. There is no set process, and reviews are not always consistent or thorough. Formal, structured reviews follow a specific process to help achieve more comprehensive coverage of the requirements. This type of review results in a report that summarizes the problems with the requirements and any issues that arise during the review. One type of formal review is an inspection. People with different perspectives on the project should be included in the inspection process – up to about six people in order to keep the process manageable. Among them should be the business analyst, the project manager, and key project team members. During the inspection process, requirements are evaluated to determine their
organization and completeness – In order for requirements to be valid, they need to be properly organized and complete. They should be written consistently, with an appropriate level of detail to ensure they provide the information needed to design the solution. Ambiguous requirements will cause problems later in the project, so it's important to validate the requirements before the project begins.
correctness – Requirements need to be correct for them to be valid. They must be unique, and cannot contradict other requirements. Each requirement must fall within the scope of the project, and be achievable within known project constraints. They must also be clearly written using proper syntax.
1241
quality attributes – Validation includes making sure the requirements attributes are right. Performance objectives, and security and safety considerations must be properly specified, and any other quality attributes need to be specifically documented.
traceability – Each requirement must be uniquely identified to ensure it is traceable. If a requirement is not identified correctly, it may be mishandled or left out of decisions that should take the requirement into account, potentially causing errors or mistakes for the project.
special issues – Requirements validation includes addressing special issues, such as ensuring that the documented requirements are actually requirements and not solutions in themselves. It also involves checking whether any time restrictions are identified and properly documented, and ensuring that internalization issues are sufficiently prepared for.
Part of validating requirements is prototyping and model validation. Test cases are used to demonstrate expected system behaviors. This helps expose any problems with the requirements early, before correcting them becomes a complicated and expensive process. Problems could include incomplete requirements or even missing requirements. Black box test cases help you understand how a system is expected to behave under specific conditions. This information can be used to evaluate textual requirements, analysis models, and prototypes. Acceptance testing is used to evaluate whether the solution or system meets the requirements. Acceptance tests should be developed early on so that any discrepancies between the acceptance criteria and the stated project requirements can be identified and remedied. Anticipated usage scenarios should be the focus of acceptance testing. Use cases help determine the acceptance criteria that the solution will have to achieve in order to satisfy the testing. They should focus on the normal expected behavior, and do not need to map every possible scenario.
Requirements verification Requirements verification is necessary to ensure that the stated requirements for the project will help to achieve the expected solution. Criteria for verifying requirements include determining whether the requirement is
complete – Requirements must be complete to be verified. This means that each requirement must be documented, providing all of the information needed to achieve the requirement.
consistent – It's important that requirements are consistent – they must not contradict or come into conflict with each other.
correct – Requirements must be correct in order to be verified. Each requirement should be described accurately according to the standards of the person who set the requirement.
unambiguous – A requirement cannot be verified unless it is unambiguous. The requirement should be phrased in such a manner as to leave no room for interpretation, and its meaning should be absolutely clear to all readers. One way to keep requirements unambiguous is to write
1242
the requirements using simple, concise language and to ensure that any technical terms that may impact understanding are clearly defined.
feasible – Requirements must also be feasible in order to be verified. They should be possible to achieve within the scope of the technical and operational environment of the project.
traceable – A backward traceable requirement has a clear path to its specific origin, whether that origin is based on a client's statement, a use case scenario, or a business requirement. A forward traceable requirement has a specific identifier that allows it to be identified through all the parts of the solution.
measurable and testable – Each requirement must also be measurable and testable in order to be verified. Testing helps ensure that the solution will meet the requirements.
Validating and verifying requirements is essential to ensuring that the project has proper requirements. Requirements validation helps to determine whether the requirements have been sufficiently defined in order to develop the expected solution. Three techniques that can be used for requirements validation are requirements review, prototype and model validation, and acceptance testing. Requirements verification helps to determine whether the stated requirements will achieve the expected solution. In order to be verified, requirements must be complete, consistent, correct, unambiguous, feasible, traceable, and measurable and testable.
1243
Software testing The Necessity of Software Testing Learning Objectives
After completing this topic, you should be able to
recognize different types of software errors
recognize how testing can improve quality in software development 1. Correcting Errors, Defects, and Failures Software systems form an integral part of our daily lives. Whether in our homes or at our workplaces, software systems have become indispensable for a comfortable existence. Therefore, software failure can prove expensive and result in the loss of time, effort, and reputation. For critical software, these failures can also cause major financial losses, injury, or result in the loss of life. Let's consider a software program used to issue airplane tickets online. Suppose the program used to create reservations miscalculates airfare because it erroneously inserts an extra zero in a numeric field used to perform the airfare calculation. In such a situation, if the airfare calculated was uncompetitively high, potential customers would likely refuse to pay the price and take their business elsewhere. This could cause a loss of reputation for the airline along with the lost business. In another instance, suppose a refrigerator is rolled out with an incorrect automatic defrost temperature. In this case the refrigerator might overheat resulting in complete failure of the appliance. This failure may require the company to arrange for a recall or a complete replacement of the appliance for all new customers. This, in turn, would result in a loss of and a negative image for the brand. In more serious cases, faulty software systems may result in injury or loss of life. Consider a software system that miscalculates the quantity of chlorine needed to disinfect the water in a reservoir. Suppose a decimal point is wrongly placed so that the amount of required chlorine is double the permissible amount. This could be fatal for the people using the water. In another instance, a software error in a medical machine could have serious implications for any patient using the machine. This is why it is important to locate and rectify the defects of a software system before it is released for public use.
1244
To eliminate the defects in faulty software, it is important to understand what causes the defects. Faulty software is a result of the errors (or mistakes) made while designing and building it. Most software issues can be divided into three categories. These categories are error An error (or mistake) is an action performed by a person or persons that leads to an incorrect result. This could be an error made by someone using a software system, or an error made by someone in the process of designing and building the software system. defect A defect, also known as a bug or fault, is a flaw in a component or a system that can cause the component or system to fail to perform its required function such as an incorrect statement or data definition. failure A failure is defined as a deviation of the component or system from its expected delivery, service, or result. A defect causes a software system to fail. Failures occur when a software system doesn't perform as expected by the end user, or executes an action which it shouldn't have. It is important to note that not all defects result in a failure – a failure only occurs when code is executed. Errors tend to increase due to stringent timelines, inexperience, careless working habits, complex work situations, or even misinformation. Failures may also be caused by environmental factors including, but not limited to, climate change, pollution, and magnetic fields. Though not all errors translate into failures, errors can lead to a defect, which can, in turn, cause a failure. You can reduce the likelihood of an error occurring in the future by conducting a root cause analysis. Root cause analysis involves trying to track the failure of a system all the way back to its root cause. Understanding and eliminating the root cause of a failure results in software process improvement, which should prevent the recurrence of related failures in the future. This should bring about an overall improvement in the quality of those systems. Root cause analysis is an important part of quality assurance. Root cause analysis can help to anticipate defects in a product, and tackle them at an early stage. Defects can arise in any of the four stages in a product life cycle – analysis, design, development, and implementation. Based on these stages, here are four scenarios to consider.
1245
Graphic The table is composed of four rows and four columns. The four columns are named Analysis, Design, Development, and Implementation. The rows represent requirements one, two, three and four. All four cells of the first row represent a zero-defect delivery scenario. A box at the end of the first row says that in such a scenario, all correct attributes of the product are delivered. In the second row the first two cells represent zero defects while the third and fourth cells represent defects. A box at the end of the second row says that in such a scenario, defects can be corrected. In the third row only the first cell represents zero defect while the second, third and fourth cells represent defects. A box at the end of the third row says that in such a scenario, redesign is required to correct defects. In the fourth all the cells represent defects. A box at the end of the fourth row says that in such a scenario, correction may be impossible. requirement 1 Requirement 1 is an ideal scenario where you have been able to completely comprehend the customer needs. The designer of the product has succeeded in understanding customer needs and designs a product to meet those needs. The product is built in accordance with the design and as a result, the product works as expected and houses all attributes required for flawless execution. requirement 2 In the scenario for requirement 2, all works well until the product is designed. Defects occur while the product is being built or coded. Such defects are ‗internal‘ and can be detected during testing. Such flaws can be easily corrected. requirement 3 In requirement 3, a defect is introduced during product design. Such defects are difficult to correct. To eliminate such a flaw, it becomes imperative to map customer requirements to the design. If the mapping is not conducted, such errors will go undetected during the testing phase and when detected later, they will be difficult to fix as it would require considerable redesigning. requirement 4 Requirement 4 is the most difficult to address. This is caused when customer needs have not been comprehended, or have not been communicated effectively. You might design a flawless product from your understanding of the requirement. The product might also pass all tests but will be rejected because it does not cater to the customer‘s expectations. Such defects appear only during the test or live phases and result in considerable financial loss. Other than understanding the impact of defects at various phases of a product life cycle, it is also important to understand the effects of fixing defects on cost and time.
Graphic
1246
The connection between time and cost is represented by a graph. The X axis of the graph represents time while the Y axis represents cost. There are five boxes aligning the X axis – Analysis, Design, Development, Test, and Use. If you misunderstand a client requirement, and detect the defect during the needs analysis stage, it becomes very easy to correct. A new requirements document could be issued after a discussion with the customer. Again, if the same defect is detected during the design phase of the product, the requirements are mapped to the design and easily corrected with minimal expenditure.
Graphic The passage of time is represented by a dotted line appearing from the beginning of the axes and ending on the block labeled Design. The line is a curved upward line. But if such a defect is detected after the product is launched, the cost to fix the defect could be huge, as it demands high level design and code changes. To lower expenses related to testing and defect fixes, it becomes imperative to eliminate any possible error as soon as it occurs. Therefore, the cost of fixing a defect is directly proportional to the passage of time.
Graphic The dotted line increases further and ends on the block labeled 'Use'. The words, 'The cost of investigating and correcting defects is directly proportional to the increase in time.' appears.
Question Match the definition to the correct software testing term. Options: A.
An action by a user that produces a result from the system that is incorrect.
B.
A flaw in a component or system
C.
A deviation of a component or system from its expected result
Targets: 1. Failure 2. Defect 3. Error
Answer
1247
A failure is defined as a deviation of the component or system from its expected delivery, service or result. A defect is a flaw in a component or a system that can cause the component or system to fail to perform its required function such as an incorrect statement or data definition. An error is an action by a user that produces a result from the system that is incorrect. Correct answer(s): Target 1 = Option C Target 2 = Option B Target 3 = Option A
2. Software testing as a solution Quality is how well a component, system or process is designed, and how well it conforms to the design. Testing helps to improve your confidence that a product meets criteria for quality. You must make sure that the testing has been thorough. Weak tests may provide a false sense of security because they may not uncover defects. This results in defects being uncovered only during execution. Testing is a thorough procedure and tests for both functional attributes Testing for functional attributes ensures that the product performs an expected task. non-functional attributes Testing for non-functional attributes measures how well or fast a task is performed. Testing nonfunctional attributes usually requires a metric, such as time to complete a task. In addition to testing attributes, part of the testing effort is focused on verification and part on validation. Verification evaluates a product to determine that it meets the requirements set out for it. Validation ensures that it meets the needs of users, and that it is fit for the purpose for which it was built. It is also important to maintain focus on the variables of time and cost. The best solution is one that delivers as promised, within the allotted time frame while remaining within budget. You might design and develop a product that fits a client‘s specification, but if it significantly exceeds the client‘s budget the status of the project as a success could be compromised.
1248
For example, if a customer wants a simple scanning application, designing a complex integrated scanning, photocopying, collating and mailing system for them will add needless complexity, cost, and time to what should have been a simple system. Similarly, if the testing phase for the scanner continues for so long that it results in missing the targeted release date of the product, it again results in increased cost and customer dissatisfaction. It is essential to understand the expectations of customers and then create a testing plan. We could sum up customer expectation based on five perceptions of quality that include physical features When the quality of a product is gauged simply by observing its physical features, the customer might only want the superficial attributes of the product to be quantified. usability When the customer gauges quality by assessing the product's usability, and not just by quantitative methods, then simply making sure the product can achieve the task is not enough. The product would not be ready for release until the usability meets their criteria. This could mean performing a task in a given timeframe, or allowing users to use it with minimal training. industry standards Proper software testing can give a quantitative measure of software quality for both functional and non-functional requirements. subjective responses Customer reactions to quality can often be a gauge to their expectations and willingness to believe that the product will meet their needs. The purpose of testing is to eliminate defects and assure a quality product. Complete or exhaustive testing is defined as a test approach in which the test suite comprises all combinations of input values and preconditions. Exhaustive testing, though ideal, is neither practical nor advisable. Which brings us to the question – how much testing is enough? To counter the problem, you should focus your testing efforts on risk and priorities. Exhaustive testing is impossible in all but a very small number of cases. Take for example a text input field. Even if we only consider alphanumeric input, there are 62 possible inputs for each character space available. The number of possible combinations is enormous – 14 million combinations for just 4 character spaces. Clearly exhaustive testing would be impossible. You can provide customer satisfaction only when you deliver a product that satisfies the customer‘s needs and is delivered on time and does not exceed the budget.
1249
A test approach should be devised by comparing the test with the risks, which the customer, the project stakeholders, the project as an entity, and the software is exposed to. What should be considered is the level of risk – technical or business – and time and budget constraints. A risk assessment will decide the amount of testing that is advisable. This amount will vary depending on the level of risk involved. Testing should also supply project stakeholders with requisite information which will help them to make informed decisions about software release for the next stage in development or roll-out to customers.
Summary Software systems are an increasingly common part of life, from business applications to consumer products; yet, most people have experienced software that did not work as expected. Defective software could lead to a loss of money, time, reputation, and could even cause injury or death. A human being can make an error, which results in a defect in the software. When the code is run this can lead to a failure. Proper testing of software can help to reduce the risk of problems occurring during operation and contribute to the quality of software.
1250
What is Software Testing? Learning Objective
After completing this topic, you should be able to
recognize the different goals in testing 1. Testing as a process The main objective of testing is to discover defects. Other objectives include preventing defects, and getting a measure of the quality of software, often to increase confidence. Testing as a process consists of activities before, during, and after actual testing occurs. Testing includes a range of activities that form an integral part of every stage of the software life cycle. You should always try to detect and fix defects during the initial stages of software development as it is a more economical option. If defects are detected during the analysis phase while verifying the requirements of the client, it can save a lot of headaches and potential costs related to finding the defects later in the process. Testing during the requirement phase involves checking the test basis – client requirements and design specifications – against the test design.
Note A test basis includes all software related documentation which specifies the requirements of a customer. If a document can be changed only by a formal amendment procedure, then the test basis is referred to as a frozen test basis. Various types of testing methods are used during each stage of the software life cycle. You can classify testing into static and dynamic testing. When you conduct tests by running a software program it is known as dynamic testing. Dynamic testing, though less cost-effective than static testing, is a more thorough testing procedure than static testing. Dynamic testing involves executing the code for an application and generally requires more effort in terms of cost and time. Static testing includes reviewing software related documentation and source code. This type of testing is more economical than dynamic testing and helps deliver an overview of the quality of the software. The static testing methods would form a part of the activities such as analyzing customer requirements and specifications, creating the design for the software, and writing the instructional manual. Dynamic testing would be required after you have written code for a functional piece of software.
1251
Planning is key to software testing and includes processes that take place before and after test execution. Planning may include activities such as creating a test plan and test strategy. Planning also includes defining entry and exit criteria. After creating a test plan, preparation is the next step in software testing. Preparation involves determining test conditions and designing test cases.
Note A test case is a set of input values, execution preconditions, expected results, and execution post conditions. A test case is developed with a defined objective or test condition. This is done to exercise a particular program path or to verify compliance with a specific requirement. After test execution, you should evaluate the test to check whether it has satisfied all preconditions stated in the test plan. Also, it is important to check whether enough testing has been conducted and if it is appropriate to end the testing process. Different testing viewpoints take different objectives into account. Here are three objectives, along with some information in general terms about when they might be considered. These include finding defects In development testing, which includes component, integration and system testing, the main objective may be to cause as many failures as possible in order to identify defects and fix them as early as possible in the software life cycle. gaining confidence in product quality and providing information Later in the software life cycle during acceptance testing, the main objective may be to verify that the software works as anticipated, and gain confidence that requirements have been met. A similar objective at this phase may be to provide information about the state of the system to stakeholders in order to assess the quality of the software (with no intention of fixing defects). This is done primarily to gauge the risk of releasing the system at a given time. preventing defects In maintenance testing, the main objective may be to ensure that no new defects have been introduced during development of changes. Other than development and acceptance testing, you also need to conduct maintenance and operational testing. Maintenance testing is done on an existing and operational system. It might be required after modifications to the system, or migration. The main objective of operational testing is to check for characteristics such as reliability and availability. Attributes such as reliability and availability surface during the operational use of the software. Reliability is a set of attributes representing the capability of the software to maintain a
1252
level of performance under stated conditions for a stated period of time. Availability refers to whether the product is ready for use whenever required. Testing is an iterative process, and organizations will improve their testing capability and knowledge with time. This will have a positive knock-on effect for future projects in terms of quality and assurance.
Question What stages of a software life cycle would require dynamic testing? Options: 1. Analyzing customer requirements and specifications 2. Creating the detailed design for the software 3. Building functional software
Answer Option 1: Incorrect. Analyzing customer requirements would involve static testing as it would only include studying requirement related documentation. Option 2: Incorrect. Creating detailed design involves static testing. Here you only check the design plan against the requirements stated by the customer. Option 3: Correct. Dynamic testing involves executing the code, and is required to test functional software after it has been developed. Correct answer(s): 3. Building functional software An effective software testing plan should include both testing as well as debugging the software. Debugging is performed as a result of testing. Debugging is performed by developers to uncover where a defect in the code exists and correct it. Debugging can be performed on code or on requirements and specifications. Debugging might not study the effects of a correction on the other components of a system. Testing studies various components of a system with the aim to discover defects and report them; testing doesn't involve fixing the defects. As opposed to debugging, testing also checks the effects of corrections on the other components of a system. A detailed debugging exercise is important to make the software worthy enough to complete the testing phase. It is a waste of time for testers to uncover errors which could have been easily
1253
corrected during debugging. While debugging ensures partial confidence in a product, testing attempts to rigorously study every component of a system and reports defects. Testing also repeats tests to check whether the corrections made by developers are actually effective.
Summary Testing includes a range of activities that form an integral part of every stage of a software life cycle. Testing activities may be both dynamic as well as static. Both dynamic and static methods ensure an effective testing plan. Testing has a number of objectives, Depending on your point of view, the main objective could be finding defects, gaining confidence about the level of quality and providing information, or preventing defects. Debugging is an important activity. While testing detects failures that are caused by defects, debugging involves identifying the cause of a defect, repairing the code, and checking that the defect has been fixed correctly.
1254
Meeting Software Test Objectives Learning Objective
After completing this topic, you should be able to
recognize how software testing meets different test objectives 1. The Objectives of Software Testing The main objective of software testing is to uncover defects and resolve them. Testing can also be conducted to provide information about the software to its stakeholders and increase confidence levels by ensuring the quality of the product. You can perform tests to check certain attributes of the software. For example, you can check for an attribute like Defect Density by dividing the number of design defects found in downstream activities by a measure of product size, such as function points or physical source lines of code. This type of testing will help you measure product reliability and assess the risk of releasing the software. Other than ensuring quality, you should also consider the point of view of end users – customers who purchase the software to use it to complete their daily tasks. These customers wouldn't be interested in the number of defects in the software unless they are affected by them. For example, a word processor might have a few lines of erroneous code, but as long as a user can use it to type documents and format them, the software would qualify as fit for use. Even if an end user qualifies a product as usable, it does not necessary mean that the product is free from defects. Thus, in spite of the end user perspective, your attempt should be to free software of critical defects. While reviewing defects and failures, you may arrive at the root cause of a defect. A root cause analysis should uncover the real reason why an error occurs and help you improve testing processes. The analysis also aids in refining the quality of your test conditions and the general software development process. Users might be logging a number of bugs about a feature which is working properly, but is complex to operate. In such a scenario, you could design a step by step wizard which teaches an individual to use the function. This wizard could be invoked by starting to use the function in question. This in turn, improves the design and subsequent development of the product. Defects tend to gather in single feature or set of features and form a cluster. This might happen because a certain area of the source code is relatively complicated. These areas are known as hot spots, and as a tester you should concentrate on hot spots during risk assessment.
1255
Clusters may also be created when a newly introduced correction results in a chain of defects on various parts of the software. These defects are referred to as knock-on defects. Early review cycles and static tests always prove to be a more economical option and help you identify potential defect clusters. So you should begin testing as early as possible in the software development cycle. Defect clusters have a tendency to change over time, so if the same set of tests is conducted repeatedly, they will fail to discover new defects. This can be referred to as the pesticide paradox. To eliminate the effects of the pesticide paradox, you should continually review existing tests and evolve newer ones to check varied parts of a component and uncover new defects. The pesticide paradox can be illustrated with an animation of a pesticide can. When a test plan is created for the first time, it is successful in uncovering relevant defects and correcting them. But as defect clusters tend to change with time, the same set of tests would be redundant for correcting defects.
Animation The animation shows a can of pesticide being sprayed over a group of bugs which get killed as a result, but the spraying continues in the same area and fails to kill the other surrounding bugs. The pesticide paradox illustrates that an effective testing approach should always integrate new tests. By creating effective static testing techniques and improving the software development cycle, you'll encounter fewer defects during a dynamic test. An improved testing initiative will uncover a greater number of defects. Initial prevention during the Analysis phase reduces the number of defects that may appear while operating the software. Later prevention during the Development phase ensures that you create software with very few defects.
Graphic The image represents a bar graph which shows the reduction of defects as a result of testing over a number of software releases. The Y axis represents the number of defects and has a range of 0 to 100. The axis is marked at regular intervals of 0, 20, 40, 60, 80, and 100. The X axis represents the number of releases and has a range of one to 10. The axis is marked at regular intervals of 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10. The progress of defect prevention is shown by four different groups of bars. These bar groups can be classified to include the total number of defects, represent the total number of defects, defects identified during reviews, defects identified during testing, and failures which occur during live use. All these bar groups are shown as decreasing steadily in size from release 1 to release 10.
1256
As defect clusters are eliminated, your goal should be to change the focus of your testing efforts. Apart from uncovering defects, you should also strive to bring about a general improvement in software design documents and development processes. This in turn will help you lower the costs associated with the testing initiative. In an effort to bring about an improvement in software quality, you should also include debugging as an important activity. Debugging is the process of finding, analyzing, and removing the causes of failures in software. Debugging and testing are varied activities: Debugging Debugging is conducted by programmers. When a tester discovers a defect in the code, a programmer locates the defect and its immediate cause. The programmer then corrects the code and runs it. The tester verifies whether the defect has been fixed in the manner expected. In certain cases, the programmer might test their fixes themselves. However, debugging solves only a single defect in the code, and does not analyze the effect of a fix on other parts of the code. Testing As opposed to debugging, testing shows that defects are present. Testers uncover defects but programmers solve them. Although testing reduces the probability of undiscovered defects remaining in the software it cannot prove that software is defect free.
Question You've created a test plan for a software application. How would you ensure that the tests find and prevent defects if any are present? Options: 1. Create a detailed debugging plan to precede testing 2. Rely only on testing efforts for uncovering defects 3. Standardize a set of tests for every release of the software 4. Continue to develop and add new tests to the plan 5. Incorporate a healthy mix of static and dynamic tests
Answer Option 1: Incorrect. Debugging is performed as a result of testing. Debugging is not a testing activity, but a development activity.
1257
Option 2: Incorrect. It is important to debug software before it actually gets into the testing cycle. This is because programmers detect quite a few obvious defects in the code and fix them immediately. Having such defects remaining in the software would only lead to a waste of time and increase testing related costs. Option 3: Incorrect. Standardizing tests across releases lowers the chances of finding new defects. You might have created a group of tests to discover and prevent a particular kind of defect. After such defects are found and resolved, these tests may become redundant for the rest of the software and may result in the pesticide paradox. Option 4: Correct. It is a good idea to constantly develop and evolve the testing plan. What may have been applicable for a set of defects in Release 1 of the software might not be relevant in Release 4 where there is a possibility of new defects being introduced into the code as a result of changes made previously. Option 5: Correct. A healthy balance of static and dynamic testing should be incorporated in an effective testing plan. Dynamic testing, though less cost-effective than static testing, is a more thorough testing procedure than static testing. Whereas, static testing includes reviewing documentation and source code. Correct answer(s): 4. Continue to develop and add new tests to the plan 5. Incorporate a healthy mix of static and dynamic tests Software testing has three clearly defined objectives:
uncovering defects
gaining confidence about the level of quality and providing information
preventing defects Uncovering defects is the main goal of initial testing. In the early stages of the product development cycle, you can conduct static tests to review specification documents and the initial design of the software. For example, if you're developing accounting software, you can map the initial design to the specifications stated by the customer. This is done to check whether your team has been able to understand client needs. After the design has been reviewed, and development begins, you can execute the code to uncover defects. These tests form part of development testing and include component and integration testing. The objective is to cause as many failures as possible so that a maximum number of defects are uncovered and solved. The objective of testing may not always be to uncover defects but to gain confidence in the product and provide information about its quality.
1258
Acceptance testing attempts to establish confidence in the system. User acceptance testing typically verifies that the system is fit for use by users. Operational acceptance testing confirms that the system is acceptable to system administrators. Contract and regulation acceptance testing is performed against contractual or regulatory criteria. Alpha and beta testing garners feedback from potential or existing customers. Alpha testing is typically performed at the developer‘s site, whereas beta testing is typically done ―in the field‖ at customers‘ sites. The last objective of testing is to uncover new defects which may have been introduced into the software from previous fixes. This testing can be referred to as regression testing. During regression testing, you can ensure that a change made to fix a defect has not affected any other part of the software that it should not have affected.
Question You have completed your first testing cycle for the accounting software. It is important for you to test whether there have been any unwanted changes in the software as a result of a defect fix. What kind of testing would satisfy your testing objective? Options: 1. Development testing 2. Acceptance testing 3. Regression testing 4. Component testing
Answer Option 1: Incorrect. Development testing occurs after a product has been developed and its main aim is to create as many failures as possible to uncover and fix defects. Development testing forms a part of initial testing activities and happens right after the design stage. Regression testing would help you to check whether any unwanted changes have occurred due to a fix. Option 2: Incorrect. Acceptance testing checks whether a product is fit for use and whether the end user will be satisfied with the product. This testing does not eliminate defects but provides information about the quality of the product and ensures whether the product can be released for use. You would need to use regression testing to test for any unwanted changes in the software. Option 3: Correct. Regression testing ensures that no errors have been introduced while changing software. Software might have been changed to fix a defect and that change might have had an adverse effect on some other part of the software. Such effects are undesirable and should be prevented through regression testing. Option 4: Incorrect. Component and integration testing form a part of development testing. Development testing forms a part of initial testing activities and happens right after the design stage. Regression testing would help you to check whether unwanted changes have occurred due to a fix.
1259
Correct answer(s): 3. Regression testing
Summary Testing has three objectives: finding defects, gaining confidence about the level of quality and providing information, and preventing defects. Different viewpoints in testing take different objectives into account. For example, in development testing the main objective may be to cause as many failures as possible so that defects in the software are identified and can be fixed. In acceptance testing, the main objective may be to confirm that the system works as expected. Regression testing checks that no new defects have been introduced during development of changes. Debugging and testing are different. Testing can show failures that are caused by defects. Debugging is the development activity that identifies the cause of a defect, repairs the code, and checks that the defect has been fixed correctly.
1260
General Software Testing Principles Learning Objective
After completing this topic, you should be able to
recognize the fundamental principles in testing 1. General Principles of Software Testing Software testing is based on certain principles that have evolved over the years. These principles guide testers and reduce software related problems. There are seven principles of software testing. Some of these principles are referred to as general software testing principles, whereas the others are referred to as applied software testing principles. General software testing principles provide a standard framework to testers for conducting tests and discovering defects including
testing shows presence of defects – Principle One
exhaustive testing is impossible – Principle Two
confusing an absence of errors with product fit is a fallacy – Principle Three The first principle states that running tests on software will discover defects, but that the absence of defects does not mean that the software is defect free. These tests also decrease the possibility that the software still contains defects, but testing an application doesn't mean that you will be able remove all defects from the software. For example, you might compile a list of tests for testing an online shopping site. You might not be able to discover any functional defects. When the site goes live, however, and is used by a large number of users in varying ways, errors and defects may then come to light. The second principle states that it's impossible to conduct exhaustive testing. Exhaustive testing can be defined as a test approach in which all possible data inputs and preconditions are used. Testing every data input and precondition of software is not feasible because it results in an increase in the cost of testing and also overshoots the time allotted to test the software. Exhaustive testing is possible only when the application under test (AUT) is based on simple logic and requires minimal user input. But when the application uses complex logic and requires a lot of user input, it is impossible to conduct an exhaustive test on the application. So instead of testing every parameter, it becomes important to base your testing efforts on risks and priorities. Consider the example of a web page that prompts users to input information for a children's dance competition. The web page has only a single input field. The field has been designed to
1261
enter the age of a child. The permissible age range for entering the competition is between five and 12 years, so the only criteria you need to test here is whether the age entered falls in the range of five to 12. In such a scenario, you would be easily able to conduct exhaustive testing. But consider the example of web page used to record user‘s delivery addresses and parse them against a zip code database. These fields would have criteria based on numerous permutations and combinations. In such an instance, exhaustive testing would be impossible. The third principle outlines the absence-of-errors fallacy. The fallacy states that although testing might succeed in locating and correcting all possible defects in the software, the software itself might not be fit for use by an end user. This might happen as a result of misinterpreting customer expectations, or as a result of poor usability. For example, you design a word processor that formats, spell checks, and prints documents. The software could pass testing and perform all these functions, but if the customer required language translation and thesaurus functionality then the software does not meet the customer‘s needs. The absence of errors in testing does not mean that the software is suitable for this customer.
Question You have designed an application that calculates wind resistance for concept car 3D models. You have tested the application and it has passed testing. A salesperson selling the product tells a client ―our application has passed our rigorous testing, and so is 100% error free!‖ Which principle of software testing is your salesperson not familiar with? Options: 1. Testing shows presence of defects – Principle One 2. Exhaustive testing is impossible – Principle Two 3. Confusing an absence of errors with product fit is a fallacy – Principle Three
Answer Option 1: Correct. The first principle states that, although testing shows the presence of defects and can also reduce the probability of discovered defects, it can never be proof that the software is defect free. Option 2: Incorrect. While exhaustive testing may have bolstered the salesperson’s claim, principle two says that such testing is (in practical terms) impossible. Option 3: Incorrect. The statement by the salesperson says nothing about product fit. Correct answer(s):
1262
1. Testing shows presence of defects – Principle One
Question You need to design tests for a very basic authentication system used by an airline ticketing system that takes a 10 digit number and validates if it is one of three pre-defined values. You realize that you would need 9,999,999,999 test cases to check every possible combination, and even then it would exclude cases where the user pressed Enter accidentally, used Backspace, or even had a long pause between numbers. Which software testing principle would use to design tests for this software? Options: 1. Testing shows presence of defects – Principle One 2. Exhaustive testing is impossible – Principle Two 3. Confusing an absence of errors with product fit is a fallacy – Principle Three
Answer Option 1: Incorrect. The first principle states that running tests on software prove that defects are present. The test will also decrease the possibility of defects being left over in the software, but testing cannot prove that the software is defect free. Option 2: Correct. The second principle states that it is not feasible to conduct exhaustive tests on software. Exhaustive testing is a test approach that tests all possible permutations of input. The principle that exhaustive testing is an unfeasible practice is more applicable in this scenario. Option 3: Incorrect. The third principle is based on the fact that it is a fallacy to assume that, although no defects are present in the software, it is fit for use. It may happen that a customer requirement is misunderstood resulting in a faulty product, as a result, the application fails to perform the task expected by an end user. You would use principle two to design tests for this software. Correct answer(s): 2. Exhaustive testing is impossible – Principle Two
Question You have designed tests for a system designed to help workers in two geographically distant offices collaborate over the Internet. Unfortunately, all traffic for these offices must travel through a commercial proxy system, and this was not identified by your team during the requirements phase. When you tested the system, it ended up working perfectly in the test environment, but had no support for the office proxy server. Which software testing principle did your team overlook while designing tests?
1263
Options: 1. Testing shows presence of defects – Principle One 2. Exhaustive testing is impossible – Principle Two 3. Confusing an absence of errors with product fit is a fallacy – Principle Three
Answer Option 1: Incorrect. The first principle states that running tests on software will indicate the presence of defects if there are any. The test will also decrease the possibility of defects being left over in the software, but testing is not proof that the software is completely defect free. Option 2: Incorrect. The second principle states that it is impossible to conduct exhaustive testing. Exhaustive testing can be defined as a test approach in which all possible data inputs and preconditions are used. The team overlooked the principle that an absence of errors does not necessarily mean that the software is fit for use. Option 3: Correct. The third principle is based on the fact that, although testing may locate and solve many defects, it may still be unfit for release. A customer requirement may have been misunderstood resulting in a faulty product design and, as a result, the application fails to perform the task expected by an end user. The team did not pay attention to the principle that an error free software is not necessary a usable one. Correct answer(s): 3. Confusing an absence of errors with product fit is a fallacy – Principle Three
Summary There are three general principles that guide testers while devising software testing plans. The first principle states that, although testing shows the presence of defects and can also reduce the probability of discovered defects, it can never be proof that the software is defect free. The second principle discusses that exhaustive testing is both impossible and unfeasible in context to time and cost, and is only possible with instances of an extremely simple logical structure and limited input. The third principle outlines the absence-of-errors fallacy. The fallacy states that although testing might succeed in locating and correcting all possible defects in the software, the software itself might not be fit for use by an end user. This might happen as a result of misinterpreting customer expectations.
1264
Applied Software Testing Principles Learning Objective
After completing this topic, you should be able to
recognize the applied software testing principles 1. Applied Principles of Software Testing You should always base your software testing efforts on certain established principles. Other than the three general principles previously discussed, software testing also follows four applied principles. Applied testing provides a standardized format for creating test plans, and acts as a guide to effective testing. The applied principles of software testing concern the importance of early testing, defect clustering and the pesticide paradox, and state that testing should always be context dependent. The first principle stresses the importance of early testing. This principle states that testing should begin as early as possible in the software development life cycle (SDLC). If defects are detected during the initial stages of the SDLC, they can be corrected with minimum effort in terms of cost and time. Correcting defects during the initial stages prevents defects from cascading onto the Development and Implementation stages. Just before the release of the software, the pressures of a deadline could lead testers to compromise their testing efforts. Software testing should not just be a part of development but should be carried out throughout the SDLC. This eliminates the problems associated with trying to accommodate everything into a single testing effort. If an error is detected during the Analysis phase through static tests, then there is little chance of an error being introduced during the Design phase.
On the other hand, if there is no testing conducted during the Analysis phase, errors can only be discovered during the Implementation phase. During implementation you may realize that there is a serious design issue with the product which will be costly to fix. During the Design phase, if a defect in the code goes undetected, it can result in further defects. Defects can have a tendency to replicate themselves in various parts of the code. A considerable amount of rework is required to correct such defects. If a defect is uncovered during Acceptance testing at the Implementation stage, it means going right back to the Analysis phase to review specification documents. This is important to judge whether you have understood the customer requirements. It can also involve reworking specifications and retesting them resulting in increased costs.
1265
Extensive studies are carried out to study the effect of defects on cost at various stages of the SDLC. Testing objectives differ at every stage of the SDLC. The objective for testing at the Analysis stage is to review the software requirements document, and at the Development phase, the objective is to test the code by executing it. It is impossible to put accurate figures to represent the difference in costs required to correct defects at different stages of the SDLC. The accompanying graph attempts to present a rough idea of the same. The graph represents the cost escalation model. It shows that the later an defect is detected, the more it costs to fix.
Graphic The graph represents a steady increase in the cost of correcting defects at various stages of the SDLC. The X axis shows the various testing stages of the SDLC, namely Requirements, Coding, Program Testing, Acceptance Testing, and Live Use. The Y axis shows the increase in costs from zero dollars to 500,000 dollars. The increase in cost is shown by a curved line which begins at zero dollars and ends at 500,000 dollars on the Y axis and at the Live Use stage on the X axis. The second principle of applied testing is based on the pretext that the defects aren't spread uniformly in the software. During pre-release of the software, a few software modules will display the most number of defects and operational failures. This is referred to as defect clustering. This can be due to
inexperience of the development team
past experiences of the development team
cascading effects of new changes on various parts of the code
volatile code, which is more susceptible to defects
complex logic and structure of a software application Defect clustering is based on the Pareto principle. The Pareto principle states that about 80% of defects will be found in approximately 20% of the modules. You should test components of the software that are more susceptible to defects. However, this doesn't mean that you should disregard less susceptible areas. You should balance your testing efforts so that both types of software components are given due attention. The third applied principle of software testing discusses the Pesticide Paradox. This paradox states that if you continue using the same set of tests over and over again, the tests will cease to uncover bugs. This can happen because during the debugging and testing, the software might have undergone changes. These new changes can no longer be checked using an old test case, so it becomes important to revise existing tests, and develop newer ones which will be
1266
able to uncover more bugs. For example, if a change is introduced in the code, new tests need to be developed to check whether the change has any unwanted effects on other components of the software. This is referred to as regression testing. The same set of regression tests might not be able to uncover defects during production because the testing objective might have changed altogether. The fourth applied principle of software testing states that you need to vary testing efforts depending on the circumstances. For example, you create a plan for a web site which stores confidential medical information. This information can only be viewed by doctors, so the test plan for this web site will be vastly different from a test plan created for a large online bookstore that sells to the general public.
A different plan would be required for various reasons. The bookstore will need to tie in with complex logistical systems based around shipping product in a timely fashion. It may also have many more users than the medical site. The key job of medical site, however, could be viewed as controlling access to the information it houses.
Question During development of an e-commerce web site, the specifications of its checkout system were reviewed. The review revealed a flaw in the logic of the system. As a result, the specification was rectified before the web site specifications were sent for development. Which principle of software testing has the development team based their testing efforts on? Options: 1. Defect clustering – Principle Two 2. Pesticide paradox – Principle Three 3. Early testing – Principle One 4. Testing is context dependent – Principle Four
Answer Option 1: Incorrect. The second principle of applied testing is based on the pretext that the spread of defects is not uniform. And, during pre-release, a few software modules will display the most number of defects and operational failures compared to others. In this scenario, the development team has followed the principle of early testing that states that it is always beneficial, in terms of time and cost, to begin testing in the initial phases of the SDLC. Option 2: Incorrect. The third principle of applied testing discusses the Pesticide Paradox. The principle states that if you continue using the same set of tests over and over again, the tests will cease to uncover bugs. The development team has based their testing efforts on the principle that
1267
effective testing always begins during the initial phase of the SDLC. This corrects defects during Analysis and Design and prevents them from appearing during development and implementation. Option 3: Correct. The first principle of applied testing stresses the importance of early testing. The principle states that testing should begin as early as possible in the SDLC. Early testing saves efforts in context to both time and cost. Option 4: Incorrect. The fourth principle of applied testing states that testing efforts will vary in different circumstances. For example, testing for a e-commerce site will be very different from testing for safety-critical software. In this scenario, the development team has followed the principle of early testing that states that it is always beneficial, in terms of time and cost, to begin testing in the initial phases of the SDLC. Correct answer(s): 3. Early testing – Principle One
Question Your organization is developing a content management system. This system uses separate modules to run most of its core functions. During component testing, you discovered that the user authentication module has a high number of defects. The same module also faced problems during integration testing. Which principle of software testing is proved by the above scenario? Options: 1. Defect clustering – Principle Two 2. Early testing – Principle One 3. Pesticide paradox – Principle Three 4. Testing is context dependent – Principle Four
Answer Option 1: Correct. The first applied principle stresses the fact that defects are not spread uniformly in the software. Some components of the software display more defects and operational failures compared to others. Option 2: Incorrect. The first applied principle is based on the fact that you should start testing from the initial phases of the SDLC. As the initial phases primarily involve static tests, early testing saves efforts in context to both time and cost. This scenario illustrates the concept of defect clustering which indicates that certain software modules are more susceptible to defects than others. Option 3: Incorrect. The third applied principle discusses the Pesticide Paradox which states that if you continue using the same set of tests over and over again, the tests will cease to uncover bugs. This scenario illustrates the concept of defect clustering which indicates that certain software
1268
modules are more susceptible to defects than others. More susceptible modules need to be resolved earlier than less susceptible modules. Option 4: Incorrect. The fourth applied principle states that you need to change your testing efforts based on different circumstances. For example, testing for a gaming site will be very different from testing for an online store selling music CD's. This scenario illustrates the concept of defect clustering which indicates that certain software modules are more susceptible to defects than others. Correct answer(s): 1. Defect clustering – Principle Two
Question You have a comprehensive set of tests developed for a spreadsheet program developed by your company and you apply these tests to each successive version of the program that is released. In the most recent version very few defects were revealed by your tests and you take this to mean that the software is now very refined. Which principle of software testing might prove your perception wrong? Options: 1. Early testing – Principle One 2. Defect clustering – Principle Two 3. Pesticide paradox – Principle Three 4. Testing is context dependent – Principle Four
Answer Option 1: Incorrect. The first principle of applied testing discusses the importance of early testing. This principle states that testing should begin as early as possible in the SDLC. During the initial phases of the SDLC, static tests are used to correct defects. Static tests are more economical than dynamic tests required to resolve errors in the later stages of the SDLC. The pesticide paradox will prove that your perception of using standardized tests to resolve defects is an incorrect approach to correct new bugs. Option 2: Incorrect. The second principle of applied testing is based on the pretext that the spread of defects is not uniform. And, during pre-release, a few software modules will display the most number of defects and operational failures compared to others. You should have paid attention to the pesticide paradox that states that you should always revise your testing efforts to resolve new defects.
1269
Option 3: Correct. The third principle of applied testing discusses the Pesticide Paradox which states that if you continue using the same set of tests over and over again, the tests will cease to uncover bugs. Option 4: Incorrect. The fourth principle of applied testing states that testing efforts will vary in different circumstances. For example testing for an e-commerce site will be very different from testing for safety-critical software. The pesticide paradox will prove that your perception, that using standardized tests to resolve defects, is an incorrect approach to correct new bugs. Correct answer(s): 3. Pesticide paradox – Principle Three
Question Your company produces noncritical office software. A new tester has recently joined your team. This tester had previous experience in testing military systems where failures would be particularly hazardous. In his first week, the new tester discovers a fair number of defects, but he seems much slower than your other testers because he insists on fully exercising any code that he is given. Which principle of software testing might this new employee benefit from learning? Options: 1. Early testing – Principle One 2. Defect clustering – Principle Two 3. Testing is context dependent – Principle Four 4. Pesticide paradox – Principle Three
Answer Option 1: Incorrect. The first principle of applied testing stresses on the importance of early testing. This principle states that testing should begin as early as possible in the SDLC. Early testing saves efforts in context to both time and cost. Testing efforts are always relevant to the context they are being used in. As this tester is used to testing complicated logic and structure, he would tend to waste a lot more time for testing simple software. Option 2: Incorrect. The second principle of applied testing is based on the pretext that the spread of defects is not uniform. And, during pre-release, a few software modules will display the most number of defects and operational failures compared to others. This scenario highlights the principle that states that testing is always context dependent. This tester is suitable for testing complicated software and would not be suitable to test software that uses simple logic. Option 3: Correct. The fourth principle of applied testing states that testing efforts will vary in different circumstances. For example, testing for an e-commerce site will be very different from
1270
testing for safety-critical software, so using this tester in a simple testing environment would be a waste of time and cost. Option 4: Incorrect. The third principle of applied testing discusses the Pesticide Paradox which states that if you continue using the same set of tests over and over again, the tests will cease to uncover bugs. Testing efforts are always relevant to the context they are being used in. As this tester is used to testing complicated logic and structure, he would tend to waste a lot more time for testing simple software. Correct answer(s): 3. Testing is context dependent – Principle Four
Summary There are four applied principles that guide testers while devising software testing plans. The first principle stresses that testing activities should start as early as possible in the software or system development life cycle. Principle two shows that a small number of modules contain most of the defects discovered during pre-release testing. The third and fourth principles outline the Pesticide Paradox, and state that testing is context dependent.
1271
The Importance of Software Testing and Mitigating Harm Learning Objective
After completing this topic, you should be able to
recognize the fundamentals of software testing Exercise Overview You need to train the new testing team about how software testing improves quality, how early testing proves economical, and how testing principles apply to scenarios presented. You need to train the team on:
how testing can help improve the quality of software
the importance of early testing
how testing efforts differ depending on context
Recognizing how testing improves quality You're a test manager in an organization. A development team within your organization has created software that manages railway line switches to control railway tracks and the train schedule. The scenario involves very real safety concerns. If the software fails, it could result in hundreds of deaths and millions of dollars of damage.
Question The success of the software is important as the slightest defect might end up putting the lives of millions at risk. What should the testing team focus their testing efforts on? Options: 1. Functional attributes of the software 2. Functional and non-functional attributes of the software 3. Exhaustive testing 4. Risk assessment and management
Answer Option 1: Incorrect. Although testing for functional attributes ensures that the product performs an expected task seamlessly, it is also important to test non-functional attributes to ensure that the task
1272
is completed in the least amount of time and effort. You would need to test for non-functional attributes too. Option 2: Correct. Testing for functional attributes ensures that the product performs an expected task. Testing for non-functional attributes measures how well or fast a task is performed. Testing non-functional attributes usually requires a metric, such as time to complete a task. Option 3: Incorrect. Exhaustive testing checks all combinations of input values and preconditions. Exhaustive testing, although ideal, is neither practical nor advisable. It would be a good idea to concentrate on risk assessment, and the parameters of validation and verification. Option 4: Correct. A test approach should be devised by juxtaposing the test with the risks which the customer, the project stakeholders, the project as an entity, and the software is exposed to. Correct answer(s): 2. Functional and non-functional attributes of the software 4. Risk assessment and management
Understanding early testing Early testing and defect removal is usually much less expensive than repairs later in development. This is especially true in a complex physical system that may need to be taken offline for testing once it is constructed.
Question You plan to brief your team on the testing plan they need to create. At which stage of the SDLC would you recommend testing to begin? Options: 1. Design 2. Development 3. Analysis 4. Implementation
Answer Option 1: Incorrect. Testing that begins at the Design stage only tests the design of the software and does not check software documentation. Although defects detected at the Design stage can be easily solved, ideally, testing should always begin at the Analysis stage.
1273
Option 2: Incorrect. Testing that begins at the Development stage, might require changes in code. Although not very difficult to implement, defects of the Design and Analysis stages might pass unnoticed. Thus, ideally, testing should always begin at the Analysis stage. Option 3: Correct. Testing should ideally begin at the Analysis stage. If all clarifications are answered at this stage, there would be a very slim chance of a defect cascading onto the later stages of the SDLC, thus saving time and money. Option 4: Incorrect. Defects detected during Implementation are very difficult to correct and involve a huge amount of investment both in terms of money and time. It could also mean going right back to the Analysis stage and recreating the product. You should always begin testing during the Analysis stage. Correct answer(s): 3. Analysis
Question Static and dynamic tests are used at various stages of the SDLC. You need to inform the team on what methods they need to utilize at what stage. Match each testing type with its relevant action. Options: A. B.
Static
Dynamic
Targets: 1. Analyzing client requirement documents 2. Reviewing software design documents 3. Reviewing source code of the software 4. Executing the code of the software
Answer Static methods comprise reviewing software related documentation. Static tests occur at the Analysis and Design stages of the SDLC. Dynamic testing includes running the code of the software. Static methods comprise analyzing software related documentation, like specification documents and client requirements. Dynamic testing includes running the code of the software.
1274
Static methods comprise reviewing software related documentation and source code. The code is not executed as is done with dynamic testing. Reviewing code generally happens during the Development stage of testing. Dynamic testing happens during Development and Implementation when the testing team executes the code of the software to check whether the product is performing as expected. Static testing is generally comprised of reviewing software related documentation and source code. Correct answer(s): Target 1 = Option A Target 2 = Option A Target 3 = Option A Target 4 = Option B
Explaining testing principles You want to inform the team that software testing is based on certain principles.
Question The spread of defects in software is not uniform and a few software modules will display the most number of defects. Which principle of software testing is this? Options: 1. Defect clustering 2. Pesticide paradox 3. Exhaustive testing is impossible
Answer Option 1: Correct. Defect clustering is based on the Pareto principle. The Pareto principle states that about 80% of defects will be found in approximately 20% of the modules. Option 2: Incorrect. The Pesticide Paradox states that if you continue using the same set of tests over and over again, the tests will cease to uncover bugs. Option 3: Incorrect. This principle states that exhaustive testing is rarely achievable in practice.
1275
Correct answer(s): 1. Defect clustering
Question You have created a test plan for the first release of audio recording software. You use the same plan to test the software for its second and last releases. The tests reveal very few defects and you decide that the software can be released without further rounds of testing. After the release, some bugs come to light. Awareness of which principle may have reduced the number and severity of these bugs? Options: 1. Early testing 2. Defect clustering 3. Pesticide paradox 4. Testing is context dependent
Answer Option 1: Incorrect. This principle states that testing should begin as early as possible in the SDLC. Early testing saves efforts in context to both time and cost. The principle which outlines the concept of the pesticide paradox is more applicable in this scenario. Option 2: Incorrect. Defect clustering states that the spread of defects in software is not uniform and a few software modules will display the most number of defects. In this case, the relevant principle is the pesticide paradox. Option 3: Correct. The Pesticide Paradox states that if you do not develop new tests and attempt to use a standard set of tests for all release of software, the tests will cease to uncover bugs. Option 4: Incorrect. Testing effort varies in different circumstances. For example, testing for an online shopping store site will be very different from testing for safety-critical software. You are violating the principle that discusses the concept of the pesticide paradox. Correct answer(s): 3. Pesticide paradox
Question During the development of an online bookstore, the specifications of the search functionality of the software were reviewed. During these reviews, a defect in the design logic and functionality of the
1276
software was discovered. This defect was corrected in the specification and the software was sent for development. If these defects had made it though to a later stage of the software lifecycle, they could have been more time consuming and costly to remove. Which principle of software testing did the development team follow? Options: 1. Early testing 2. Defect clustering 3. Pesticide paradox 4. Testing is context dependent
Answer Option 1: Correct. This principle states that testing should begin as early as possible in the SDLC. Early testing saves efforts in context to both time and cost as it involves only static testing techniques. Option 2: Incorrect. The spread of defects in software is not uniform. A few software components will always display more defects and operational failures compared to others. The principle of early testing in the SDLC is more applicable in this scenario. Option 3: Incorrect. The Pesticide Paradox stresses that if you continue using the same set of tests over and over again, the tests will cease to uncover bugs. The test team has followed the principle of early testing in this scenario. Option 4: Incorrect. Testing efforts will vary in different circumstances. For example, testing for a content management system will be very different from testing for an online store that sells medical equipment. The test team has followed the principle of early testing in this scenario. Correct answer(s): 1. Early testing
1277
The Fundamental Software Test Process Learning Objectives
After completing this topic, you should be able to
recognize the test process in a given project
identify the component steps in the test process 1. The software testing process Once a software application is developed, it is important to test it and verify whether the software has met the purpose and the objective for which it was developed. The more rigorous the test process, the better the product quality. Although testing rigor may vary across software products – products with fewer risks may not require as much testing as a product with higher risks – the software testing process remains the same. This process includes distinct phases where one phase follows the other and where phases are interdependent on one another.
Note Although the process is depicted here as strictly linear, there will be times when you need to go back to an earlier task, or run tasks in parallel. There are five fundamental phases in the software testing process.
Graphic Description of the software testing process flow chart: The five phases of the software testing process begins with test planning and control as the first phase. It then moves to the second phase – test analysis and design – and then the test implementation and execution phase. This is followed by the evaluating exit criteria and reporting phase, with the process finally ending with the test closure activities phase. Description ends. Test planning and control In the test planning phase, you establish the need or mission of testing. This helps you focus on what needs to be tested, the scope of testing, and what defines the exit or completion of the test. These details are outlined in the test plan – a deliverable of this phase. The test plan also specifies the schedule of activities, resources required for the testing process,
1278
and the test environment. Additionally, it also lists any risks that might affect test execution and documents contingency plans. Test control compares actual progress against the test plan. Reports are the deliverable of test control which include deviations from the plan. Test control involves taking action to meet project objectives, and is an ongoing activity during the project. Test analysis and design In the test analysis and design phase, test objectives determined during planning are converted into plausible test conditions and test cases. During this phase, you review the test basis (including requirements, architecture, design and interfaces), and evaluate the testability of the test basis and test objects. You also identify and prioritize test conditions based on the analysis of test items, the specification, behaviour and structure. In this phase, you also design test cases and prioritize them, identify the test data necessary to support the test conditions and test cases, and design the test environment set-up and identify the tools and infrastructure which will be required. Test Implementation and execution The test implementation and execution phase is where test procedures, or scripts, are specified, the test environment set up, and tests are run. Test implementation includes developing and prioritizing test cases and procedures, creating test data and creating test suites from the test procedures to ensure efficient test execution. You should also verify that the test environment is set up properly. Test execution is the phase where you execute tests – manually or by using execution tools – in the sequence planned. You also log the outcome of test execution, record what software and version is under test, and what test tools and testware are being used. You also compare actual results with expected results and report any discrepancies as incidents. These incidents will be analysed in order to establish their cause – was it a defect in the software, a defect in the test data, or maybe a mistake in the test execution? Finally, test activities are repeated for any discrepancy. In the case of confirmation testing, you would re-execute a test that previously failed to confirm a fix. In the case of regression testing, you might execute a corrected test in order to ensure that a defect has not been introduced into an unchanged area of software. Evaluating exit criteria and reporting In the exit criteria evaluation and reporting phase, you analyze the test execution results against the objectives defined in the analysis and design phase. You determine if the exit criteria – conditions determined for test completion – are met. You then analyze if more tests are required, or if the exit criteria set should be changed. You also prepare a test summary report for the stakeholders. Test closure activities Test closure activities – the final stage of the testing process – require you to consolidate and document data from the completed phases of testing.
1279
This phase involves checking deliverables and ensuring that all test incidents are closed. During this phase, testware – scripts, test environment, and other test infrastructure – are archived for future reference before the product is handed over to maintenance testers for regression testing. The five-step software testing process ensures that the developed software meets the stated objectives and mitigates any risks of failures that may occur due to the defects in the software. Although this process follows a sequence of activities, it is not rigid. Some steps in the process are iterative and can be conducted in parallel for rigorous and extensive testing. For example, suppose you completed the planning phase for a software application and have begun designing test activities for it. A change in the market requirements for the software is reported, which in turn modifies stakeholder requirements and project objectives. In this case, you need to revisit the planning stage after the design phase. Similarly, you also iterate the analysis phase, after test implementation and exit criteria evaluation, if there are changes in the test plan.
Graphic In this depiction of the software testing process, the test planning and control phase iterates after the test analysis and design phase, the test analysis and design phase iterates after the test implementation and execution and evaluating exit criteria and reporting phases.
Question Sequence the phases constituting the fundamental software testing process from start to finish. Options: A.
Analyze test goals and prepare a test plan B.
Analyze test conditions and architecture and then create test cases
C.
Implement test suites and report test incidents
D.
Evaluate the exit criteria and prepare test summary
E.
Archive testware and evaluate test results
Answer Correct answer(s): Analyze test goals and prepare a test plan is ranked as the first step of the software testing process. In the software testing process, the first phase is to analyze the test goals, objectives, and the risks, and plan how testing will proceed. This phase is called test planning and control.
1280
Analyze test conditions and architecture and then create test cases is ranked as the second step of the software testing process. The second phase of the software testing process is where testing objectives are converted into test conditions and cases. Implement test suites and report test incidents is ranked as the third step of the software testing process. Implementing test suites and executing them is the third phase. Implementation activities include creating test scripts. Execution is where you run tests and record incidents. Evaluate the exit criteria and prepare test summary is ranked as the fourth step of the software testing process. The fourth stage of the software testing process is to evaluate the exit or test completion criteria defined during planning. You validate these criteria against the actual test results documenting them in a test summary report. Archive testware and evaluate test results is ranked as the fifth and final step of the software testing process. Test closure is the final phase and involves analyzing test results for future projects and archiving testware for maintenance testers. Suppose you're a test manager in an organization developing an online auction web site for automobiles. You want to test the developed software to evaluate its effectiveness, and to check if it meets the stated expectations. Applying the fundamental software test process, you begin with the planning phase. In this phase, you ensure that you understand the goals and objectives of the stakeholders – your company, the clients, and the end-users. The objective of the auction web site is to provide an online portal that allows users to log in and place bids on automobiles, with the web site allowing the highest bidder to proceed with the transaction. Because the transaction is financial, user privacy and security is paramount. These objectives help you identify what elements are critical to the web site and let you decide areas that need to be tested. In this example, the testing focus will be ensuring that only authorized users with valid logins can perform a transaction, checking if users can place bids, ensuring that the web site allows only the highest bidder to access the transaction page, and determining that a secure connection is provided for complete anonymity during transactions. You can then continually monitor these objectives throughout the testing process. During the planning phase, you also determine the kinds of tests to run and the people who will be involved. You also create a schedule and then define the exit criteria based on the areas to be tested. For your auction web page, you will set 80% statement coverage throughout the web auction system and 100% branch coverage for areas of code relating to financial transactions as the exit criteria against which test results are validated. Testing is deemed complete only if the exit criteria are met.
1281
With a test plan with exit criteria and schedules in place, you proceed to the analysis and design phase, where you review the test basis and identify test conditions Your first task in the analysis phase is to review the test basis and identify test conditions. While reviewing the test basis, you analyze risks, requirements, and specifications. Based on these, you identify test conditions for your software. In the auction web page example, you want users to be able to view automobile models and place bids without being impacted by large volumes of site traffic. These become your test conditions, where you can check if the web page functions as expected during hours of peak network traffic. design tests and evaluate testability Based on the test conditions, you design the tests and evaluate the testability of the component – the auction web page, in this example. If a requirement for the auction web page is that the web page should respond quickly, you must define 'quickly' and set parameters for how quick you want the page to respond – five or ten seconds, for example. Accordingly, your test environment will include resources that allow this test to occur. Once tests are designed and a strategy put in place, you develop and execute test cases. To do this, you create test procedures – instructions for test cases. These procedures focus on checking elements you defined as critical earlier. These elements could include, for example, whether you can log into the site, whether an automobile name entered in the search string displays appropriate images, and whether you're able to place a bid on the car. These details are mentioned in the test cases. After creating test procedures and cases, you create test suites, which are logical collections of test procedures. For your auction web page, the collection of test cases that check whether users are able to log in becomes one test suite. In addition, you also ensure that the test environment is set up, and use it to run possible trial tests to measure the efficiency of the environment. In the test execution phase, you execute the test suites and document test outcome logs. While documenting, you record the versions of the software under test, your test tools, and testware. You also compare actual results to expected results and, where there are discrepancies, record incidents. Suppose currency is not displaying correctly in your web page during testing. As a result, transactions become tedious for a user, who is unable to view the amount accurately. This instance is reported as an incident during the execution phase.
1282
In this phase, incidents or discrepancies reported should be fixed, and test activities should be repeated for each discrepancy to confirm that the fixes function correctly and haven't altered the program in other ways. This procedure may be repeated until test results display expected outcomes. After running the test suites, you need to determine whether the exit criteria set during the planning phase are met. This is the exit criteria evaluation and reporting phase where you check logs of the test outcome against the exit criteria to determine if they are met. Wherever a criterion is not met, depending on how critical it is, you may revise it before re-running the tests. For example, in the auction web page, you can revise the criteria for the 80% statement coverage to 75% and run tests again. But you would not revise the 100% financial coverage, because it is directly connected to ensuring a secure finance system. In this case, you devise further tests to check 100% financial coverage.
Note Testing is considered complete when exit criteria are met. Once exit criteria are met, you can create a test summary report. This report informs the stakeholders about the extent of testing undertaken and its outcomes. In the final stage of the testing process – test closure – you deliver the tested software and document whether incident reports are resolved or deferred. Categorizing incidents is important, because deferred incidents might become requests for a future version of the software. For example, in your auction web page, deep bookmarking might not be available for individual cars in the version, because it is not critical for successful implementation of the application. This feature, however, is user friendly and could be made available in the next version. In this phase, you also archive the scripts and details of the test environment so that it is readily available for use at a later stage. As a sign-off, you hand over the tested software to the maintenance team in charge of deploying and maintaining the web auction page. Lastly, you document any lessons learned during testing, in an overall project evaluation report, so that these lessons can be applied to future projects.
Question As a test engineer, you want to test the software for managing payroll services in your organization. The focus of this payroll portal is to maintain employee privacy and security of transactions. Rank the tasks in the order you would execute them in the software testing process. Options: A.
Identify unauthorized user access as a security risk B.
Specify as a test condition that only users with authorized user names and passwords can log on
1283
C.
Create a test procedure for the ability to log into the payroll portal
D.
Check the exit criteria defined for security of transactions against the test outcome
E.
Archive testware and prepare a project evaluation report
Answer Correct answer(s): Identify unauthorized user access as a security risk is ranked as the first step in testing the software for managing the payroll service. Understanding the goals of your project and identifying the risks belong to the planning phase of the testing process. This also helps you determine the tests required to meet the test objective. Specify as a test condition that only users with authorized user names and passwords can log on is ranked as the second step in testing the software for managing the payroll service. Setting up test conditions is done in the analysis and design phase. You also proceed to design the test cases, and identify test data required to support those cases. Create a test procedure for the ability to log into the payroll portal is ranked as the third step in testing the software for managing the payroll service. You create test procedures and execute test suites during the implementation and execution phase of the process. In this phase, you also repeat the test activities designed for fixed defects, to validate these fixes. Check the exit criteria defined for security of transactions against the test outcome is ranked as the fourth step in testing the software for managing the payroll service. Evaluating the exit criteria is the fourth phase of the testing process. You compare the actual results against the estimated results during this phase. You do this using the logs of the test execution. Archive testware and prepare a project evaluation report is ranked as the final step in testing the software for managing the payroll service. During the test closure phase, you archive the testware for future test components and hand it over to the test maintenance team. In addition, you prepare a test summary report.
Summary Software testing is an extensive process that includes a number of phases and tasks. This process includes five fundamental phases – test planning and control, analysis and test design, test execution and implementation, exit criteria evaluation, and test closure activities. Each of these phases includes specific tasks. Planning requires you to define the test objectives. Control compares actual progress with the test plan on an ongoing basis, and takes action where necessary. Analysis and design is where testing objectives are converted into test conditions and cases. Implementation includes designing test scripts, and execution is where the test scripts are executed. Evaluating exit criteria and reporting is where test execution is
1284
assessed against the objectives. Test closure activities include creating a test summary report and archiving testware.
1285
Exit Criteria and Test Closure Activities Learning Objective
After completing this topic, you should be able to
identify the two final steps of the test process in a given scenario 1. Exit criteria and test closure The objective of testing is to ensure that a quality product that meets the purpose for which it is created is released. Based on this objective, test plans are created and exit criteria are defined, which further impacts how tests are designed and executed. Only when these exit criteria are met is testing considered to be complete. Evaluating exit criteria is an important task or phase in the test process. Exit criteria are a set of business-driven conditions that determine the customer-ship or deployment decision for a software application. Exit criteria are defined during the planning phase of the test process. These criteria act as a set of checkpoints that provide focus on what you need to track during testing and also what you should validate your test outcome against. For example, you plan to test a web application that helps you book airline tickets. You define exit criteria based on the critical factors of the application that need to be fully tested. A critical element of this application is to test its functionality – for example, selecting a flight and being able to enter the number of tickets to book in that flight. So you set an exit criterion that checks 70% of the application functionality with a certain rigor – no critical defects reported for a particular function, for example. This criterion helps determine what needs to be evaluated after testing. The testing is considered complete only if this criterion is met. Meaningful exit criteria that are measurable and achievable help
ensure test efficiency and effectiveness
prioritize and execute testing activities
evaluate current activities in the testing process and decide steps for further action
suggest corrective measures for incomplete and faulty efforts
identify plausible risks for your test project
1286
Evaluating exit criteria lets you check whether the conditions to complete the testing process are met. Evaluation requires you to analyze the test results of a completed test suite against the objectives and the criteria set during the planning phase. In exit criteria evaluation, you analyze different types of criteria – all of which are part of the exit criteria – such as the coverage criteria Coverage criteria help you decide test cases that must be included during the exit criteria evaluation process. For example, when testing an application that helps you book air tickets; your coverage criteria could be to test the functionality of the application, which enables the user to select the required airline tickets and the mode of payment. You will not cover features that process credit card numbers in this test suite. acceptance criteria The acceptance criteria enable you to check whether the software under testing has passed or failed in the overall process. For this test suite example, the acceptance criteria could be to pass the application only when it allows you to select the required flight service and the date of travel. The exit criteria for this process could specify that testing is complete only when you have completed every step of the ticket-booking process and prepared the test report. If you're checking a spreadsheet application, you might set a number of exit criteria statements to check if testing is complete. The following serve as an example and should not be taken as complete, accurate or exhaustive:
final draft of the product documentation, including the Contents and Help files, are reviewed, tested in QA, and approved by the core team
help files are launched with the print option when the required menu option is selected
menu options available on the UI of the spreadsheet are enabled and highlighted when rolled over
spreadsheet runs on all supported hardware and software configurations, as mentioned in the documentation files
defects of all priorities are fixed and closed during regression testing
navigation across different instances of the spreadsheet is enabled In addition to analyzing the exit criteria, the exit criteria evaluation phase includes a number of tasks and activities of which three are particularly important.
1287
Check test logs When you begin exit criteria evaluation for your test suite, you collect and check the test logs acquired from the test implementation and execution phase. You check these logs against the exit criteria set for your test suite during the planning phase. You then identify evidence for every test executed and the defects that are logged. Defects are analyzed to distinguish between those that are resolved and those yet to be confirmed or fixed. Estimate additional test requirements Depending on the test log analysis, you can estimate if additional tests are required in a test suite for a more thorough checking. You may decide this based on the number and the criticality of defects logged. At times, you may even revise exit criteria. Additional tests are required when the designed tests do not meet the required test coverage. You change the exit criteria only when the business or technical risks of the software under testing changes. However, these decisions require the approval of stakeholders. Prepare test summary report After analyzing the test logs and assessing if more tests are required, you prepare a summary report for the stakeholders of the project. This document communicates the test outcome to your stakeholders, which enables them to make critical decisions about the software under testing. This document summarizes testing activities and an evaluation of the test results against the exit criteria. After you evaluate the exit criteria for your testing process, you proceed to the final phase of the testing life-cycle – test closure. This phase ensures the completion of all test activities and the sign-off of the end product. Once you reach this phase, you're ready to deliver the software to your client.
Note In tests executed for research purposes, you close testing as soon as you've gathered the required information, because complete testing could exceed the scope of your requirements. Test closure activities include checking deliverables Test closure is initiated by checking planned deliverables against the actual deliverables meant for the client. This helps check if incident reports are either resolved or deferred according to the planned deliverables. Planned deliverables specify if an identified incident is to be fixed in the current version of the software. For example, in the spreadsheet application, an exit criterion is compatibility with third-party products. If the spreadsheet is incompatible with a specific third-party product, then you check your planned deliverable to see if this compatibility is required. If not, you
1288
can defer fixing this issue, documenting it so that it's addressed in the future versions of the application. archiving testware After checking deliverables, you collate and archive testware – test scripts, test environment components, and any tools used in the test infrastructure. You archive testware so that the same components can be reused during maintenance testing, making the process time- and costeffective. Archiving also helps you compare test results between the different versions of the software. Suppose an earlier version of the spreadsheet application had been tested by you and the test logs of that test are available from the test library. You can compare these with the current test logs to check if any errors are repeated. You can then archive your test logs for future use. submitting testware to maintenance team Submitting testware to the maintenance team is an important activity of test closure. The maintenance team – independent of the test team – supports the software and is responsible for defect resolution after the application goes live. Archived testware in the test library helps maintenance testers reuse the same test scripts and environment. evaluating the overall test process Finally, you evaluate the overall process that was executed to test the software. This helps identify and assess lessons learned from the test process, letting you improve future test processes.
Question As a development tester, you've recently completed multiple test suites for a word processing application to check if 85% of statement coverage is tested. You also checked to ensure that userdefined words could be added to the dictionary. Having implemented the test suites and generated the test logs, what activities would you perform as the final steps of the test process? Options: 1. Check if the functionality of the word processor is tested up to the required degree of test coverage as planned 2. Create exit criteria to check that 85% statements are covered and words to the existing dictionary can be added without errors 3. Validate test logs against the exit criteria and identify if further tests are required
Answer Option 1: Correct. You check the actual deliverable against the planned deliverable during test closure phase before delivering the tested software to the client. At this stage, you ensure that all incident reports and defects are resolved.
1289
Option 2: Incorrect. You create the exit criteria that you require for testing, during the initial planning phase. You would check these criteria against the test outcome, analyze whether they are met, and if met, exit testing. Option 3: Correct. Once test logs are generated, it is important to validate them to evaluate exit criteria. At this stage, if you determine that exit criteria are not met, you can identify further tests to cover the exit criteria. Correct answer(s): 1. Check if the functionality of the word processor is tested up to the required degree of test coverage as planned 3. Validate test logs against the exit criteria and identify if further tests are required
Summary In the software testing process, the last two phases – evaluating exit criteria and reporting and test closure – help you assess whether testing is complete and document the test results and the scripts for future use. Evaluating exit criteria and reporting requires you to check the test logs acquired from test execution and then compare them against the exit criteria set during test planning. In addition, you also analyze if any further tests are required and prepare the test summary report. During test closure, you check the actual deliverables against the planned deliverables, before you deliver the software to the client. You then archive testware in the test library, which is used by the maintenance testers. Finally, you analyze and suggest improvements to the overall test process documenting them in the project evaluation report.
1290
The Psychology of Software Testing Learning Objectives
After completing this topic, you should be able to
identify levels of independence in testing
recognize the role of communication in the psychology of software testing 1. Levels of independence in testing Among the many factors that affect software testing, psychological factors are important, because they influence the success of the testing activity. How an individual identifies and reports defects, how evidence is gathered and shared, and how results are communicated and interpreted, are all factors determined by the psychological make up of individuals involved.
The psychological make up of a developer differs from that of a tester, and consequently influences the process of testing. Testing requires an objective mindset. This objectivity exists only if the person testing the product is not personally attached to the product. For example, when a developer creates an application, he constructively resolves the issues in the design to ensure that the end product meets the required standards. But while testing the product, the developer may miss defects because he may approach the product – given the effort he put in and the personal involvement in developing the product – as one without defects. But a tester, who is not involved in software development, stays detached from the product being tested. This helps him or her objectively assess the product and find defects because he or she consciously looks for them during testing. Testing activities should be assigned to someone who was not part of the software development process. This ensures separation of responsibilities between a tester and a developer, called independence. Independence in software testing introduces objectivity and adds value. It defines the success of the software testing process by preventing author-induced biases from creeping in and allowing valid defects to be reported. You can implement different levels of testing independence at different stages of the development life cycle depending on the nature of the testing and reviewing activities in that stage.
1291
There are four basic levels of independence – graded from high to low – in software testing. The grade of independence depends on the degree of responsibilities shared between the members of the testing and the development teams. Software developer When the developer who created the software tests his own software, the level of testing independence obtained is minimal. There is no actual separation of duties, because the tester and the developer are the same person. This first level of independence is the lowest in the order of independence and can be employed for cursory reviews or when the project is considered low risk. For example, when you program a word-processing application, you can do a self-review of the product for any design-based defects easily identifiable by you. But this level of independence would not suffice for in-depth analysis of the software – for example, to check functionality defects or third-party application support. Peer reviewer The second level of testing independence is when a peer within the team reviews the product or application. This person brings a fresh perspective to the testing and tends to be more objective than the product author. Typically, peers are members from the same development team, who may be in charge of developing a different application or different portions of the same application. Internal tester For a higher level of testing independence with improved objectivity, you can employ an internal tester from a different functional group or a testing team. For example, you can ask a qualified tester from the QA team in your organization to review your software. This is the preferred and most common level of testing independence employed by most organizations. It is cost effective, because you employ someone within your organization to independently evaluate your software. Third-party reviewer The highest and the fourth level of testing independence is achieved when a third-party reviewer – usually a certified tester from a different organization – tests your software. Although expensive, this level provides optimum results in a test scenario, providing maximum separation of responsibilities between the development and testing teams. Suppose your team develops a calendar application. To ensure complete objectivity, you can hand over the product to a third-party test team. This team approaches the product as flawed, unlike teams within the organization which may not bring this level of objectivity. As a result, they're able to find defects that teams within the organization may overlook.
1292
Although objectivity is critical during software testing, sometimes developers test their products due to resource and time constraints. In these cases, the developer must adopt the mindset of a tester – to look consciously for defects – for testing to be effective. The primary advantages of self-review include early defect detection and prevention and cost effectiveness. However, higher levels of independence in testing produce more effective results, even though they may impact the schedule and project costs.
Question As a Project Manager for a payroll application, you want to employ different levels of testing independence for different testing activities. Rank the levels of testing independence from the lowest to the highest. Options: A. Ask Pete, who designed and worked on the payroll application, to review his module and report defects detected. B.
Acquire the help of Sandra, who is working on a related application, to test the payroll module created by Pete
C.
Hand over one module of the payroll application to the testing team in your organization that tests all completed software products of your organization
D.
Hire certified testers from outside your organization to run tests on the payroll application
Answer Correct answer(s): Ask Pete, who designed and worked on the payroll application, to review his module and report defects detected. is ranked as the first level of independence in the software testing process. The first level of testing independence is applied when the developer who created the software is employed to test the product. This level can be applied for cursory reviews. Acquire the help of Sandra, who is working on a related application, to test the payroll module created by Pete is ranked as the second level of independence in the software testing process. When a peer within the team is involved in testing a software product, then second-level independence is applied. This level of testing independence is higher than the level of selfreviews. Hand over one module of the payroll application to the testing team in your organization that tests all completed software products of your organization is ranked as the third level of independence in the software testing process.
1293
The third level of independence is applied when a member of a different functional group, such as the QA team in your organization, is involved in the testing process. Hire certified testers from outside your organization to run tests on the payroll application is ranked as the final level of independence in the software testing process. The highest level of independence is applied when a tester from a different organization or company is employed to test the software product developed in your organization.
2. The role of communication in testing Although processes and procedures are critical to the success of software testing, an overlooked but equally important component affecting testing is communication. Because software testing includes the participation of multiple teams – internal testers, development team, stakeholders, and external testers – these teams must communicate with each other as seamlessly as possible. Otherwise, misunderstanding and misinterpretation can undermine the test objective. Suppose your organization requires test activities at every stage of the process. The test results at every stage should be communicated to the entire team, because the tester may change for every round of testing. For example, a developer tests the software design model during the design phase and an integrator checks for integration defects later in the development stage. Results of these tests need to be communicated to the next level of testers and the final testing team so that they are aware of what occurred in the past and how it was resolved. It also helps them to look for similar defects while testing. Not only is communicating initial test activities to the testing team important, but how the testing team communicates its test results to the development team is equally critical. A tester's mindset is to look for defects in a product, and when they find them; their role in the process is justified. This can affect the tone used when they log defects. A harsh tone can make a developer defensive. The developer may feel that the defect log pinpoints faults, which in turn reflects on the developer's skills and competency. This may lead him to disregard defects reported. The validity of the defect is lost and the purpose of testing is defeated. Effective inter-team communication can help avoid these issues. For communication among team members during the test process to be effective, it is important to communicate defects and incidents neutrally Chances of test results being taken positively by the development team would increase if you communicate the defects and incidents in an objective manner. This means that the defects should be recorded without attributing the cause to the person who worked on it or undermining his effort. You should provide objective information on the defects so that the developer
1294
understands that you're not finding fault with him. For example, if the developer of the software has made a recurring error, simply explain the defect and discuss your observations of the incident. You can also record anything that you felt worked particularly well in the software. how the end user benefits For successful software development and testing, it helps to keep in mind the requirements and the benefits to the end user. Communicating how the defects you observe can impact end-user experience, provides objectivity to the test process. You should also emphasize how the defect prevents the product from meeting its stated objective. For example, you are evaluating a GUIbased web application that requires high network bandwidth usage. As a tester, you can highlight this to the development team and explain to them how this may hinder the end user experience. the need for collaboration The test process benefits from team effort, with the test and development teams collaborating effectively. In addition to achieving end-user satisfaction, working in a collaborating team helps you detect and fix defects, with multiple perspectives. Collaboration requires you to share your observations and suggestions with your team and receive feedback. For example, you've identified a new defect in a piece of software, but you are unsure of the scope of the defect. Instead of logging with the information you have, you could collaborate with the developer to get more information. As well as improving the information logged, this could help the developer feel more involved and invested in the testing process. As a tester, you should remember and understand the objectives and the stakeholder requirements defined for the testing process. The project and the test process are driven by these factors, and test plans are based on them. Understanding these factors helps you adopt the right perspective while testing. For example, if testers understand the objectives, they can set test parameters and the exit criteria, and rate the performance of the product according to these details. Otherwise, testing can be flawed, with noncritical defects possibly emphasized over others. In such cases, the developer may reject the defects logged against the software, hindering the overall test process. Testers must be able to identify what is critical and what is not while reporting defects. This ensures that the development team does not spend time and money in closing defects that are not critical to delivery. Involvement in software testing enables individuals to learn confidential and privileged information. A code of ethics is necessary, among other reasons to ensure that the information is not put to inappropriate use. Recognizing the ACM and IEEE code of ethics for engineers, the ISTQB® states the following code of ethics: public Certified software testers shall act consistently with the public interest.
1295
client and employer Certified software testers shall act in a manner that is in the best interests of their client and employer, consistent with the public interest. product Certified software testers shall ensure that the deliverables they provide (on the products and systems they test) meet the highest professional standards possible. judgment Certified software testers shall maintain integrity and independence in their professional judgment. management Certified software test managers and leaders shall subscribe to and promote an ethical approach to the management of software testing. profession Certified software testers shall advance the integrity and reputation of the profession consistent with the public interest. colleagues Certified software testers shall be fair to and supportive of their colleagues, and promote cooperation with software developers. self Certified software testers shall participate in lifelong learning regarding the practice of their profession and shall promote an ethical approach to the practice of the profession.
Question You implemented a test suite and found some incidents and defects. Now you want the programmer who developed the application to fix them. How would you communicate your findings to the programmer? Options: 1. Record incidents in a neutral and factual manner 2. Record your surprise on how such defects were allowed to creep in 3. Discuss how closing the defect helps the end product 4. Direct that all incidents must be closed without any delay
Answer Option 1: Correct. As a tester, you need to create neutral and factual incident reports that clearly and constructively discuss the defects, without insulting or blaming the developer.
1296
Option 2: Incorrect. When you log errors against a programmer, your reports should be written in an objective tone devoid of personal remarks. Expressing surprise in incident reports detracts from objective testing. Option 3: Correct. As a tester, you need to explain to the developer how your observations would help improve the end product. This helps the developer recognize the testing process as an effort to improve the product. Option 4: Incorrect. Once you report the defects against the programmer and explain your suggestions, the programmer takes over. Insisting on a particular schedule is not a tester's domain. Correct answer(s): 1. Record incidents in a neutral and factual manner 3. Discuss how closing the defect helps the end product
Summary The process of software testing is influenced by psychological factors that determine the success of the testing activity. These factors help you understand the differences between the mindsets of a developer and a tester. Generally, objective testing – testing carried out by someone other than the developer – is preferred because it supports the separation of responsibilities across the various teams involved in testing. This separation of responsibilities is called independence. There are four basic levels of independence, based on the degree of separated responsibilities. These levels include tests executed by the programmer himself, a peer programmer, a tester from the same organization, or a test team from another organization. Communication across teams also affects test results. Test results should be communicated in an impersonal, nonjudgmental manner so that they are taken as constructive critiques.
1297
Contrasting Software Testers and Developers Learning Objective
After completing this topic, you should be able to
recognize the different mindsets of a tester and developer in a test situation 1. The mindset of testers and developers The success of software testing is dependent on effective communication across different teams that participate in this activity, including testers and developers. As a software tester, you need to interact with the programmers or developers, who build the software applications and services being tested. This interaction drives the entire process, helping achieve the project goals and objectives. Project objectives drive the test plans, and to understand these objectives thoroughly, developers and testers need to interact with one another seamlessly. The interaction between the testers and the developers are influenced by numerous factors – psychological differences, roles and responsibilities in the testing process, and more. The roles and responsibilities of testers and developers impact their differing attitudes toward testing. For example, the basic responsibility of a developer is to code and to create a software application based on customer requirements. Even if the developer performs a self-review during development to locate and fix bugs, she is likely to undertake testing from the perspective that the product is defect free. A tester, on the other hand, is not expected to create or code software, and may not factor in the effort the developer puts in. She may only focus on testing the software on the assumption that it does not meet customer requirements and so consciously looks for defects in the application. There are basic differences in the mindset of testers and that of developers. Tester A tester tests the product for defects, keeping in mind the complete picture of the development life cycle and how different systems in the application are interconnected. Consequently, he or she is most likely to locate defects in the product. Because the tester didn't create the product, he or she is more objective and more likely to find defects. Developer A developer is usually an expert in a specific technical domain. Developers understand how a specific development model works and what functionality provides a better user experience of the product.
1298
However, because they delve deeply in their domains, they may lose perspective of the complete picture. They may discount some defects reported if they feel that the tester isn't competent enough to understand the development model or the technology used. Being personally involved in the development may make them less likely to accept defects reported objectively. Testers should display competence by thoroughly understanding the objectives and requirements of the application. In doing so, they should get the developer's perspective so they know what is critical and valid. This understanding is reflected in the test cases and in the nature of defects reported. This competence helps convince the developer to fix the defects. In addition, testers should demonstrate maturity and integrity in communicating defects. They must avoid personal and judgmental communication. At the same time, they must maintain integrity and resist pressure from any stakeholder to allow the product to pass without thorough testing. The mindset of testers is to look at products being tested as flawed, and they approach testing as an activity that uncovers these flaws. So they design test suites to detect defects instead of designing test cases that only check if something works. This results in more defects being uncovered. In the same test situation, a developer is likely to fit the defects reported within the established development models, and in cases where they don't fit, disregard them. The developer aims to create a working solution, not to look for intermittent bugs that arise in some other element of the application. The differing mindsets of the testers and developers can lead to misunderstandings and communication gaps when the two interact. There are ways that testers and developers can bridge this gap:
understand and appreciate each other's roles and responsibilities in the testing process
communicate and coordinate with one another throughout the development and testing life-cycle
initiate conversations with the programmers, as testers, and not wait for them to start inquiring about defect reports
share plans, drafts, schedule, design documents, and prototypes to stay updated of the process
provide fair feedback to the developers, appreciating their good work and reporting defects objectively A tester should be able to discriminate between the critical factors that need immediate attention and those that are minor. This helps him log faults that are valid and require immediate attention. He should also maintain logs and incident and test summary reports as evidence for test defects. This helps him substantiate defects when questioned by the developer. Although reporting defects is a key responsibility, the tester must also communicate the fault appropriately to the developer so that it can be fixed. The tester should avoid offending the
1299
developer and present the defect report in a manner that makes the developer understand that the aim is to improve the end product.
Question What mindset should a potential tester adopt while analyzing a test case? Options: 1. Understand the need to observe, identify, and record evidence of the defects 2. Recognize and fit defects found within the development models used 3. Be open to appreciate good work in the application in addition to reporting defects
Answer Option 1: Correct. A potential tester should always back the defects identified with evidence, such as test logs and test summary reports. Doing so provides a clear perspective of the defects and the conditions they occur in, and allows developers to validate and fix the defect. Option 2: Incorrect. Developers work based on established development models and usually try to fit defects within these models when they're reported. Testers only need to understand the basics of these models so that defects can be communicated effectively. Option 3: Correct. A good tester always provides fair feedback, which includes positive and constructive feedback, using an incident report. Correct answer(s): 1. Understand the need to observe, identify, and record evidence of the defects 3. Be open to appreciate good work in the application in addition to reporting defects
Summary The success of software testing is dependent on the effective interaction between testers and developers. To improve this interaction, you should first understand the differences in the mindsets of a developer and a tester. These mindsets are dependent on their roles and responsibilities. Testers possess an overview of the entire development life cycle, and the developers are experts in a specific technical domain. Developers code and create software, and testers review these software products and identify the defects within. The responsibility of a tester does not end with reporting the defects. He should communicate the defects politely to the developers and offer suggestions to fix the defects. He should provide
1300
fair and objective feedback. This helps bring testers and developers together and creates a unified team.
1301
Organizing Testers and the Software Test Process Learning Objectives
After completing this topic, you should be able to
organize a test team
organize test activities Exercise overview In this exercise, you're required to set up a test team and organize activities that constitute the software testing life cycle. This involves the following tasks:
setting up a test team
organizing test activities
Setting up a test team You are a test manager in an organization. A development team within your organization has created a payroll administration web site for the company, which will help payroll executives manage the payroll account of all employees. The site also helps employees view their salary credits, view and print pay slips, and claim monthly reimbursements. As a test manager, you want to test and evaluate the functionality of the payroll intranet. To begin, you want to set up a core team of potential testers.
Question You want the team you set up for testing the payroll application to have a degree of independence and objectivity. Due to budgetary limitations, you cannot opt for the highest level of independence. Who would you assign as testers considering the level of independence required? Options: 1. The developer who worked on the application 2. A peer of the developer from within the team 3. A testing team from within the organization 4. Testers from a certified testing organization
Answer
1302
Option 1: Incorrect. This is the lowest level of testing independence and should be applied for cursory reviews of the product, not for achieving higher degrees of testing independence. Option 2: Correct. The second level of testing independence is achieved when peer reviews are implemented in testing a software product. This level is higher than self-reviews and provides a fresh perspective lacking in self-reviews. In the absence of a testing team, this is an option to consider. Option 3: Correct. For a higher level of testing independence, you can employ an internal tester from a different functional group or a testing team to test the product. This is the preferred level of testing independence in most organizations. Option 4: Incorrect. Although certified testers from organizations that specialize in testing provide the highest level of independence, it is expensive. With budgetary limitations, this isn't a feasible option. Correct answer(s): 2. A peer of the developer from within the team 3. A testing team from within the organization
Question You decide to use testers from a different functional group to test the product to get the level of independence required. You want to ensure that the testers on your team display the right mindset. Identify the mindset that a potential tester should adopt while analyzing a test case. Options: 1. Upgrade their skills to gain expertise over the specific domain in the development model being tested 2. Provide evidence in support of defects observed at all times 3. Discriminate between critical defects that require immediate attention and those that are minor 4. Thoroughly understand the objectives and requirements of the application under test
Answer Option 1: Incorrect. Obtaining the working knowledge of a specific domain in the development model is the responsibility of a developer, who is considered a specialist in that domain. A tester needs only an overall idea of the entire test case. Option 2: Correct. A potential tester should always back the defects identified with evidence, such as test logs and test summary reports. This helps developers validate and quickly fix the defect.
1303
Option 3: Correct. Testers should be able to differentiate between the two to help save both time and cost of the overall testing process. Option 4: Correct. Understanding the objectives and the requirements of the application helps testers to design and implement test suites that help them detect defects. Correct answer(s): 2. Provide evidence in support of defects observed at all times 3. Discriminate between critical defects that require immediate attention and those that are minor 4. Thoroughly understand the objectives and requirements of the application under test
Question You also want the test team to focus on communication. Suppose a test engineer in the team finds a simple but valid defect in the login functionality of the payroll application. This defect is to be communicated to the senior programmer who designed and developed the program. How would you want the test engineer to communicate this defect to the programmer? Options: 1. Create a strongly worded incident report escalating how such a basic but major defect could occur 2. Explain the defect with observations and defect history in a factual incident report 3. Communicate the defect in a neutral tone with remarks on how fixing it helps the end user 4. Inform the programmer that the defect is assigned to someone else with experience
Answer Option 1: Incorrect. A good tester creates neutral and factual incident reports, and contributes as a team rather than blame anyone for defects found. A strongly worded incident report can cause the programmer to feel that he or she is being judged. Option 2: Correct. The incident reports that a tester creates should be neutral and objective. For this, the defects should be recorded without attributing the cause to the person who worked on it or undermining the effort of that person. Option 3: Correct. Testers should always communicate their opinions – subjective and objective – in a neutral manner. This emphasizes to the developer that the tester's only interest is to ensure that the product meets the stated objective and meets end-user expectations. This tone also makes it easier for developers to accept the feedback positively. Option 4: Incorrect. A potential tester should never assume that a defect cannot be fixed by the programmer who worked on it. The programmer has the domain knowledge and is skilled enough to fix a major defect in design.
1304
Correct answer(s): 2. Explain the defect with observations and defect history in a factual incident report 3. Communicate the defect in a neutral tone with remarks on how fixing it helps the end user
Organizing test activities Now that you've set up a core testing team, you want to identify the order of test activities that need to be performed to carry out the test process.
Question You want the focus of the test team to be client privacy and security for the payroll application. Sequence the tasks in the order your team will perform them during the software testing process for this payroll site. Options: A.
Identify exit criteria based on client privacy and security objectives and create test plans
B.
Specify as a test condition that only authorized employees with valid user IDs can enter the site
C.
Create a test suite for the payroll administration site with test procedures that check if individual logins of employees could be circumvented
D.
Check the logs of the actual test outcome to check if the exit criteria on employee privacy is met
Answer Correct answer(s): Identify exit criteria based on client privacy and security objectives and create test plans is ranked as the first step in testing the software for managing the payroll administration site. Understanding the goals of the project and identifying the objectives and risks belong to the planning phase of the testing process. During this phase, the testers can also determine the kinds of tests to run. Specify as a test condition that only authorized employees with valid user IDs can enter the site is ranked as the second step in testing the software for managing the payroll administration site. During the test analysis phase, the test documents – such as requirements and design specifications – are analysed. Create a test suite for the payroll administration site with test procedures that check if individual logins of employees could be circumvented is ranked as the third step in testing the software for managing the payroll administration site. During the test implementation and execution phase, the testers on your team will convert the test conditions that were determined during test design into test cases and test suites. For the payroll site, these test suites would focus on the security features of the site.
1305
Check the logs of the actual test outcome to check if the exit criteria on employee privacy is met is ranked as the fourth step in testing the software for managing the payroll administration site. Checking the logs of the actual test outcome against the exit criteria is carried out during the exit criteria evaluation phase. During this phase, your testers would analyze if the exit criteria for the privacy of the site is adequate, or if more tests are required.
Question After test suites are executed and test results evaluated, you now want your team to close the test process. What test activities should the team perform to close the test process? Options: 1. Archive testware for maintenance testers 2. Analyze lessons learned for future test projects 3. Recommend additional tests to resolve open defects in the payroll processing site 4. Check the test logs against the exit criteria set for the payroll application
Answer Option 1: Correct. Testers archive testware so that maintenance testers can reuse the same components during maintenance testing and regression testing – because it is time- and costeffective. Option 2: Correct. In the project evaluation report, testers identify and assess the lessons learned from this test process, which would help them improve the test process as well as the development life cycle in the future. Option 3: Incorrect. A tester determines whether additional tests are required during the exit criteria evaluation phase, not in the test closure phase. Option 4: Incorrect. Checking the test logs against the exit criteria set for the payroll application occurs during the exit criteria evaluation phase. This test activity is not part of the test closure phase. Correct answer(s): 1. Archive testware for maintenance testers 2. Analyze lessons learned for future test projects
1306
Software Development Models Learning Objectives
After completing this topic, you should be able to
recognize how software testing relates to the development life cycle
identify software test levels 1. Software testing and development models Depending on the requirements of a software-development project, you use a specific development strategy. For example, if you want to quickly design and develop software, you use a fast-track approach. However, if your main aim is to develop a high quality product, you spend extra time on the design and development process. Your development strategy depends on the availability of time and resources, the allocated budget, and the scope of the project. Each development strategy is known as a Software development model. Each model defines the order in which you should perform project-related activities. These activities include identifying the client's requirements, creating a product design, developing the required product, and testing the product for defects. Testing is an important part of each model. Software development models are of two types:
sequential
iterative In a sequential development model, the project-related activities are distinct from each other. Only after you complete one activity can you initiate the next. The simplest sequential development model is the waterfall model. The waterfall model comprises six activities.
Graphic Description of the waterfall model flow chart: When using the waterfall model, you first identify client requirements. Second, you identify system requirements. Third, you create an overall design, and fourth, you create a detailed design. Then you develop the product, and finally, you test the product. Description ends.
1307
Identify client requirements To develop a satisfactory product, the development team starts by identifying the client's requirements. During this activity, the team determines the client's expectations of the product. Then the team records these requirements in a requirement specification document. Identify system requirements After identifying the client's requirements, the team identifies system requirements or the requirements that the product should satisfy. This activity helps them identify the features and functions the software product needs to possess to meet the client's needs. The output of this activity is the functional specification document. Create an overall design Based on the identified requirements, the team creates an overall design of the software product. This overall design outlines the external features of the product. This design also describes the internal components of the product, such as modules and classes, and their interrelationships. The team saves the overall design in the technical specification document. Create a detailed design While creating a detailed design, the team defines the functions of each of the identified components and decides on the method to create the components. To store the detailed design, it creates the program specification document. Develop the product Using the detailed design as a blueprint, the team writes code for each component of the product and, finally, integrates the components to create the product. Test the product After developing the product, you test it to ensure that it meets the client and product requirements as well as the requirements of all types of end users. The main drawback of the waterfall model is that it incorporates testing toward the end of the development life cycle. Because the code for the product is too complex at this stage, fixing bugs or defects in the product can be time consuming. Also, while fixing the bugs, you can introduce new bugs in the product. To overcome the drawbacks of the waterfall model, you can divide the development of the product into various stages and perform a testing activity at the end of each stage. This division of development and testing activities can help you identify bugs in their nascent stage, when you can easily fix them. The V-model is a sequential model that improves upon the waterfall model. In the V-model, the development team first identifies client and system requirements and creates an overall and detailed design. You and other members of the testing team review the documents generated at the end of these processes. You simultaneously plan for the testing activity. As the product is progressively developed, you and the other testers test it. However, you divide the testing into four test levels.
1308
Graphic Description of the V-model flow chart: In the V-model, you first identify client requirements and plan for acceptance testing. Next, you identify system requirements and plan for system testing. The third step in the V-model is to create an overall design and plan for integrating testing. And the fourth step is to create a detailed design and plan for component testing. After the fifth step, you move on to developing the product. Finally, you progressively conduct component testing, integration testing, system testing, and acceptance testing. Description ends. Component testing During component testing, you test each component of your product for defects. Also, you fix any defects immediately. You use the detailed design of the product as the basis for creating a component-testing plan. Integration testing Integration testing is used to test the interrelationships between the components of the product. During integration testing, you determine whether the components interact correctly with each other and with computer hardware and other software. To create an integration-testing plan, you refer to the overall design of the product. System testing Before you begin system testing, developers integrate all the components and build a functional software product. It exhibits the desired features and functions and performs without any evidence that there are defects present. You create a system-testing plan based on the system requirements. Acceptance testing Acceptance testing is conducted by the representatives of the client. The representatives may either test the product at your site or test it after you've delivered it to them. Their main objective during acceptance testing is to determine whether the product meets all their requirements. You create an acceptance-testing plan after the client's requirements have been identified. In the V-model, you test the product at each stage of development. You release the outcome of each stage to the next stage only when all identified defects have been fixed. However, the V-model also has a drawback. In this model, you verify a product against client requirements only toward the end of the development process. Fixing bugs and adding missing features and functions to the product at this stage can be difficult, expensive, and time consuming.
1309
The iterative development model eliminates the drawback of the V-model. In the iterative model, developers build a product using a series of iterative steps. Each step consists of four tasks – Identify requirements, Create a design, Create code, and Test code. You, as the tester, are part of the development process. Because you are able to test the product while it is being developed, you can identify bugs easily and accurately.
Graphic Description of the iterative model flow chart: In the flow chart, four rectangular boxes represent the four tasks – Identify requirements, Create a design, Create code, and Test code. Connected to the test code box is a decision box labeled "Have all requirements been met?". If the answer to this question is "Yes", you end the development process. Otherwise, you move back to the first task and repeat the entire process. Description ends. In the iterative model, representatives of your client can participate in the testing process at the end of each step. The representatives can also suggest changes to the product during development. If you use the iterative model, you
don't prepare formal documents, such as the requirement specification document, before you begin development
don't have to identify all client and system requirements or design the entire product before you start creating code
have a set schedule and cost for the project and for each iterative step
repeat each iterative step until you develop a final product that meets all client and system requirements The iterative model also has its drawbacks. These drawbacks can adversely affect the testing process. Two significant drawbacks of the iterative model are absence of formal documentation In the absence of formal documentation, you can't verify requirements accurately. So you write a functional test for each iterative step and ask the developers to create code that can pass the functional test. increased testing time and cost Compared to the other models, the iterative model can increase testing time and cost. For example, during an iterative step, developers can inadvertently modify a previously approved feature. To prevent such modifications and deletions, you have to spend more effort on testing. This can be a drawback for small-scale projects.
1310
Question Match each software development model to its diagram. Options: A.
V-model
B.
Iterative model
C.
Waterfall model
Targets: 1. Model 1 2. Model 2 3. Model 3
Answer In the iterative model, you perform a series of iterative steps until all your project requirements are met. The waterfall model is a sequential software development model. In this model, you build and then test a software product. The V-model is a customized version of the waterfall model. In this model, you combine the testing process with the software-development process. This ensures that you test each component, feature, and function of your product as it is built. Correct answer(s): Target 1 = Option B Target 2 = Option C Target 3 = Option A The V-model and the iterative model are not stringent and you can modify them to suit your requirements. For example, you can use the four test levels – component testing, integration testing, system testing, and acceptance testing – during each iterative step of the iterative model. You can also customize the order in which you perform the four test levels, regardless of the development model you use. For example, if you're testing a web portal that contains a thirdparty application, you perform acceptance testing on the third-party application first. Then you carry out system testing for the web portal.
1311
Question Match each test level to the correct scenario. Options: A.
Component testing B.
Integration testing
C.
System testing
D.
Acceptance testing
Targets: 1. You are testing the interaction between the component of your software product and an operating system 2. You are testing whether a software product meets users' needs 3. You are testing an assembly that you want to add to your web page 4. You are testing whether a tax-calculator application performs calculations correctly
Answer Integration testing helps you determine whether the components of your software product interact correctly with computer hardware and other software. It also helps you test the interrelationships between the components. During acceptance testing, you check whether or not your software product meets all actionable client requirements. During component testing, you check each component of your software product for defects. At the system testing level, you check a complete product and ensure that it meets all client and system requirements. Correct answer(s): Target 1 = Option B Target 2 = Option D Target 3 = Option A Target 4 = Option C
1312
Summary The development model of any software-development project depends on its requirements. Sequential and iterative models are two types of development models. Testing is an integral part of both these models. The waterfall model is the simplest sequential development model. In this model, you test a complete product. So you should use the waterfall model only if you've identified the client and system requirements accurately and don't expect to find extensive defects in the product. The V-model is an improved version of the waterfall model. In this model, you divide the testing activity into four test levels: component testing, integration testing, system testing, and acceptance testing. You use these test levels as you progressively build the product. This makes the testing and fixing processes easy. When using the iterative development model, you develop your software product in parts, using a series of iterative steps. Testing is a part of each step, and you can involve client representatives in the testing process. This makes it easier to identify bugs.
1313
Component and Integration Testing Learning Objectives
After completing this topic, you should be able to
recognize how component testing works
recognize how integration testing works 1. Component testing In advanced software development models such as the V-model, testing is an elaborate activity and is performed at four levels. Dividing the testing activity into these levels helps you efficiently manage and control the activity. These test levels also make it easier for you to identify bugs and fix them. Component and integration testing help you locate code-related defects and determine whether the various code segments interact with each other as intended. You perform component and integration testing during the early stages of software development. So you can correct identified defects with minimal rework and reduce, or even prevent, defects in the integrated software. Component testing helps you identify errors in each component, such as an object, program, or module, of a software application. After the code for a component is written, it can be tested by the original developer, or passed for testing to another developer. The involvement of another developer brings objectivity and independence to the component-testing process. During component testing, you don't maintain a formal record of defects. So to avoid oversights later, you or the designated tester should fix all errors as soon as you detect them. A common approach to component testing is the test-first approach, which is an iterative process. According to this approach, you create test cases before you start developing and testing code. To create the test cases, you use the specifications documents and the blueprint for the software application. The test-first approach involves repeating three steps until the code passes the tests:
create test cases
develop code
run tests While you're testing the code of a component, you may also need to check whether the code correctly responds to or calls other components. However, sometimes, you may not have
1314
immediate access to these other components. The unavailability of the other components in a component-testing scenario is similar to the testing of parts at a car-manufacturing plant. For example, when you begin testing the motor of a particular car model, the braking system or the ignition mechanism might not be ready. Here the braking system is a called component and the ignition mechanism is a component that calls the motor. To test the functions of the motor in the absence of a braking system and ignition mechanism, you might first create a temporary, no-frills braking system and ignition. Then you could connect both to the motor. Similarly, to check whether a software component can respond to or call other components, you create two temporary components: stubs Stubs simulate called components. While testing a software component in isolation, you use a stub in place of each called component. For example, if an component calls an object that is not yet ready, you can use a stub in place of the object. drivers During component testing, you may also have to create simulated components or test tools known as drivers. A driver acts as a substitute for a component that calls the component you're testing. For example you can use a driver in place of the button that calls the authentication system you're testing. At the component-testing level, apart from checking the functions of a software component, you also verify whether it meets nonfunctional requirements. For example, you check whether a component can manage memory and storage space efficiently.
Note A nonfunctional requirement is one that isn’t related to functionality, but to an attribute such as usability, efficiency, reliability, maintainability or portability. During component testing, you also test the robustness of a component. For example, you check how well the component responds to invalid inputs. You also check whether the components require additional testing and perform the tests, if required.
Question The training department at Easy Nomad Travel, a worldwide travel agency, has developed various training courses over the years. To manage these courses, the agency hires your company to develop a modular course management system. As a testing manager, you're responsible for testing the system. Identify the steps which are necessary to ensure successful component testing. Options:
1315
1. Assign a developer to test each module created by another developer 2. Maintain a formal record of defects 3. Ensure all called components are available 4. Create test cases before you develop and test code
Answer Option 1: Correct. To bring objectivity and independence to the component-testing process, you can ask a developer to test a code segment or module created by another developer. Option 2: Incorrect. It is not necessary to maintain a formal record of defects during component testing. You fix all defects as soon as you detect them. Option 3: Incorrect. During component testing, you may not have access to all called components. So to check whether the code you're testing correctly calls other components, you substitute the called components with stubs. Option 4: Correct. A commonly used approach to component testing is the test-first approach. In this approach, you create test cases before you start developing and testing code. Correct answer(s): 1. Assign a developer to test each module created by another developer 4. Create test cases before you develop and test code
2. Integration testing After successful component testing, you move on to integration testing. At this test level, you determine whether software components interact with each other as intended. During integration testing, you also verify whether the software components interact correctly and efficiently with computer hardware and other software, such as an operating system. This level of testing is also known as component integration testing and is typically conducted by either developers or integrators. You can also conduct an integration test after the system-testing process. At this stage, you refer to integration testing as system integration testing. This type of testing helps you accurately analyze the interactions between a complete software product and other software systems. During component and system integration testing, you can test the nonfunctional characteristics of the integrated components and systems. For example, after integration, two components may use a single system resource at the same time. This can negatively affect the performance of the components. You can check for such performance degradation during component integration testing.
1316
Before you plan for and perform integration testing, you should choose an integration strategy. This strategy helps you decide the order in which you integrate the components of a software application. The order depends on the number and types of bugs you expect the application to have. Based on the integration strategy you choose, you can adopt one of two methods to conduct integration testing: big-bang integration testing You perform big-bang (or non-incremental, as it is formally known) integration testing on a fully integrated system. You should use this method of testing only if you plan to integrate the software components first and then test the resulting system. Bang-bang integration testing proves successful if the components have few and uncomplicated bugs. Description of the big-bang integration testing animation: The animation depicts the pieces of a jigsaw puzzle being assembled to complete the image of a car. Description ends. incremental integration testing Incremental integration testing is opposite to the big-bang method. In this type of testing, you gradually build and test the system on a component-by-component basis. For example, you test the interactions between any two components before you integrate and test additional components. Description of the incremental integration testing animation: The animation depicts the pieces of a jigsaw puzzle being assembled one-by-one to complete the image of a car. Description ends. Both integration testing methods have their advantages and disadvantages. Big-bang integration testing ensures that you don't require stubs and drivers to simulate missing components. Yet this method is time consuming because it involves testing an entire system. While conducting such tests, you may be unable to identify the cause of defects quickly. Additionally, big-bang integration testing allows you to detect defects only late in the development process. Fixing defects at this late stage can considerably increase the defects and expenses of the project, leading to budget overruns. The advantage of incremental integration testing is that you start testing on a small scale. For example, you first test the interaction between two or three components. This increases your chance of isolating defects. However, when you conduct tests using incremental integration testing, you need to use stubs and drivers to substitute for missing components. Creating the stubs and drivers can be time consuming, increasing the cost and effort involved in the test process.
1317
In most cases, incremental integration testing is preferable to big-bang integration testing because the advantages of incremental integration testing outweigh the disadvantages. You can divide incremental integration testing into two types: top-down integration testing Top-down integration testing involves testing the external features of a software application first and then gradually integrating and testing the internal components. For example, you start by testing the interactions of the graphical user interface (GUI), which isn't called by any other component. If the components the GUI calls aren't ready, you use stubs to simulate them. When you receive the missing components, you perform integration testing on them. The advantage of top-down integration testing is that you don't need to create drivers. Also, this type of testing helps you easily identify and fix defects in the design of your software application. However, additional effort is required to create stubs. bottom-up integration testing In bottom-up integration testing, you first test the component at the lowest level in the software application. This would be the component that doesn‘t call any other components. You can use drivers to simulate the components that call this component. Similarly, you progressively build the application and test the higher-level components. This method helps you test the interactions between software components more effectively than the top-down method.
Question Having integrated the components of the Easy Nomad Travel course management system, you want to perform big-bang integration testing. Before you do so, what should you know about this testing method? Options: 1. Is performed in an incremental manner 2. Involves the use of stubs and drivers to simulate missing components 3. Allows you to detect defects at a late stage of software development 4. Tests the interactions between components and computer hardware
Answer Option 1: Incorrect. Big-bang integration testing involves testing an entire system. You perform this type of test only after you've integrated all the software components.
1318
Option 2: Incorrect. You perform big-bang integration testing on a fully integrated system. Because you don't have missing components, you don't require stubs and drivers. Option 3: Correct. You can conduct big-bang integration testing only after you've integrated all the components of your software application. This prevents you from detecting defects until all the components are ready. Option 4: Correct. Big-bang integration testing verifies the interactions between software components and other systems such as the operating system, computer hardware, and other software applications. Correct answer(s): 3. Allows you to detect defects at a late stage of software development 4. Tests the interactions between components and computer hardware
Summary To accurately identify bugs in your software applications, you can test them at four levels. The first two test levels are component testing and integration testing. During component testing, you test the code of each component of a software application and immediately fix the bugs you discover. Integration testing helps you verify the interactions between the components of a software application. You can carry out integration testing in two ways – big bang and incremental. Using big-bang integration testing, you test a fully integrated system. Conversely, incremental integration testing involves progressively integrating components and testing their interactions. You can perform integration testing using either a top-down or a bottom-up approach.
1319
System and Acceptance Testing Learning Objectives
After completing this topic, you should be able to
recognize how system testing works
recognize how acceptance testing works 1. System testing After you have successfully tested the features and functions of each component of a software application, you can test the application as a single entity. This level of testing is called system testing. During system testing, you ensure that the application meets the requirements you'd identified during the initial phases of the software-development process. You also test whether the application can withstand potential risks, such as hacker and virus attacks. Additionally, during this level of testing you determine whether the application can optimally utilize system resources. Checking whether the application can interact with the operating systems it supports is also a part of the system-testing process. System testing is typically conducted by a dedicated testing team. This team will assess the application on the basis of its external features and not the underlying code. To ensure that the implementation details are not known to the testers, they should not have worked on the development of the code. The objective of system testing is to verify that the system meets specified requirements. You test the application in the simulated environment to do this, checking for any defects as you progress. You can categorize requirements into functional requirements Functional requirements refer to the features and functions of the application. For example, an order-processing system needs to display order details to users. So the ability of the system to retrieve the order details from a database is a functional requirement. You can also consider the security mechanism of an application and the ability of the application to interact with other systems as functional requirements. nonfunctional requirements Nonfunctional requirements are those that are not related to specific functionality, but to attributes such as usability, efficiency, reliability, maintainability or portability. For example, you consider an
1320
application efficient if it retrieves information within a few seconds. So the ability of an orderprocessing system to retrieve customer details within a few seconds may be a nonfunctional requirement. Although somewhat generic, nonfunctional requirements do need to be identified as part of requirements gathering. While testing functional requirements, you start with a specifications-based black box approach. Black box testing is so called because it takes no interest in the internal structure of the system or component. White box, or glass box, is used to describe testing that is concerned with the internal workings of a system. As we‘ll see, structural testing is one such testing type.
Note To influence the experience of developers, testers, and users and to determine what should be tested, black box and white box testing may be used in conjunction with experienced-based techniques. While performing nonfunctional tests, you verify quality attribute requirements. For example, you check whether an application performs as efficiently and reliably as intended. You might determine if the system is as easy to learn and use as you require, and test for issues relating to future maintenance. You may be testing for how easy it is to install or adapt the system into other environments. The attributes, and their sub-attributes, tested for during nonfunctional requirements testing, are
Reliability, comprising robustness, fault-tolerance, recoverability and compliance
Efficiency, comprising speed, resource utilization, and compatibility
Usability, comprising comprehensibility, learnability, operability, appeal, and compliance
Maintainability, comprising analyzability, stability, changeability, testability and compliance
Portability, comprising adaptability, compatibility, installability, replaceability, and compliance
Question During system testing, you verify whether an application meets two categories of requirements: functional and nonfunctional. Match each type of requirement to the appropriate category. Options: A. B.
A graphics-sharing web site allows users to edit their graphics online
An accounting application must be capable of being expanded in the future
1321
C.
A bank's website runs in all types of web browsers
D.
The web site of an airline company must be able to process payments made via a range of credit cards
E.
An order-processing system provides buttons and menus that are easily accessible
F.
A web form displays transaction details only to authorized users
Targets: 1. Functional requirement 2. Nonfunctional requirement
Answer Functional requirements are application specific. These requirements refer to the features and functions your client wants in an application. An example of a functional requirement is the ability of a photo-sharing web site to allow users to edit photos. Similarly, the ability of a web site to correctly process credit-card payments and the ability of a web form to display transaction details only to authorized users are functional requirements. Not all web sites and web forms need to satisfy these requirements. Nonfunctional requirements are those that are not related to specific functionality, but to attributes such as usability, efficiency, reliability, maintainability or portability. For example, a system’s readiness to have new features and functionality added at some future date is a maintainability attribute. Correct answer(s): Target 1 = Option A, Option D, Option F Target 2 = Option B, Option C, Option E
Question Which of the following tests form part of system testing? Options: 1. Testing an application that can support a minimum number of concurrent users 2. Testing an application that works properly on a specific Operating System 3. Testing a component that interacts with other components correctly 4. Testing a module of an application before code is available
Answer Option 1: Correct. System testing tests the whole system as it might be used in a production environment.
1322
Option 2: Correct. System testing tests that the system interacts as intended with its environment. Option 3: Incorrect. This kind of testing would form part of integration testing. Option 4: Incorrect. This kind of testing would form part of component testing. Correct answer(s): 1. Testing an application that can support a minimum number of concurrent users 2. Testing an application that works properly on a specific Operating System
2. Acceptance testing After successful system testing, you hand over the application to the client. Representatives of the client, such as prospective users of the application or designated testers, then conduct acceptance testing. Instead of checking the application for defects, the testers verify whether the application meets all their requirements, both functional and nonfunctional. Some clients may also send their representatives to your company to conduct acceptance testing on a product. This type of acceptance testing is known as Factory acceptance testing. After a successful factory acceptance test, the representatives take the product to their site and perform another acceptance test there. At this stage, you call the test Site acceptance testing.
Note Overlapping of system and acceptance testing is common during factory acceptance testing. If an application contains multiple independent subsystems, you don't need to wait for system testing on all the subsystems to be complete. You can perform acceptance testing on any subsystem that has passed a system test. For successful acceptance testing, you simulate the environment in which the application will run. During acceptance testing, you determine whether an application
meets all the specified requirements
is ready to be deployed
adversely affects existing applications and business operations If an application fails an acceptance test, then unless the customer chooses to accept the defect, it needs to be fixed by developers. For example, if you discover that a new orderprocessing system causes problems when coexisting with an existing line of business system, then a fix will need to be sought.
1323
You can categorize acceptance testing into various types: user acceptance testing The prospective users of an application conduct user acceptance testing. During this testing process, they check whether the application allows them to perform business tasks. For example, they check whether an accounting application allows them to generate and print reports. operational acceptance testing Operational acceptance testing is conducted by system administrators. These administrators try to assess whether the application can withstand malicious attacks, can recover from failures, and can be maintained easily and efficiently. For example, a system administrator may check if a customer-survey form can use back up data to recover from failures. contract acceptance testing If you sign a contract with the client about the type of application you'll create, the client conducts contract acceptance testing. During this testing process, the client ensures that the application meets the acceptance criteria specified in the contract. For example, if a contract mentions that a web site must allow users to customize each web page, the client verifies this. regulation acceptance testing To ensure that an application complies with standard government, legal, and safety regulations, the client conducts regulation acceptance testing. Suppose a company is developing software for US government use. There may be a requirement that the software complies with Section 508 Amendment to the Rehabilitation Act of 1973. Compliance means that the software is accessible to people with disabilities, and that access and use are comparable to access and use by a people with no disabilities. The government department receiving the software would test for section 508 compliance against these criteria. Two other types of acceptance testing are alpha and beta testing. You perform alpha and beta testing on software applications your organization produces for mass use, for example, commercial off-the-shelf (COTS) applications. During the alpha testing process, your team and a group of prospective customers check an application to ensure that it meets all specified requirements. You perform alpha testing at your site. After successful alpha testing, you send the application to another set of prospective customers for beta testing to help simulate a real-world environment. These customers check whether the application meets their needs and report problems to you. Based on their reports, you fix the application and then release it to the market.
Note Alpha testing that takes place at the developer’s site is sometimes referred to as factory acceptance testing, while beta testing in the customer’s site corresponds to site acceptance testing.
1324
Question The development team at your company has created a transaction-processing system for the call center at Easy Nomad Travel. After conducting a successful system test, you send the system to the client for acceptance testing. The client decides to conduct operational acceptance testing on the system. Identify the characteristics of this type of testing. Options: 1. Is conducted by system administrators 2. Is conducted by prospective users 3. Assesses the ability of a system to resist hackers 4. Verifies whether a system meets safety regulations 5. Checks whether a system meets client acceptance criteria
Answer Option 1: Correct. During operational acceptance testing, system administrators try to assess the robustness of a system. They also check whether they can maintain the system easily and efficiently. Option 2: Incorrect. The prospective users of a system conduct user acceptance testing. During the testing process, they check whether the system can help them perform required tasks. Option 3: Correct. During operational acceptance testing, the administrators try to assess whether a system can withstand malicious attacks and recover from failures. They also check whether their security guidelines and user-management criteria can be applied to the users of the system. Option 4: Incorrect. Regulation acceptance testing verifies whether a system complies with standard safety, government, or legal regulations. Option 5: Incorrect. To check whether a system meets acceptance criteria, representatives of the client conduct contract acceptance testing. The acceptance criteria are part of a contract, which the client and representatives of your organization jointly sign. Correct answer(s): 1. Is conducted by system administrators 3. Assesses the ability of a system to resist hackers Acceptance testing is often the last test level. However, you can also perform acceptance testing at other stages of the software-development process: during component testing
1325
During component testing, you can conduct acceptance testing on a component to verify it performs as expected. during installation or integration You subject a COTS application to acceptance testing while you‘re installing it or while you‘re integrating it with another application. before system testing If you add a new feature to an existing application, you first perform acceptance testing on the feature. Then you conduct system testing on the entire application.
Question You've handed over the course management system to representatives of Easy Nomad Travel. The representatives want to run an acceptance test on the system. What should they do? Options: 1. Ask a group of prospective users to perform the test 2. Ask the developers at your company to perform the test 3. Check each component of the system for defects 4. Check whether the system is ready to be deployed
Answer Option 1: Correct. A group of prospective users conducts acceptance testing on a system and checks whether the system meets their requirements. Option 2: Incorrect. The developers who created the application should not be involved in acceptance testing although the customer might commission acceptance testing on their behalf by professional testers from the same company. Option 3: Incorrect. The client representatives don't perform acceptance testing primarily to look for defects in a system. They perform acceptance testing to verify whether the system can be deployed and meets their key requirements, both functional and nonfunctional. Option 4: Correct. During acceptance testing, representatives of the client check whether a system is in a satisfactory state and is ready to be deployed. In doing this, they check whether the system can adversely affect existing applications and business operations. Correct answer(s): 1. Ask a group of prospective users to perform the test 4. Check whether the system is ready to be deployed
1326
Summary Before you deliver a fully integrated application to your client, you perform system testing on the application. This is the first time you test the application as a whole. System testing helps you determine whether the application meets the requirements you'd agreed upon with your client. Once the application has completed system testing successfully, acceptance testing is carried out for, or on behalf of, the client. The client representatives may carry out the tests in two stages: first at your site (alpha testing) and then at the client‘s (beta testing).
1327
Testing to Reveal Defects Learning Objective
After completing this topic, you should be able to
evaluate software defects and test levels Exercise Overview In this exercise, you're required to evaluate software defects and test levels. First, you need to evaluate given defects and determine which test levels can help detect them. Second, you need to evaluate given test levels and determine which defects the test levels can reveal. This involves the following tasks:
recommending test levels
evaluating test levels
Recommending test levels Your company is developing an online-banking web site for Poseidon Bank. Two significant features of the web site are an innovative user interface and an authentication system. The user interface should allow users to log on and effortlessly navigate through the web site. The purpose of the authorization system is to verify the user credentials and allow authenticated users to view their account details. You and your team members have been assigned the task of testing the web site.
Question During which level of testing would representatives of a client typically note a system failure, for example difficulty in reinstating a web site after it has been hacked? Options: 1. Component testing 2. Integration testing 3. System testing 4. Acceptance testing
Answer
1328
Option 1: Incorrect. During component testing, you check the features and functions of each component of an application separately. The representatives of your client are rarely involved in the component testing process. Option 2: Incorrect. Integration testing helps to verify the interactions between the components of an application. Even if client representatives participate in integration testing, this type of defect is unlikely to be exposed. Option 3: Incorrect. Before you deliver an application to your client, you assess the features and functions of the entire application using system testing. Typically, the representatives of the client don't participate in system testing. Option 4: Correct. Acceptance testing is conducted by the representatives of your client. During this testing process, client representatives verify whether an application meets all their requirements and is easy to maintain. Correct answer(s): 4. Acceptance testing
Question You want to check whether the authentication component of the web site erroneously grants access to users who provide invalid input. Which testing level helps you achieve this objective? Options: 1. Component testing 2. Integration testing 3. System testing 4. Acceptance testing
Answer Option 1: Correct. The authentication system is one of the components of the Poseidon Bank web site. To verify whether this component can distinguish between valid and invalid input, you conduct component testing. Option 2: Incorrect. During integration testing, you don't check the internal workings of a component. Instead, you check whether the component interacts with other components and systems as intended. Option 3: Incorrect. You don't test individual components during system testing. In this type of testing, you conduct a system test to check an application as a whole and ensure that the application meets client requirements.
1329
Option 4: Incorrect. Acceptance testing is performed by the representatives of a client. Rather than look for defects in an application, these representatives verify whether the application meets all their functional and nonfunctional requirements. Correct answer(s): 1. Component testing
Question Users of the web site should be able to locate links and navigation controls easily. Which test level helps you verify this requirement? Options: 1. Component testing 2. Integration testing 3. System testing 4. Acceptance testing
Answer Option 1: Incorrect. Ease of use and effortless navigation are external features of an application. Component testing can't help you test these features. It only helps you test the code for individual components of the application. Option 2: Incorrect. Integration testing helps you verify the interactions between individual components of an application. Option 3: Correct. Ease of use is one of the nonfunctional requirements of an application. You verify this requirement during system testing. Option 4: Incorrect. Acceptance testing helps verify whether an application can be deployed by the client. This level of testing is conducted directly by, or on behalf of, the client. Correct answer(s): 3. System testing
Evaluating test levels Your company develops gaming software for a wide range of customers and sells the software through its worldwide retail outlets.
1330
As a testing manger, you supervise the testing of the software. You're currently supervising the testing of a product aimed for children in the age group 7 through 10. The product will allow users to change display preferences and color schemes. Also, the product will provide four levels of complexity during each gaming session.
Question You ask developers to perform component testing on each component they develop. What type of defect can they discover during component testing? Options: 1. The processor of the product cannot resolve user input 2. A logic defect in the user-level management system 3. The product is incompatible with Microsoft Windows Vista 4. The target audience users find the graphical user interface confusing
Answer Option 1: Incorrect. The processor receives user input from another component, the user interface. You can verify whether it can interact correctly with the user interface during integration testing. Option 2: Correct. You use component testing to detect defects in a particular component, such as the component that manages user levels. Option 3: Incorrect. You verify the compatibility of a product with an operating system during system testing. You can make such verifications by simulating the environment in which the product will run. Option 4: Incorrect. The discovery that the target market users find the graphical user interface confusing will typically arise at the acceptance testing level, in particular, during beta testing. Correct answer(s): 2. A logic defect in the user-level management system
Question You are conducting system testing, and have simulated the environment in which the intended users will run the product. Which types of defects are most likely to be exposed during system testing? Options: 1. Too few of the intended users are able to reach level four of the game 2. The output of the user interface is corrupted after it's transferred for processing
1331
3. Sessions become slow for users at the third and fourth levels of a gaming session 4. The product is not compatible with computers that have less than 256 MB of memory
Answer Option 1: Incorrect. The ability of the user population to master the product as expected is tested during acceptance testing, not system testing. Option 2: Incorrect. The user-interface is one of the components of the product, and its output is corrupted while it is interacting with another component. You test the interactions between components during integration testing. Option 3: Correct. A nonfunctional requirement of any software product is that it responds to users within a reasonable period. You can verify such requirements only after you integrate the product and conduct performance testing. Option 4: Correct. To verify the compatibility of a product with a given system, you need to run it on that system. You simulate the environment in which a product will actually run during system testing. So you can use this type of testing to verify the compatibility of the product. Correct answer(s): 3. Sessions become slow for users at the third and fourth levels of a gaming session 4. The product is not compatible with computers that have less than 256 MB of memory
1332
Functional and Non-functional Software Testing Learning Objectives
After completing this topic, you should be able to
recognize how functional software testing works
recognize how non-functional software testing works 1. Functional software testing Testing happens at all phases of the product development life cycle. At every stage of development, testing reveals defects that need to be fixed to assure quality. When testing a software product at various levels, merely testing the functionality of each component or system is not always sufficient. You define test objectives for the various levels of development. To meet the overall test objectives, you focus your testing on specific objectives at each level. To meet these specific objectives, you use different test types. These test types are typically a set of test activities, focused on a specific test objective, used to test different components and systems. Different tests enable you to meet each specific objective in different test phases, whether you‘re testing a function or testing modifications made to the software. There are different test types:
functional testing – tests the functionality of a selected component
non-functional testing – tests the behavioral, or the quantified characteristics, of the systems and software
structural testing – tests the structural aspects of the component or system
changed-based testing – including regression and confirmation testing that involve the re-run of tests to ensure that the software is working correctly following changes Functional testing is the process of testing a software product to determine its specified behavior or functionality. As a functionality tester, you focus on the software's capability to provide functions that fulfill stated and implied needs under specified conditions. In other words, you test the function that the component or system needs to perform. For example, consider software that allows people to book tickets online. To test the functionality of this software, you would have to test whether the software accepts information requests from travelers, checks for ticket availability and reports back, accepts applications and returns tickets, and finally records the transactions in a database.
1333
Based on the International Organization for Standardization (ISO) quality standard 9216 that regulates testing, functional testing is performed for various quality characteristics, such as suitability Testing suitability involves testing the capability of the software product to provide an appropriate set of functions for specified tasks and user objectives. Suitability testing determines if the product performs as expected for its intended use. For example, a spreadsheet should provide you with an appropriate set of functions to perform financial, logical, mathematical, and trigonometrical calculations. interoperability Testing interoperability involves evaluating the capability of the system to interact with other specified components or systems. accuracy Testing accuracy involves ensuring that faulty products do not leave the production line and cause errors during beta testing. For example, if a word count feature in a word processing application does not function properly, accuracy testing would detect this defect before a beta user discovers it. Based on the standard, functional testing is also performed for various quality characteristics, such as security Testing security involves investigating the functions relating to prevention of unauthorized access to software and data, either intentionally or unintentionally. It also involves detection of malicious outside threats, such as viruses. For example, if readers can leave comments on your corporate blog, you will have to ensure that user input validation is performed in the comments area. There is the possibility of a malevolent user typing in malicious code, which gets executed automatically. Security testing would be able to capture this loophole in the code. compliance When you test compliance, you determine whether the system adheres to certain specified criteria, such as standards, conventions, regulations, or laws. For example, suppose that your organization's information security policy requires that employee system CD drives be disabled at all times. Code that is run every morning during system boot to verify that the drive is disabled would be checked during compliance testing. To perform functional testing, you derive your test conditions and cases from the requirements specification, functional specification, or from use cases. You design a model, such as a state transition model, a process model, or a plain language specification, as part of the test design.
1334
In all cases, the functional tests performed across all test levels would look at specific functions in a system, including undocumented or implicit functions. Because only the program specification is considered – not the design or implementation of the program – this type of testing is also called specifications-based or black box testing.
Note Black box testing can be either functional testing or non-functional testing and is performed without reference to the internal structure of the product. Two approaches to functional testing are: requirements-based testing Requirements-based testing designs tests based on a functional requirements specification for the system. To decide the items to test, you can use the table of contents of the requirements specification and prioritize the requirements based on the risk criteria. This ensures that the most important tests are included in the testing effort. For example, your company is revamping its HTML-based corporate web site. Your job is to test if the ASP.NET-based web applications display properly in a web browser that supports HTML. You refer to the requirements specification to create the test cases. business-process-based testing Use cases provide a basis for test cases from a business perspective because they often use business processes as a starting point. Business-process-based testing uses knowledge of the business processes to describe the scenarios involved in the day-to-day business use of systems. For example, your company's travel reimbursement system may have a policy that determines reimbursements for employees traveling on business.
Question Match each characteristic against its function. Options: A.
Accuracy
B.
Suitability
C.
Interoperability
D.
Security
Targets:
1335
1. Tests if the product performs according to specifications 2. Tests if the product is shielded from threats, such as viruses and other malicious software. 3. Tests to ensure that the faulty products are not passed to users 4. Tests if the product interacts correctly with other components or systems
Answer Suitability testing verifies that the product performs according to specifications and as expected for its intended use. Security testing investigates the functions relating to detection of threats, such as viruses, from malicious outsiders. Accuracy testing ensures that faulty products do not leave the production line and cause errors during beta testing. Tests if the product correctly interacts with other components and systems as specified. Correct answer(s): Target 1 = Option B Target 2 = Option D Target 3 = Option A Target 4 = Option C
Question You are the tester for a web-based banking application where financial data is requested from the user and stored in a confidential database. How would you perform functional testing for this application? Options: 1. Verify that unauthorized access to data is prevented 2. Test the quantified characteristics of the systems and software 3. Ensure that any shortfalls in the required level of precision of the application‘s results and effects are detected 4. Conduct tests that verify the impact of a modified operational system on the existing environment
Answer
1336
Option 1: Correct. Because customer financial information is confidential, you perform security testing to ensure its safety. Option 2: Incorrect. You test the quantified characteristics of the systems and software in nonfunctional testing. Option 3: Correct. You perform accuracy testing on the application to ensure that an application that does not meet required levels of precision is not released, particularly because it deals with sensitive financial data. Option 4: Incorrect. You test modifications and verify the impact of these modifications on the existing environment in maintenance testing. Correct answer(s): 1. Verify that unauthorized access to data is prevented 3. Ensure that any shortfalls in the required level of precision of the application‘s results and effects are detected
2. Non-functional software testing As well as testing the functional aspects of a software system, you must also test the nonfunctional aspects of the system. Suppose you are testing the operation of a mathematics package. You finish testing the functional aspects, such as fomulae and functions, and then move on to how well the package performs. Here, you would test how the system manages performance, load, stress, portability, and so on. This type of testing, where you measure how well or fast a system works, is called non-functional testing. In non-functional testing, which can be performed at all test levels, the behavioral characteristics of systems and software are tested and quantified on a varying scale. For example, you are testing a gaming application that will be hosted online and played by gamers simultaneously across the world. During functional testing, you determine what the application does, test its suitability for the web, verify compliance with online gaming standards, and so on. In contrast, when doing non-functional testing, you will test how the application performs, the load that it can handle, the speed with which it performs, and other aspects. Non-functional testing comprises various types of testing: 1. performance testing – tests the degree to which a system fulfills its specified functions within given processing time and throughput rate constraints 2. load testing – measures the behavior of a system with increasing load 3. stress testing – evaluates a system at and beyond the boundaries of its specified requirements
1337
4. usability testing – tests how easily a user can perform a specific task 5. maintainability testing – tests how easily a product can be modified in the future 6. reliability testing – tests how reliably a product performs over a given period of time 7. portability testing – tests how easily a system can be transferred from one platform to another According to ISO 9216 there are five characteristics covered by non-functional testing. These are further divided into sub-characteristics. The first two characteristics are reliability A software product is reliable when it performs its required functions under stated conditions. Reliability testing tests if the product meets the standards of reliability. Reliability testing can be defined further into maturity, fault-tolerance, recoverability, and compliance. For example, a server could be tested for robustness by increasing the number of users that access the server until it crashes. usability A software product is said to be usable if the user easily understands and likes the interface, likes the product itself, and finds it easy to operate. Usability testing tests the extent to which the software product meets these requirements under the specified conditions. Usability testing is divided into understandability, learnability, operability, attractiveness and compliance. For example, a graphical user interface could be tested to determine ease of use and navigation. The other three characteristics are efficiency Efficiency is the capability of the software product to provide appropriate performance, relative to the amount of resources used under stated conditions. Efficiency testing checks if the software is efficient. Efficiency testing is divided into performance, resource utilization, and compliance. For example, a web page could be tested to check if it loads quickly or not. maintainability The ease with which a product can be modified to correct defects, meet new requirements, make future maintenance easier, or be adapted to a changed environment is called maintainability. Maintainability testing is divided into analyzability, changeability, stability, testability, and compliance. portability When a software product can be transferred easily from one hardware or software environment to another, it is said to be portable. Portability testing is the process of testing to determine the portability of a software product. Portability testing is divided into adaptability, installability, co-
1338
existence, replaceability, and compliance. For example, checking the software code to verify if the application has been created to be platform independent or not.
Question Match the testing types with their explanations. Options: A.
Reliability testing B.
Usability testing
C.
Efficiency testing
D.
Maintainability testing
E.
Portability testing
Targets: 1. Test the ease with which a product can be modified to meet requirements 2. Test how easily a user understands an application's interface 3. Test how easily a software product can be transferred across platforms 4. Test the product's ability to perform required functions under stated conditions for a specified period of time 5. Test capability of the software to perform as specified
Answer Maintainability testing tests the ease with which product modification can be undertaken to correct defects, meet new requirements, or adapt to changes. Usability testing tests how comfortable a user is with an interface and how easy he finds it to operate when used under specified conditions. Portability testing is the process of testing to determine the portability of a software product. Reliability testing is the process of testing if the product meets the standards of reliability. Efficiency testing checks the capability of the software product to provide appropriate performance, relative to the amount of resources used under stated conditions. Correct answer(s): Target 1 = Option D Target 2 = Option B
1339
Target 3 = Option E Target 4 = Option A Target 5 = Option C
Summary Test types are activities that help you in testing systems of components to check if they meet specific test objectives. There are a number of test types. Functional testing checks if the software product under test meets all its functional specifications. It also checks if the software product has the characteristics of suitability, interoperability, security, accuracy, and compliance. Non-functional testing checks certain quality characteristics of the software product. This includes checking for performance, reliability, portability, usability, and maintainability.
1340
Structural and Changed-based Software Testing Learning Objectives
After completing this topic, you should be able to
recognize how structural software testing works
recognize how change-based software testing works 1. Structural software testing Every time a system or a component is developed, you test it to verify that the system not only works as specified but also as efficiently as required. To aid you in this testing, you are provided with test objectives and test types. The test objectives will define the test types which are used, such as functional testing or blackbox testing, non-functional testing, structural testing, and regression testing. Each test type has specific types of test objectives pertinent to that type of test. You carry out functional testing to check that the application does what the functional specification requires. Since functional testing is not directly concerned with the inner workings of the software, and only on what it actually does, it is sometimes referred to as black-box testing. Structural testing on the other hand is concerned with the internal architecture and workings of the software, and for that reason is often referred to as white-box, or glass-box, testing. Structural tests can be carried out at all test levels. However, they are mostly performed at the lower test levels such as at the component and the component integration level. At the component level, the tests are based on the structural aspects of the system such as code in a program. And at the component integration level, the tests may be based on the architecture of the system, such as a calling hierarchy. Structural tests measure the amount of testing done by checking the coverage of a set of structural elements or coverage items. In structural testing, in addition to testing the coverage of a set of structural elements or coverage items, the internal system design is considered and the tests are based on the logic of the application's code. But in functional testing, the tests are based on the requirements and the functionality. For instance, when testing a data object, functional testing tests the working of the data object. And structural testing verifies if the data object has the specified data fields with correct data types.
1341
So, in structural testing, you are required to have knowledge of the internal working of software and the code. Regardless of the specifications, you are required to test each command in the code. To ensure that you are testing your program adequately, you need to execute all the elements such as statements, branches, conditions, and decisions in the code one by one. The coverage achieved in structural testing is expressed as a percentage of the items being covered. There are a variety of tools and methods available to support code coverage measurement at component and integration testing levels. These tools measure the percentage of executable elements. If the coverage is not 100%, then more tests may be designed to test those items that were missed, and thereby, increase the coverage. You use various structure-based techniques to implement structural testing. These techniques are also called white-box techniques. They are based on an analysis of the structure of a component or a system. Two examples of code-related structural testing techniques for code coverage at the component level include statement testing and decision testing. White-box techniques can also be used at various levels, such as component At the component level, the structure is that of the code itself, such as in the statements or decisions. integration The structure at the integration level could be a call tree where modules call other modules. system At the system level, the structure may be a menu structure, a business process or a web page structure.
Question Which of these are accurate statements when applied to structural testing? Options: 1. Is also referred to as white-box testing 2. Is also referred to as black-box testing 3. Is used to measure the coverage of functional requirements that have been satisfied 4. Is used to measure the percentage of code elements that have been executed.
1342
Answer Option 1: Correct. Because structural testing is concerned with the internal structure of a component or system, it is also known as white-box, or glass-box, testing. Option 2: Incorrect. Black box testing is so called because it is not concerned with the inner workings of a component or system, unlike structural testing. Option 3: Incorrect. Functional testing, not structural testing, is primarily used to test whether functional requirements have been met. Option 4: Correct. Structural testing incorporates code coverage measurement to determine the percentage of executable elements that are activated during testing. Correct answer(s): 1. Is also referred to as white-box testing 4. Is used to measure the percentage of code elements that have been executed.
Question You are testing an application. Which of these steps will you do while performing structural testing on the application? Options: 1. Measure the amount of code used in a system 2. Test all the elements in the code 3. Use structure-based techniques to test components 4. Complement functional tests by measuring the number of tests performed 5. Check how much of the item being tested is covered by the test
Answer Option 1: Incorrect. While performing structural testing, you measure the amount of a system or component that is covered by the test. Option 2: Correct. In structural testing, you execute all the elements in the code such as the statements, branches, conditions and decisions in the code. Option 3: Correct. At component level testing, you use structure-based techniques such as statement testing and decision testing.
1343
Option 4: Incorrect. You would complement functional tests by measuring the extent of the item that has been tested, not the number of tests performed. Option 5: Correct. To measure the thoroughness of the tests performed earlier, your structural tests check the coverage achieved by those tests. Correct answer(s): 2. Test all the elements in the code 3. Use structure-based techniques to test components 5. Check how much of the item being tested is covered by the test
2. Changed-based software testing Testing is carried out at every stage of the product development to discover the defects, if any, and fix them. This ensures that the product is defect free and works as specified. Every time you find a defect and fix or debug it, you need to retest the debugged component by re-executing the test cases that failed the last time. The product is considered free of known defects only when it passes the retest. This type of retesting is called confirmation testing. Confirmation testing by itself does not guarantee a quality product. Even after confirmation testing, because of fixing a bug, or any other modification such as the addition of a new feature, a debugged or new version of the software can lose its original functionality or a part of it. When this happens, the new version is said to have regressed with respect to former versions, and is defective again. A systems or component that has had changes carried out needs to be tested again to ensure that none of its functionality was modified unintentionally. A set of tests are designed to demonstrate that despite the changes that were made, the system works as expected. These tests are called regression tests and the testing is called regression testing. Like confirmation testing, regression testing involves executing test cases that were executed before. However, confirmation testing is performed on the items that failed the tests the last time they were executed, to confirm that the developers have fixed the defects. And regression testing is performed to ensure that previously working parts of the system have not had faults introduced as a result of these fixes. There are three types of regression:
local regression – a change or a bug fix in the existing software creates a new bug
exposed regression – a change or a bug fix in the existing software reveals an existing bug
1344
remote regression – any change or a bug fix in one area triggers an error in another area of the system While performing regression testing, most organizations use a regression test suite, which is a set of test cases used for regression testing at each level. And where the postcondition of one test is used as a precondition for the next one. Also because the same test cases are used every time, the test cases can be used for test automation. The test cases perform an overall testing of each of the most important functions in a system. They are executed every time software is updated or the environment is changed. It is important to maintain the test suite so it stays updated with the latest software version. So every time new functionality is added to software, new regression tests should also be added and the older and irrelevant tests removed. In a situation where the regression test suite becomes very large, and the tests need to be executed, a subset of the test cases can be chosen. This is because it is difficult to execute all the tests manually or simultaneously. In such cases, or in cases when the test cases have not captured a defect in a long time, repetitive tests can be combined or, if needed, even eliminated, but with care.
Note Unlike the other types of testing, regression testing can be carried out only at the very end, after the last code that was changed is tested and quality passed. It is also important not to omit regression testing because the risk involved is huge. Consider a case where you have added a new feature to an existing product. While functional tests help you verify the functionality of the features, non-functional tests test the behavioral characteristics of software, which are quantifiable on a varying scale. And structural tests measure the amount of the developed component that has been exercised by testing. After running the new code through all these tests, you find it passes the tests and is free of known defects. You release your product to the market confidently. And then suddenly find out that faults have surfaced in parts of the system that were previously working OK. There are a number of strategies available to capture defects in the regressed software to avoid such situations. The main strategies are repeating all the tests If you have sufficient time and resources to cover critical risks, repeat all your tests after the last change to the code. You should be able to find all the important regression bugs. However, if you are repeating these tests for large, complex systems, you can use automation. repeating some of the tests
1345
It is not always possible to repeat all the tests. Executing all the test cases for a large and complex software product may require too much time and too many resources to be practical every time the product is updated. Even if you consider automation, you may find that full automation is impossible or impractical. In such cases, you can repeat some tests only. Other strategies are using cross-functional tests You use cross-functional tests to capture accidental regressions. Otherwise, because you are not going to be running all the tests again, you are likely to miss regressions that may occur in unanticipated areas. releasing the product in various phases You can also choose to release your updates on the product in phases. You will need to phase your release so that you have more time to ensure that your product is thoroughly tested. having other users testing the product (Beta testing) When you send your product for a Beta test, it will be your users who will be testing your product for you before the commercial release. If you find yourself bogged down with schedule pressure, instead of releasing poorly tested emergency patches, it will be a good idea to release smaller but well tested patches to only those users who need them. You can then roll the final and completed patches into maintenance releases instead. Doing this will ensure that the regression risk increase for your users is only short term. If you are using the strategy of repeating tests, you will need to decide which of the tests to repeat. To decide which tests to repeat, you can use techniques, such as traceability You use the traceability technique when you want to check whether any requirement, design element, or quality risk is affected by the software modification. You would have a set of tests related to the behavioral descriptions of the system. You trace back to these tests and re-execute them. change analysis When you want to analyze how changes in one part could trigger off changes in other portions of the system, you use the change analysis technique. So you look at the structural descriptions to find the answers. To be able to do this, you need to have an indepth understanding of the code and the system's design. quality risk analysis If you want to decide what to retest based on business risks, you should use the quality analysis technique. Even though defects are unlikely here, you will have knowledge of the areas that are
1346
prone to high business risk. Using traceability and change analysis techniques will only help you select tests based on technical risks.
Question Match the four test types with their definitions. Options: A.
Functional testing
B.
Non-functional testing
C.
Structural testing
D.
Regression testing
Targets: 1. Is based on an analysis of the internal structure of a component or system 2. Tests the working of a component or system and how it interoperates with other specific systems 3. Confirms that the system works as expected even after changes 4. Tests the behavioral aspects of the system
Answer Structural tests measure the amount of a component or system that has been exercised by testing against the total amount possible, which is known by reference to the internal structure. When you perform functional testing, you focus on the testing of a function that the component or system needs to perform. When you perform regression testing, you create a set of tests that demonstrate that the system works as expected despite the modifications made. When you perform non-functional testing, you test the characteristics of systems and software that can be quantified on a varying scale. Correct answer(s): Target 1 = Option C Target 2 = Option A Target 3 = Option D Target 4 = Option B
1347
Question You are testing courses for an online education provider who has converted all Director-based courses to Flash. You do not have the time to repeat all the tests. How would you perform your regression tests? Options: 1. Repeat all the tests nevertheless 2. Repeat some tests only 3. Automate all the tests 4. Use techniques such as traceability, change analysis, or quality risk analysis
Answer Option 1: Incorrect. Repeating all the tests is not only impractical, it is impossible considering that you do not have the time to repeat all of them. Option 2: Correct. Even if the best thing would be to run all the tests again, when you do not have the time for doing it, you repeat only some of the tests. Option 3: Incorrect. Automating the tests is not possible without a test suite. Option 4: Correct. When you've decided to repeat some tests only, you can use different techniques to decide which tests to repeat. Correct answer(s): 2. Repeat some tests only 4. Use techniques such as traceability, change analysis, or quality risk analysis
Summary Structural tests are based on an analysis of the internal structure of a component or system, and measure the amount of structural elements or coverage items that have been exercised by testing. The structural aspects could be the code in an application or the logic behind a decision. While these tests can be carried out at all levels, they are mostly performed at the component and integration levels. Change-based testing is concerned with testing that is carried out on foot of changes made to a component or system. Confirmation testing is performed on items that failed the tests the last time they were executed, to confirm that the developers have fixed the defects. And regression
1348
testing is performed to ensure that previously working parts of the system have not had faults introduced as a result of these fixes.
1349
Maintenance Software Testing Learning Objective
After completing this topic, you should be able to
recognize how maintenance software testing works 1. Maintenance software testing To ensure a product is free of known, unacceptable defects, and meets user requirements, you need to perform testing at every stage in the product development life cycle. You have to carry out functional and non-functional testing in the initial stages of the development and then follow it up with structural, confirmation, and regression testing in the later stages. After the product is deployed and in use for a number of years, it may require maintenance work to be carried out on its components. This work may be to correct defects, to improve performance, or to adapt the product to a modified environment. To confirm that the modified product is once again free of known defects, you need to retest the modified components. This is termed maintenance. And this type of retesting when you test a system, which is in operation in a live environment, is called maintenance testing. Maintenance testing not only tests the changes to the operational system, but also the impact of this modified system on the existing environment. The main reasons for using maintenance testing include modifications Modifications refer to any enhancements and emergency corrections made to an operational system. They also include environment changes such as operating system or database upgrades and patches for rectifying any vulnerabilities. Maintenance testing for modifications involves verifying that these changes do not adversely affect the system. For example, your organization has upgraded its database and installed a patch to a newly discovered operating system vulnerability. You have to ensure that the data is not lost and that these changes do not affect any other functionality in the system. migrations Migrations refer to a transfer of a system from one platform to another. Maintenance testing for migrations involve operational testing of the new environment and the modified software. This operational testing is conducted to evaluate the working of the migrated system or component in its new operational environment, which typically consists of software installed at the users site. For example, your organization is migrating to a new environment. After migration, the modified
1350
software may not work as required. You have to ensure that the new environment and all software specially modified for it, work fine. retirement of the system Maintenance testing for the retirement of a system refers to testing of data migration. Or, if data is to be retained for long periods, archiving is considered. For example, your organization is retiring a server and replacing it with another one. All the data stored in the old server has been transferred to the new server. Some of the tables were merged in the process. You have to check that all the data was transferred accurately and into the specified rows and columns of the new tables. Of the main reasons for maintenance testing, modifications are the ones most frequently occurring in organizations, and therefore very important. From the view point of testing, modifications can be classified into Planned modifications Planned modifications account for around 90% of the maintenance work. They are structured modifications and are decided well in advance. Planned modifications include three types of modifications. Perfective modifications refer to changes such as including additional features or enhancing performance of the system. Adaptive modifications refer to changes such as the product being retired or migrated to a new platform or new environment, new software, or new legislation. Corrective planned modifications refer to changes such as deferred defects being finally corrected. Unplanned modifications Unplanned modifications occur when defects arise suddenly and the consequent malfunctions require an immediate solution. For example, a server being patched when a security vulnerability is discovered. By carrying out a risk analysis on the operation system, you can be prepared to minimize the impact of most unplanned modifications by, for example, having those tests that will most likely be required already designed and ready. During maintenance testing, two fundamental tests are carried out to ensure the quality of the product:
confirmation tests – to verify that changed software is functioning correctly after the changes have been carried out
regression tests – to check that unchanged software is continuing to work as expected following changes being carried out on different parts of the system Ideally, maintenance testing should test all the changes made to the system and the working of the entire system itself. However, this may not always be cost effective or even possible. So to
1351
reduce the amount of regression testing, you should always first determine the parts of the system that could be affected because of the maintenance work. Analyzing this impact of the changes on the system is called impact analysis. Maintenance testing often makes use of original test specifications with some updates applied. An impact analysis helps in assessing the amount of updating required to the original test specifications. However, it may be difficult to conduct an impact analysis for a system which has already been released. This is especially the case when a product's specifications are out of date, or unavailable, and/or the original development team has moved on to other projects, or is no longer with the company. Impact analysis enables you to focus your regression test activities where they are most needed. The process involves: performing a risk analysis The function of a risk analysis is to establish which of the areas of a software product constitute the greatest risk to the operational services. When you do not have the time to repeat all the tests, you perform a risk analysis to help you determine which areas to focus on during regression testing. For example, you perform a risk analysis on a software system that malfunctions to help you decide where to focus first and what to do next and where. checking for the product's original test specifications If you have the test specifications from the original development process, you can reuse them for the regression tests. You do this by adapting them for changes to the system. For instance, you may just change the expected results for the original tests. This helps in reducing the overall regression testing time. This also helps you decide if you need to build additional tests for specific areas, which is often the case for enhancement or extension projects or for updates for automated test sets that support regression testing. There are some specific differences between maintenance and regular testing for new products. The differences are due to factors, such as test types Maintenance testing can include all test types that a new product undergoes, although often only a subset of test types is required. For example, usability testing is unlikely to be required if changes affecting the user experience have not been made. In most cases however, regressions and confirmation tests form part of maintenance testing. Maintenance testing is also different from maintainability testing, which is a test to determine how easily a system can be maintained. It also
1352
tests how quickly a system can be modified to meet new requirements, adapt to a changed environment, or correct existing defects, and make future maintenance easier. test triggers While testing for new products is carried out as part of a project, maintenance testing is carried out as an activity in a regular organization, only when there are modifications to the system, or migration, or retirement activities. This makes maintenance testing more prone to challenges such as resource availability, flexibility, and competition from other activities when compared with regular new product testing. issues faced When systems are maintained for a while, a number of defects come to light. Specifications are needed, but unlike in the testing for a new product, they are often unavailable. Also whenever there is an extension or addition, specifications have to be created. For this you can use documentation similar to the original product specifications. But this poses a problem too as you may end up having many test cases executing the same scenario. And because no traceability exists, if an incident is found, it is difficult to trace it back to the actual defect. From a test management perspective, a somewhat different path is followed for maintenance testing as against new product testing. Suppose you are the test manager carrying out the fundamental test activities for a new product. Upon the receipt of an application for a product test, you produce a test plan using the application as a basis. Next, you receive test specifications and create test cases, which you execute upon receiving the test object. Finally, upon completion of the testing, you preserve the testware. Suppose you are carrying out the fundamental test activities for a maintenance product instead. You will follow the same process followed for a new product, except for when it comes to the test specifications. This is because unlike in regular product testing, test specifications may not be available. Especially in the case of enhancements or extensions. So, if test specifications are not available, and if it is impossible to compile them again, you use an alternative test basis such as a test oracle. The test oracle contains information that is used to determine expected results to compare with the actual results of the tested product. The oracle may be anything from the current system in use to a tester's knowledge, as long as it is not code. Finally, upon receipt of the test object, you execute the new and modified tests and perform the regression tests, and then preserve the testware.
Question Match the definitions of the terms used in maintenance testing to the corresponding term.
1353
Options: A.
Maintainability testing
B.
Test oracle
C.
Impact analysis
D.
Operational environment
E.
Maintenance testing
Targets: 1. Assessment of the how a component and its test and development documentation are affected by the implementation of a specified change 2. Tests the changes to an operational system or impact of a changed environment to an operational system 3. Helps determine the expected results for a software 4. Determines ease of maintenance of the system 5. Comprises hardware and software products installed at users' site
Answer Impact analysis is the assessment of change to the layers of development and test documentation, and to a component, in order to implement a given change to specified requirements. Maintenance testing tests a system that has been modified but is in operation in a live environment. It also tests the impact on a system of a change made to its operating environment. A test oracle provides a source determining the expected results for a software being tested for comparison with the actual results later. Maintainability testing determines how quickly a system can be modified to meet new requirements, adapt to a changed environment, or correct existing defects, and make future maintenance easier. The software in the operational environment can include database management systems, operating systems, or such other applications. Correct answer(s): Target 1 = Option C Target 2 = Option E Target 3 = Option B Target 4 = Option A Target 5 = Option D
1354
Summary Maintenance testing is carried out to test the functioning of an operational system that has been modified. It also tests the impact of a changed environment on a system. The reasons for maintenance testing include maintenance fixes, modifications, or migrations. Maintenance testing involves all test levels and can also involve any test type. Two of the more common test types that occur during maintenance testing are confirmation and regression tests. Confirmation tests verify the results of the fixed defect. And regression tests retest the entire system again in case the fixes have affected any existing functionality. To reduce time spent on regression testing, an impact analysis is carried out. The impact analysis determines areas that specifically require regression testing after the maintenance work.
1355
Models of Software Testing and Development Learning Objective
After completing this topic, you should be able to
evaluate test types Exercise Overview In this exercise, you are required to evaluate test types. This involves the following task:
evaluating functional, non-functional, structural, change-based, and maintenance test types
You are a tester in a software development company. You are currently involved in two projects. In the first project, you are testing a software order/cash management system. In the second project, you are involved in testing an online audio tool.
Note You are currently involved in two projects. In the first project, you are testing a software order/cash management system.
Evaluating test types You are testing a sales order management system for a fast food restaurant. You want to evaluate which test types would be most effective at each stage of the product's life cycle.
Question The product is at the initial phase of the development life cycle. And the code for the order/cash management system has different elements such as the part that allows for ordering, the part that calculates the prices/taxes, and the part that transmits the order to the cooks. Each element of the code is developed separately and then sent for testing. The elements will all be integrated at a later date. Which test types would be most effective at this stage of the product's life cycle? Options: 1. Functional testing
1356
2. Confirmation testing 3. Structural testing 4. Regression testing
Answer Option 1: Correct. During the first phase of the product's development life cycle, you check if the product meets the functional specifications. Option 2: Incorrect. Confirmation testing is conducted on elements that have previously failed a test, and have been submitted for a re-test. Option 3: Correct. During the first phase, each developed component is subjected to an analysis of the component's internal structure and its implemented behavior. And to do this, you perform structural testing. Option 4: Incorrect. Regression testing is performed at the end of the product's development life cycle. Correct answer(s): 1. Functional testing 3. Structural testing
Question The elements of code are all now integrated and the complete product is now sent for testing. What test type would be most effective at this stage of the product's life cycle? Options: 1. Confirmation testing 2. Non-functional testing 3. Regression testing 4. Functional Testing
Answer Option 1: Incorrect. Confirmation testing is carried out after the defects found in an earlier round of testing are fixed. Confirmation testing is like a verification round of testing. Option 2: Correct. As part of system testing you should test that the system has achieved an acceptable level of quality.
1357
Option 3: Incorrect. Regression testing is performed after confirmation testing when the defects that were found are fixed. Option 4: Correct. Functional testing is conducted to ensure that the integrated system performs according to specification. Correct answer(s): 2. Non-functional testing 4. Functional Testing
Question A number of defects were discovered during the non-functional testing. All these defects were rectified. The product was also passed through a round of confirmation testing. However, there is a slight possibility that the defect fixes altered the overall functionality of the software. What test type would be most effective at this stage of the product's life cycle? Options: 1. Functional testing 2. Maintenance testing 3. Regression testing
Answer Option 1: Incorrect. Functional testing is performed in the initial stages of the product development when you want to check the functionality of any product and verify how it interoperates with other systems. Option 2: Incorrect. Maintenance testing is performed only after the product is completed and deployed to the customer. Option 3: Correct. Regression testing is performed when as part of a process, you find or suspect that because of the addition of a new feature, or fixing a bug, a new version of the software may have lost some functionality that was previously present. Correct answer(s): 3. Regression testing
Question
1358
After regression testing was performed, and the product cleared for delivery, the system was released to the client. A couple of years later, an online ordering/delivery system was added. What test type would be most effective at this stage of the product's life cycle? Options: 1. Non-functional testing 2. Structural testing 3. Maintenance testing
Answer Option 1: Incorrect. Although some non-functional testing may be involved, maintenance testing is called for at this stage of the product’s life-cycle. Option 2: Incorrect. Structural testing is performed during the various stages of the product's development life cycle and not after the product deployment. Option 3: Correct. Maintenance testing is performed when you want to check a system operating in a live environment after post-delivery changes are made to it. Correct answer(s): 4. Maintenance testing
1359
ENGLISH
| Print | Back | Close |
Business Grammar: Punctuation SkillBriefs
End Punctuation Marks -Explore the rules for using end punctuation. Using the Comma Correctly -Explore the correct use of commas. Using Connectors and Separators -Learn how to use semicolons, colons, and dashes correctly. Using Other Punctuation Marks -Explore apostrophes, parentheses, and quotation marks.
1360
SkillBrief
End Punctuation Marks All sentences need to be ended with either a period, a question mark, or an exclamation point. These punctuation marks indicate the end of a sentence, separate thoughts, and keep ideas moving cohesively toward a conclusion. They help the reader move in the same direction toward that conclusion.
The period The period – also referred to as the full stop – is one of the most commonly used punctuation marks in the English language. Periods are used
to close declarative, imperative sentences, and indirect questions
in single-word abbreviations
after a number in a list or outline
in Internet addresses, and
to indicate an ellipsis, which is the omission of a word, phrase, line, paragraph, or more from a quoted passage
The question mark Questions come up every day in business. It's when you have to communicate questions in writing that problems can arise. Question marks
are always used after direct questions
are not used after indirect questions, which report what someone has asked but not in the form of the original question
are occasionally used to indicate surprise or skepticism
are not used when a request is politely disguised as a question, and
are never combined with other question marks, exclamation points, periods, or commas.
You can also use question marks in the following types of sentences:
statements – Question marks can turn statements into questions. For example, the statement "He finished the report yesterday" may be turned into a question that indicates surprise or doubt – "He finished the report yesterday?"
elliptical questions – Elliptical questions are questions that refer back to other questions or statements. Elliptical questions are incomplete in that they can't stand on their own but rely on other parts of the statement for their meaning.
questions within a sentence – Question marks are most commonly used at the end of sentences, but they can also be used within a sentence. A question might end with a question
1361
mark, but the sentence as a whole ends with a period. For example, "The question, how can we finish on schedule? was on everyone's mind."
questions in a series – Each question in a series should be followed by a question mark.
questions in quotes – You place a question mark inside quotes only when it's part of the quoted matter. But the question mark follows quotes when the entire sentence is a question.
question marks within parentheses – You can use question marks within parentheses to indicate doubt about the correctness of a number, date, or other fact. But you should avoid using a question mark within parentheses to express sarcasm or irony.
The exclamation point An exclamation point marks an emphatic comment or indicates excitement. You can use it in two ways:
to show emphasis or strong feelings – An exclamation point tells the reader that you are emphasizing a statement or that you have strong feelings about what you are saying – as in the example "We need to succeed!" Interjections, or exclamations – which are words, phrases, or clauses that denote strong feeling – often end in exclamation points. For example, "Wow! That meeting was long."
with questions that functions as exclamations – An exclamation point is also a valid ending for a rhetorical question, or a question that is essentially an exclamation – for example "How could you do that!" Rhetorical questions don't require answers; they emphasize a point. For example, "Can you believe that was the final result!"
A caveat is that you should use exclamation points sparingly. Otherwise, they won't be effective. If you succeed in building the excitement into your sentences, you won't need an exclamation point to tell the reader how to read them. End punctuation marks indicate the end of sentences, and they separate thoughts. They also keep your ideas moving cohesively toward a conclusion by helping the reader move mentally in the same direction toward that conclusion. End punctuation marks are the period, question mark, and exclamation point. The period's primary purpose is to end a sentence. Question marks are always used after direct questions, and exclamation points suggest excitement or add emphasis to a sentence.
1362
Using the Comma Correctly Commas are used more often than any other punctuation mark, so it's really worth your effort to learn how to use them correctly. The placement of commas can change the entire meaning of a sentence. Commas make your writing easier to understand and serve several major functions:
They make your writing easier to understand because they create boundaries between ideas, which makes them more clear.
They indicate pauses or changes in mental direction, which makes it easier for readers to follow.
They demonstrate your professionalism by showing that you care about the details in your writing, as well as the reader's comprehension.
Correct usage Commas separate parts of a sentence in three ways:
commas separate the main elements of a sentence
o
Most introductory clauses are separated from main clauses by commas. An introductory clause may be a subordinate clause, a verbal phrase, or a prepositional phrase. A single word or a very short introductory phrase doesn't usually require a comma, except to avoid misreading.
o
Transitional expressions such as currently or in fact used at the start of a sentence are followed by commas. And expressions such as fortunately and in other words, which provide comments, explanations, or other supplementary information, are followed by commas as well.
o
You also use a comma to separate main clauses connected by a coordinating conjunction.
they set off nonessential elements within a sentence
o
These elements – also referred to as nonrestrictive elements – are not essential to the meaning of the sentence. They also don't limit a word to a particular individual or group.
o
However, restrictive or essential elements in a sentence aren't set off with commas. They limit the word they refer to and cannot be omitted without leaving the meaning too general.
o
Clauses and phrases that act as adjectives and adverbs may be either nonrestrictive or restrictive. But only nonrestrictive ones are set off with commas. An appositive renames a noun just before it. Many of these are nonrestrictive
they separate elements in a series o
You place commas between all items in a series – that is, between three or more items of equal importance. The basic rule is that commas separate each word or phrase listed consecutively in a series.
1363
o
You also use commas to separate two or more adjectives that equally describe or modify the same word. If you have two or more adjectives before a noun and you could – without affecting the meaning – connect those adjectives with and, you normally separate them by commas.
Incorrect usage The comma is often used incorrectly or not used when it should be. Four rules may help keep you from misusing commas:
don't separate a subject and its verb – Never use a comma to separate the subject of a sentence from the verb. This applies even when the verb and predicate come first.
don't separate a verb and it object or complement – The object of a verb is the target of the action indicated by the verb. For example, in the sentence "I hit the ball," ball is the object of the verb hit. You shouldn't put a comma after the verb and before this object.
don't separate pairs joined by a coordinating conjunction – When linking elements with a coordinating conjunction, you don't use a comma except when the elements are main clauses. So you shouldn't have a comma after wrote in the sentence "She wrote and took photographs for the local paper." This sentence includes an example of a compound predicate – or two verbs that share the same subject.
don't use a comma after a conjunction – Coordinating and subordinating conjunctions are not followed by commas. For example, you don't put a comma after but in the sentence "She was early, but she had to prepare the room for the meeting." And you wouldn't put a comma after although in the sentence "Although the price has gone down, it's still not worth the money."
The main purpose of the comma is to separate thoughts in a sentence. The comma serves three other common functions or uses in a sentence – to separate the main elements of a sentence, to set off nonessential elements within a sentence, and to separate elements in a series.
Using Connectors and Separators You can use various punctuation marks to connect and separate elements within sentences. These punctuation marks have similar functions, and it can sometimes be difficult to figure out which is most appropriate to use.
Semicolons Semicolons can join complementary main clauses that are not linked by a coordinating conjunction. They can also connect ones that are related by a conjunctive or linking adverb or other transitional expression. Semicolons are used to join main clauses in two situations:
they're not joined by a conjunction – Semicolons join balanced sentences or clauses.
they're related by a conjunctive adverb – Semicolons should be also used with two main clauses that are linked by a conjunctive adverb, such as furthermore, in fact, or however, as well as by
1364
other transitional expressions, including words like currently, finally, or as a result. They can also replace these words. The position of the semicolon between main clauses doesn't change. However, the conjunctive adverb or transitional expression can be placed in different places within the clause. Sometimes you can use a semicolon to separate main clauses that are joined by a conjunction. This is the case if the clauses are complicated or contain internal punctuation, such as commas. Similarly, you can use semicolons to separate items in a series if they're long or contain commas. You shouldn't use a semicolon to separate subordinate clauses or phrases from main clauses. Doing so will create a disjointed sentence. And you also shouldn't use a semicolon to introduce a series or an explanation. Colons are used for this purpose.
Colons You can use colons in several types of sentences:
an explanation – for example, We made many mistakes: the underlying reason for all of them was that we didn't think about the customer.
a series – for example, The following issues are on the agenda for the meeting today: appraisals, sick leave, and deadlines.
a quotation – for example, The report starts out positively: "We can increase sales by 10% this year."
a greeting – for example, Dear Mr. Smith:
When a colon is used within a sentence, the first word following the colon is lowercased, except when it's a proper noun. When a colon introduces two or more sentences, however, the first word following the colon is capitalized. It's also capitalized if the colon introduces a quote, a speech in dialogue, or an extract. And you should use a colon only at the end of a main clause. For example, don't use it after a verb or a preposition.
Dashes A dash is used mainly to indicate sudden changes in tone or thought. It's also used to set off some sentence elements. More specifically, dashes can set off the following:
digressions – Dashes can mark a point in a sentence where someone deviates from the original point. They may indicate an abrupt change in thought or content.
afterthoughts – Dashes can also provide additional information.
concluding explanations – A clause following a dash can provide a concluding explanation of what's stated in the previous clause. Note that a dash sets off a concluding explanation more informally and more abruptly than a colon does.
1365
nonessential elements – Dashes are used to add additional descriptive phrases or clauses to a sentence. They may be used in place of commas or parentheses to set off nonessential elements in a sentence.
Dashes are especially useful when the descriptive content has internal punctuation. You should use a pair of dashes when the content element interrupts a main clause. It's not a good idea to use too many dashes in your writing – it can lessen their effect and create a jumpy quality in your writing. A dash isn't typically used with other punctuation marks. Sometimes a question mark or an exclamation point may precede a dash – but never a comma, a colon, or a semicolon, and rarely a period. In addition, you usually include spaces before and after a dash. However, some prefer not to add a space on either side. Either way is acceptable. Commas, semicolons, colons, and dashes are punctuation marks that connect and separate words, phrases, clauses, and sentences. They have similar yet different functions that can depend on the meaning you want to convey and the type of sentence you write. Knowing when and when not to use these punctuation marks will help you clarify what you want to communicate.
Using Other Punctuation Marks You may consider the apostrophe, parentheses, brackets, and quotation marks to be unimportant compared to the punctuation marks used most frequently, such as periods and commas. However, these four marks have important functions.
The apostrophe The apostrophe is used to mark the possessives of nouns and some pronouns in several instances:
noun doesn't end in an s – If a noun is singular and does not end in s, the possessive is formed by adding an apostrophe and an s. This also includes irregular plural nouns – for example media's – and indefinite pronouns – anyone's files.
noun does end in an s – If a singular noun ends in s or the s sound, you form the possessive based on how the word is pronounced. If you naturally say two s sounds, then use the apostrophe s, as in James's. If you pronounce the word with only one s sound, just use the apostrophe on its own, as in employees'.
pronounced ssyllable is added – If a noun ends in s, and a pronounced syllable is added when the noun is changed to the possessive form, then add an apostrophe s. For example, "The witness's statement."
Letters and numbers can be replaced with apostrophes to create contractions or short forms of dates. The apostrophe is inserted where the letters or numbers are left out. Contractions shorten words or phrases to conserve space or to create a less formal tone in a document. And remember, because contractions aren't abbreviations, they aren't followed by a period. The following are all contractible elements:
1366
words – By established convention, letters can be left out to shorten words – international becomes int'l, for example. These types of contractions are used in informal writing and may be more common in formats that have very limited space – such as in addresses. The dictionary lists many common contractions, along with alternative spellings and, where appropriate, plurals.
phrases – In conversational language, letters can also be left out to shorten certain phrases. For example, you are becomes you're and I have becomes I've.
dates – An apostrophe is also used to replace numbers in a date. For example, the '60s instead of the 1960s. Remember that you don't use an apostrophe between the last number and the s.
plurals – You can also use the apostrophe to form the plural with lowercase letters and abbreviations with two or more interior periods or with both capital and lowercase letters – as in Ph.D.'s and x's and y's. Remember that you never use an apostrophe with an s to make a plural noun from a singular noun.
Parentheses and brackets Although very similar, parentheses and brackets have different purposes:
Parentheses are used to provide clarification of certain words that may appear to be vague or unclear. Or you use them to provide additional explanations, facts, and examples that may be helpful or interesting but aren't crucial to the meaning.
You can use parentheses for afterthoughts.
You use parentheses to add personal comments to your sentences.
Parentheses typically enclose material that is less closely related to the rest of the sentence than that set off by dashes or commas. So the content within parentheses is emphasized less than if it were set off by commas or dashes. And remember not to put a comma, semicolon, or period before a parenthetical expression. You use brackets in the following instances:
use of the word [sic] – The word sic is Latin for in this manner. It's used in brackets to indicate that an error in the quotation appeared in the original and was not made by you.
add clarifying material – If you need to clarify the words of the writer you quote, you place your additions in a pair of brackets.
indicate comments – The term emphasis added is used within brackets after a quote to indicate that you have emphasized a word or phrase within the original quote.
Finally, if you need to explain or comment on something within parentheses, then you use brackets.
Quotation marks Generally, the double quotation mark is used to enclose a direct quotation, whether made by a person or taken from a piece of literature.
1367
Double quotes are sometimes used to indicate a word is used in a special sense – as in "intelligent" robots. Writers sometimes put quotation marks around a word they're using with irony. This practice is discouraged in business writing. Quotation marks are also used around titles that are part of a published work. For example, the titles of book chapters, short stories, magazine articles, essays, poems, songs, lectures, and conference themes take quotation marks. Single quotation marks are used inside a statement that's already enclosed by double quotation marks. Specific rules apply when using other punctuation marks with quotation marks:
periods and commas – Periods and commas always go inside the closing quotation mark.
semicolons and colons – Semicolons and colons always go outside the closing quotation marks.
question marks and exclamation points – You should place question marks and exclamation points inside quotation marks only if they belong to the quotation. When a question mark or exclamation point applies only to the larger sentence, not to the quotation, place it outside the quotation marks.
The minor punctuation marks that often confuse people are the apostrophe, parentheses and brackets, and quotation marks. The apostrophe is used to mark the possessives of nouns and some pronouns. Parentheses can be used to clarify, indicate afterthoughts, and add personal comments. Brackets are used within quoted material. You use quotation marks to enclose a direct quotation.
1368
Business Grammar: Sentence Construction SkillBriefs Sentence Parts, Phrases, and Clauses Explore the various parts of a sentence. The Rules of Subject-Verb Agreement Explore how to ensure the subject agrees with its verb. Rules of Agreement for Pronouns and Antecedents Discover agreement rules for gender, person, and number. Sentence Fragments, Comma Splices, and Modifiers Discover the most commonly made mistakes in sentences.
Sentence Parts, Phrases, and Clauses All too often, badly structured sentences stand in the way of clear communication. Each sentence should have a logical structure with a clearly defined subject, verb, and object. This ensures the reader can easily identify who's responsible for an action you describe, what the action is, and who or what is the recipient of this action. A sentence is made up of two main parts:
a subject - The simple subject of a sentence is typically a noun or pronoun identifying the person or thing responsible for the action described by the verb. The complete subject includes this noun or pronoun, plus all the words that describe or modify it.
a predicate - The simple predicate of a sentence is the verb – the word identifying the action taken by the subject. The complete predicate includes the verb and any other words that describe or modify it. The predicate provides information about the subject.
In some cases, a sentence doesn't identify a subject explicitly. It's important to identify the subject and verb in a sentence so you can make sure they agree in number. In most sentences, the subject comes before the verb. However, some sentences have an inverted subject/verb order, in which the verb comes before the subject. Sometimes this can make it tricky to identify the subject and predicate. Inverted subject/verb order may be used in different types of constructions:
it's typically used in questions, and
it may be used with here or there at the start of a sentence
1369
Direct and indirect objects A verb may be followed by an object. More specifically, a transitive verb is followed by an object. This type of verb requires an object to complete its meaning. An object is a noun or pronoun that identifies who or what is affected by the action of the verb. Intransitive verbs, on the other hand, don't take objects. Two types of objects can be used with transitive verbs:
Direct objects identify who or what receives the action of the verb.
Indirect objects identify to or for whom the action of the verb is performed.
A direct object answers the question what or whom about the verb. The answer will indicate what the direct object of the sentence is, if one exists. You can identify an indirect object by asking of the verb to whom? to what? for whom? or for what? Indirect objects are usually placed right before the direct object. They can also be complex – in other words, made up of the simple indirect object and all the words describing it. Sentences using intransitive verbs don't take any object.
Subject and object complements A linking verb connects the subject to an equivalent word in the sentence. The most common linking verbs are forms of the verb to be – is, was, and are. The word or phrase that follows a linking verb is known as a subject complement, because it provides additional information about the subject. An object complement is similar to a subject complement, except that it provides additional information about the direct object in a sentence.
Phrases and clauses Well-crafted phrases and clauses help ideas and thoughts flow naturally from one to another. A phrase is a group of related words that lacks either a subject or a verb, or both. It acts as a single part of speech. There are three types of phrases:
A prepositional phrase begins with a preposition – such as at, over, in, or along. The preposition is followed by its object, usually a noun or pronoun, and its object's modifiers.
An appositive phrase provides additional information about a noun in a sentence. It follows immediately after a noun or noun phrase in order to define or further identify it. Gerund phrases and infinitive phrases can act as appositives.
1370
A verbal phrase includes a verbal, which is a verb form that does not serve as a verb in the sentence, and any objects or modifiers.
There are three types of verbal phrases:
Participial phrases include either a past or a present participle and any objects or modifiers. They always function as adjectives.
A gerund is a verb ending in ing that functions as a noun. So gerund phrases include the gerund and any objects or modifiers. A gerund phrase can act like a participial phrase – the difference is that the gerund phrase functions as a noun and the participial phrase as an adjective.
Placing to in front of a verb creates an infinitive, which can function like a noun, adjective, or adverb in a sentence.
Clauses are different from phrases in that clauses have a subject and a verb, whereas phrases lack either a subject or a verb, or both. Clauses can be either independent or dependent.
An independent clause is also known as a main clause. It can stand alone as a full sentence. And you can join independent clauses using coordinating conjunctions, such as and or but.
A dependent clause is also called a subordinate clause. It doesn't form a complete sentence but depends on a main clause. Subordinating conjunctions, like because, although, and after, or relative pronouns, such as who, which, or that, usually introduce dependent clauses.
Proper sentence construction is an integral part of any communication. Your business documents and communications should contain sentences and text that are presented logically and clearly. To do this, you should be aware of the different parts that make up sentences. Being able to identify and knowing how to correctly use sentence subjects and predicates, direct and indirect objects, phrases and clauses, and subject and object complements can improve the quality of your writing. This in turn will ensure that your messages are conveyed as clearly as possible.
The Rules of Subject-Verb Agreement You probably know that a basic principle for any sentence is that the subject and verb agree in certain areas:
number – In any sentence, the correct form of a verb depends on whether the subject is singular or plural. And nouns that form irregular plurals – such as child/children – require a plural verb.
person – A verb's person indicates whether the action or state is that of the person speaking – in other words, the first person, I or we ; the person spoken to – that is, the second person, you ; or the person or thing spoken of – the third person, he, she, it, or they.
Remember, the verb to be is irregular. The present tense third person singular – he, she, it – takes the verb is and the third person plural takes are. In the past tense, the singular verb is was and the plural is were.
1371
So if a subject noun is plural, it will end in s, but the verb won't. On the other hand, if the subject noun is singular, it will not end in s, but the verb will. The only exceptions are nouns that form irregular plurals, such as woman/women – these still require a plural verb. Mistakes in subject-verb agreement can sometimes occur in longer sentences, when a subject and verb are separated by other words. In these cases, it's important you identify the subject and verb correctly. For example, in the sentence "The requirements stated in the catalog is unclear," the subject is requirements – not the catalog. This is a plural subject, so the plural verb are is required. Determining subject-verb agreement can be tricky when the subjects of sentences fall in any of different categories.
titles of books, names of companies, or other entities – These are plural in form. When the subject is the title of a book or the name of a company or entity, the verb should be singular even if the title or the name is plural.
subjects joined by and – If a compound subject connects two or more people, places, or things using the word and, the verb must be plural. This is true whether one or all subjects are singular. An exception is when the parts of a subject form a single idea or refer to a single person or thing. Then they take a singular verb – as in "Corned beef and cabbage is a favorite dish among Irish Americans." In addition, when a compound subject is preceded by each or every, the verb is usually singular. But a compound subject followed by each takes a plural verb.
parts of a subject linked by oror nor – In instances where parts of a subject are joined by or or nor, the verb in the sentence should agree with the subject closest to it. And when one part of the subject is singular and the other plural, it's best to place the plural part closer to the verb.
collective nouns, some of which end in s – Collective nouns identify groups of people, animals, or things. Usually they are treated as single entities, so they agree with singular verbs. However, if the focus is on members of a group acting separately as individuals, a collective noun can sometimes take a plural verb. And sometimes collective nouns end in s and look like plurals.
measurements or figures ending in s – Although measurements may identify multiple units, they are considered singular and therefore take singular verbs.
indefinite pronouns – An indefinite pronoun is one that doesn't refer to a specific person or thing. When an indefinite pronoun is the subject of a verb, it's usually singular. However, sometimes it can have a plural sense. And there are some indefinite pronouns that can take either a singular or a plural verb – for instance, all, any, most, some, and none – depending on the context. For example, if none is followed by a singular noun, you should treat it as a singular. Then there are some that take only a plural verb, such as both, few, many, and several. Inverted sentences occur when the verb comes before the subject. This is most common in questions and in constructions beginning with there, here, or it and a form of the verb to be. It can also occur with a compound subject. Moreover, in sentences starting with there, you may use is before a compound subject when the first element in the subject is singular.
In any sentence, the subject and verb must agree in both number and person. Specific rules apply when the subject is a book title or company name, a compound subject, or a collective noun. Rules also apply when the subject is linked by "or" or "nor," is a measurement, or is an indefinite pronoun. Ensuring subject-verb agreement can be tricky when sentences are inverted.
1372
Rules of Agreement for Pronouns and Antecedents Pronouns can substitute for expressed nouns or pronouns, especially to avoid needless repetition. A pronoun typically refers to an antecedent, which is an earlier noun, pronoun, phrase, or clause in the same sentence. To ensure clarity in your sentences, you should make pronouns and their antecedents agree in gender, person, and number.
Agreeing in gender Depending on the antecedent, a pronoun can be any of the following:
masculine – When referring to a noun that identifies a male, you use a masculine pronoun, such as he, his, or him.
feminine – When referring to a noun that identifies a female, you use a feminine pronoun, such as she, her, or hers.
gender-neutral – When referring to something that cannot be classed as male or female, you typically use the gender-neutral pronoun it. Using the pronoun it doesn't always mean the noun has no gender – sometimes, the gender is unknown or unimportant. Common-gender is a term sometimes applied to animate beings, the gender of which is indeterminable.
Traditionally, a generic he was used in cases where the gender was indeterminable or where you were using an indefinite pronoun that included both masculine and feminine genders. In almost all instances, the generic he is no longer acceptable. You can avoid using the generic he in one of three ways:
include both masculine and feminine pronouns – It's appropriate to specify both masculine and feminine pronouns when an antecedent can refer to both genders. However, doing this often can make sentences tedious. It's a good idea to limit your use of he or she to once in a sentence.
use a plural antecedent and pronoun – Often you can convert a sentence into the plural form without changing its intended meaning. You can then use a plural pronoun like their or they, which isn't gender-specific.
avoid using a pronoun – You can often rewrite a sentence so no pronouns are necessary. This eliminates the problem of having to choose between gender-specific pronouns.
Agreeing in person Pronouns and antecedents must also agree in person. Remember, the first person refers to the person speaking – I ; the second person to the person being spoken to – you ; and the third person to the person or thing spoken of – he, she, or it. You decide which pronoun to use based on which person the antecedent refers to – and whether it's in plural or singular form.
1373
To make pronouns agree in person, avoid switching from one person to another in the same sentence. You should keep the use of the personal pronouns consistent. For example, you shouldn't switch from the third person to the second person. When multiple antecedents differ in person and are connected by and, or, or nor, the pronoun must take the person of only one of the antecedents. The first person is preferred to the second, and the second person to the third. And if the pronoun refers to just one of the connected nouns or pronouns, it takes the person of that noun.
Agreeing in number Where the antecedent is singular, the pronoun must also be singular. Likewise, if the antecedent is plural, the pronoun must be plural too. It all seems relatively straightforward, but there are some cases where pronoun-antecedent agreement can be less clear – for example, with antecedents that are joined by and, those joined by or or nor, an indefinite pronoun as antecedent, and collective noun antecedents. Where antecedents are joined by and, you usually use a plural pronoun. However, an exception is when the compound antecedent refers to a single entity. Another exception occurs when the compound antecedent follows each or every. In this case, you use a singular pronoun, even if the antecedent refers to a plural entity. When parts of an antecedent are linked by or or nor, you use the pronoun that agrees with the closest antecedent. And when two or more antecedents of different numbers are joined by or or nor, the pronoun's number agrees with that of the closest antecedent. If you can, you should recast the sentence so the plural antecedent comes last. This avoids an awkward construction. Confusion may arise when antecedent nouns are singular, of different genders, or of indeterminable gender. Agreement with the nearest antecedent may be misleading. You should recast the sentence in order to eliminate the need for personal pronouns. For indefinite pronouns as antecedents, you use a singular or plural pronoun – depending on which indefinite pronoun is used:
singular – When each or anyone is the antecedent, the pronoun referring to it should be singular.
plural – When both, few, many, or several are used as antecedents to other pronouns, you always use a plural pronoun.
Some indefinite pronouns – namely, all, any, more, most, and some – may be singular or plural depending on the word they refer to. Collective noun antecedents – like team, crowd, or family – take singular pronouns when they're acting as a unit. However, when the members of the group act separately, the pronoun is plural.
1374
Pronouns can substitute for expressed nouns or pronouns, especially to avoid needless repetition. A pronoun typically refers to an antecedent, which is an earlier noun, pronoun, phrase, or clause in the same sentence. To ensure clarity in your sentences, you should make pronouns and their antecedents agree in gender, person, and number.
Sentence Fragments, Comma Splices, and Modifiers Sentence fragments A sentence fragment is an incomplete sentence that is formatted like a whole sentence with an initial capital letter and end punctuation. You can identify sentence fragments because they're usually incomplete for one of three reasons:
they lack a verb
they lack a subject, or
they contain subordinate clauses not attached to complete sentences
You should generally avoid sentence fragments. However, it's acceptable to use them in some cases:
as exclamations,
in questions and answers
as commands, or
as transitional phrases
When you identify a sentence fragment, you can revise it by turning it into a complete sentence or combining it with the appropriate main clause. You could also revise a fragment by joining it to a previous sentence or by attaching a subordinate clause to the main clause to form a complete sentence.
Comma splices and run-on sentences Comma splices and run-on sentences can be serious mistakes because they usually force the reader to reread to get the correct meaning. A comma splice occurs when two or more independent clauses are joined by a comma. If you can read the text on each side of the comma as a full sentence, a comma splice is present. You can correct a comma splice using one of several methods:
join the independent clauses with a comma followed by a coordinating conjunction
join the independent clauses with a semicolon
make one clause subordinate, especially if one idea is more important than the other, or
1375
split the independent clauses into separate sentences, each ending with a period
Comma splices also occur when main clauses are separated by a comma that's followed by a linking adverb. Examples of linking adverbs are however, consequently, and finally. And comma splices also occur when main clauses are separated by transitional phrases, such as even so and in fact. Transitional phrases, along with linking adverbs, describe how two clauses relate in meaning. Run-on sentences are also called fused sentences. They occur when two or more independent clauses are placed together, without any punctuation or coordinating conjunction to join them. Like comma splices, run-on sentences can also be corrected by revising the punctuation or wording. To correct run-on sentences, you can use one of these approaches:
add a comma and coordinating conjunction
add a semicolon
add a subordinating conjunction, or
make the clauses into separate sentences
Misplaced and dangling modifiers Knowing where to place modifying words, phrases, or clauses is important because readers rely on the arrangement of words to tell them how those words are related. If modifiers are not connected to the words they modify, they can be awkward, confusing, and even sometimes funny. There are two common errors made with modifying words:
a dangling modifier, which is a modifier that doesn't logically describe anything in a sentence, and
a misplaced modifier, which is a word or phrase that's placed too far from the noun or pronoun it's meant to modify – with the result that it modifies a different noun or pronoun instead
It's especially common for writers to misplace limiting modifiers, like just, exactly, only, and simply. To avoid ambiguity, you must always place a limiting modifier immediately before the word or phrase you want it to modify. Several types of phrases and clauses may be used incorrectly in sentences, resulting in dangling modifiers. They can occur at the beginning or end of sentences. These include the following:
infinitive phrases – These phrases should be followed by a noun or pronoun identifying who determines the causes. Remember, dangling modifiers are particularly likely when the verb in the main clause is in the passive voice.
prepositional phrases – These phrases should be followed by a noun or pronoun identifying who studied the report.
1376
elliptical clauses – An example of a sentence in which an elliptical clause is a dangling modifier is "When inspired, our research shows that writers are likely to beat their deadlines." The elliptical clause "when inspired" is meant to refer to writers, but instead it refers to "our research." The revised sentence is "When writers are inspired, our research shows that they are likely to beat their deadlines."
To correct a sentence that contains a dangling modifier, you can change the main clause so it clearly identifies the subject you mean to modify. Alternatively, you can rewrite a dangling modifier as a complete clause with its own subject and verb. You should avoid using sentence fragments, which are incomplete sentences. It's also important to use the correct punctuation or conjunctions to join independent clauses in sentences. Failing to do this results in one of two types of errors – comma splices or run-on sentences. In addition, using modifying phrases or clauses incorrectly can result in either misplaced or dangling modifiers. In either case, it's important to revise sentences to make it clear what the phrases or clauses are meant to modify.
1377
Business Grammar: Common Usage Errors SkillBriefs Recognizing Commonly Confused Word Pairs Explore the difference between commonly confused word pairs. Using Prepositions Idiomatically Understand the idiomatic use of prepositions. Recognizing Commonly Misused Verbs and Other Words Discover the correct use of certain verbs.
Recognizing Commonly Confused Word Pairs English can be a confusing language. When you're not sure of a word's meaning – or the difference between two words – you should look it up in a dictionary. Commonly confused words can be divided into two categories:
words that sound the same or similar – When you hear someone use a word that sounds identical to another word, you know which word the speaker refers to because you contextualize it.
words with similar or related meanings – People often confuse words that sound different yet have similar or related meanings. But in a technical or economic report, for instance, those differences in meaning can have negative implications if you don't use them properly.
Similar sounding words The pronouns you, it, who, and they have forms that can be easily confused:
you – You are is contracted to you're, and the possessive form is your or yours.
it – It is – and sometimes it has – is contracted to it's. The possessive form is its.
who – Who is or who has is contracted to who's and the possessive is whose.
they – They are is contracted to they're. The possessive form is their.
English has many word pairs that often create problems for writers and readers alike. Some examples of words that commonly get mixed up include the following:
accept and except – Accept means to receive something favorably. Except is most commonly used to mean other than or with the exclusion of.
elude and allude – Elude means to escape notice, perception, or often memory. Allude means to hint at or refer to something indirectly.
1378
imminent and eminent – Imminent is an adjective that means about to happen, or expected. It's often used in the sense of something hanging threateningly over one's head. Eminent means well-known and having a reputation as an expert. Eminent applies to a person.
cite and site – Cite is a verb that means to make reference to something, usually to a source of information. Site is a noun meaning place or location.
complement and compliment – A complement is something that completes or makes perfect. It can also be used as a verb, meaning to complete or supplement something. A compliment is an admiring remark or a sign of respect, honor, or praise, often directed at a person.
principal and principle – The adjective principal means most important or influential. As a noun, you use it to refer to the person who has primary responsibility for an institution. But the noun principle is a basic law or doctrine. Principle may refer to a rule or code of conduct, or to someone who is an ardent supporter of a principle.
capitol and capital – Capitol refers to the official place or building where government work is done. Capital means chief in importance or influence and refers to the most important town or city in an area.
stationery and stationary – Stationery refers to office supplies such as pens, pencils, paper, and paperclips. Stationary is an adjective describing an object that isn't moving. A way to remember the difference between the two is to associate the er in stationery with the er in paper.
a while and awhile – The two-word version a while is a noun phrase that follows the preposition for or in. The one-word version awhile functions as an adverb.
Similar meaning pairs Some words are confusing because they have similar or related meanings.
Ambivalent almost always applies to feelings or thoughts. It means having mixed feelings or contradictory ideas about something. If you feel ambivalent, you may be uncertain about which idea or approach to follow.
Ambiguous means having more than one meaning, open to different interpretations, or even doubtful or indistinct.
It can help to remember that moods, characters, relationships, attitudes, and behavior – or anything deemed to contain contradictions – can be described as ambivalent. The word ambivalence is usually used in the context of a person whereas ambiguous applies most often to words and language. Anxious and eager are often confused:
Anxious means worried, tense, or suffering from anxiety.
Eager means marked by enthusiastic or impatient desire or interest.
Continuous and continual are very similar in meaning – both describe duration:
Continuous refers to something uninterrupted or constant.
1379
Continual refers to something intermittent or often repeated.
In other words, continuous indicates duration without interruption. And continual denotes duration that continues over a long period of time, but with intervals of interruption. Comprise and compose is a particularly troublesome word pair:
To comprise means to be made up of or to include
To compose means to make up, to constitute, or to form the substance of something.
The words fewer and less are often confused:
You reserve fewer for countable things.
And you use less for noncount nouns or amounts.
A guideline to help you remember this is to use fewer with plural nouns and less with singular nouns. The difference between disinterested and uninterested can be obscure:
Disinterested means impartial and unbiased
Uninterested means unconcerned or bored.
It's usually appropriate to use myself when you have used I earlier in the same sentence. You are emphasizing your own role in the. A very common error is to use myself in place of the objective pronoun me or the subjective pronoun I, perhaps because it seems more formal. Many words either sound similar or have related meanings. For instance, it's easy to mix up certain contracted pronouns with their possessive forms. Examples of similar sounding words that are sometimes confused are accept and except, elude and allude, imminent and eminent, and cite and site. Words with related meaning can also trip you up. A few examples include ambiguous and ambivalent, anxious and eager, continuous and continual, and comprise and compose.
Using Prepositions Idiomatically When you compare things, do you compare them to each other or with each other? And would you say that something is different than, different from, or different to something else? The word that changes in each of these cases – than, from, and to – is a preposition, which is a word or phrase that links an object – a noun or a noun equivalent – to another word in a sentence to indicate the relationship between them. More than one preposition can be used after a verb. And the choice of one over another is often idiomatic – in other words, it's been established through use rather than because of a rule.
1380
But one general guideline for choosing a preposition is to use with when referring to people and another preposition for situations or things. Remember, though, this applies in some cases but not in all:
you argue with a person, but over or about a situation or thing, and for or against a position
you agree with a person, but agree to or on terms; also, you agree about something, meaning you concur, and
you differ with a person, but differ from is applied to a thing or quality, and you differ about, over, or on an issue
But in the case of the word occupied, the guideline about with doesn't apply. For example, the seat is occupied by a person, but you are occupied with a task or thing. As you can tell from the examples given so far, idiomatic combinations of verbs, nouns, or adjectives with prepositions can be confusing because their meanings can change depending on context and because they have so many idiomatic uses. For example, you can make a comment about another person, but you can also comment to a person and comment on a situation or thing. And you can charge for a purchase and charge with a crime. You use compare to primarily when highlighting similarities between things or when considering how alike they are. But you use compare with when focusing on the differences between things. You also use compare with when you want to discern both the similarities and differences between things. When things are different, are they different from, different than, or different to each other? Generally, different from is the correct expression. Different from means the same as it differs from. In general, different from is preferable to different than. However, sometimes differently than is appropriate. On the other hand, when things are the same, are they identical with or identical to one another? Identical with is preferred by some, but identical to is also acceptable usage. When do you use between and when should you use among? Between indicates one-to-one relationships and is usually used to compare two things. Among denotes undefined or collective relationships and is used where the emphasis is on distribution rather than individual relationships. However, you can use between for more than two objects if multiple one-to-one relationships are understood from the context. It's even appropriate when one thing is mentioned, but repetition is implied. The expression center around is a common one, but you should avoid it, using instead center on or upon. Or you could use the phrase revolve around. And when you approve of something, you show favor toward it. Approve alone indicates official sanction. More than one preposition can be used after a verb. And the choice of one over another is often idiomatic – in other words, it's been established through use rather than because of a rule. For example, when you compare things, you compare similar things to each other, and things that are unlike with each other.
1381
Recognizing Commonly Misused Verbs and Other Words Learning to use words correctly is important for several reasons:
your word usage influences your readers' perceptions of you – and in the business world, good perceptions and reputations are vitally important
careful word usage helps readers pay attention and value your message more, rather than ignore and disregard the message, and
correct word usage makes your writing easy to read and understand
Commonly misused verbs Some verbs tend to be misused more often than others:
affect and effect – The verb affect means to influence or have an effect on. Affect is usually used as a verb. You should note that in psychological terminology, affect is another word for a mental state or feeling. As a verb, effect means to make happen or produce. In business and generally, effect is usually used as a noun, meaning outcome or result.
appraise and apprise – Appraise means to assess or to put a value on something. You can appraise the amount of something. Apprise means to inform or to tell. You apprise someone of something.
lie and lay – As a verb, the main meaning of lie is to rest, recline, or stay in a horizontal position. Lie also means to have direction or extend. You should check your dictionary for the variety of ways that lie can be used. Lay is a transitive verb, which requires a direct object. It usually means to put or set down.
imply and infer – To imply means to suggest something indirectly. Infer is a verb that means to draw a conclusion from facts or reasoning.
deduce and deduct – To deduce means to reason from general principles to specific conclusions. It is similar in meaning to infer, which is listed as a synonym for deduce. The verb deduct means remove, reduce, or subtract. It's usually used in mathematics.
precede and proceed – Precede relates to sequence. It means to come or go before in time. Proceed means continue doing or move along.
When to use can and when to use may also causes confusion.
May suggests permission or possibility.
Can traditionally applies to physical or mental ability and means to be able to. In less formal English, can also expresses a request for permission, but this usage is not recommended in formal writing.
To irritate means to annoy or to bother. Traditionally, aggravate means to worsen or intensify. A customer who complains excessively might aggravate your bad mood or your headache, but he doesn't aggravate
1382
– or intensify – you in the strict sense of the word. The bottom line is that if you mean to bother, use the word annoy or irritate, rather than aggravate.
Other misused terms The old meaning of the word hopefully is in a hopeful manner, but its newer use as I hope and it is hoped seems to have gained some acceptance. Still, many careful writers avoid the new meaning. These two terms are also commonly misused:
Literally means exactly as described. But people often misuse literally to emphasize something. The word shouldn't be used in a figurative sense.
In lieu of means in place of or instead of. It doesn't mean in light of.
Irregardless is a word that is simply incorrect. The correct term to use is regardless, meaning without regard to, without consideration, or without taking into account. The word unique means one of a kind. Something can't be very unique or a little unique – it either is or it isn't. This is an absolute term that is not gradable. Due to and because of are often confused. Due to is interchangeable with caused by or attributable to. When used as an adverb, due to is usually considered inferior to because of or owing to, which mean by reason of or on account of. It may help to remember that nouns are usually due to something, whereas verbs happen because of something. The two-word expression all together does not have the same meaning as its one-word version altogether. Altogether means entirely, in all or in total amount, or considering everything. But if you say "The employees assembled all together in the boardroom," it means that the employees are together in the boardroom. Using words correctly is important in business communication. Doing so helps to improve your readers' perceptions of you, ensures readers will pay attention to your message, and makes your writing easy to read and understand. Commonly confused verb pairs include affect and effect, appraise and apprise, and lay and lie. Other terms that writers often misuse include in lieu of, literally, unique, and all together.
1383
Business Grammar: Parts of Speech SkillBriefs Recognizing the Eight Parts of Speech Learn about the eight parts of speech. Using Verbs Correctly Discover how to use verbs correctly. Using Adverbs and Adjectives Recognize how to use adverbs and adjectives correctly. Using Nouns Correctly Learn how to use the different types of nouns.
Recognizing the Eight Parts of Speech To understand the basics of good grammar, you need to be familiar with the eight parts of speech. The parts of speech tell you how words function in a sentence, rather than what words are or mean. Words can also be altered to function as different parts of speech.
Nouns Nouns are words that name things. They can be categorized into five groups:
Common nouns name a generic type of person, place, or thing. Common nouns can be further divided up into count, abstract, or collective nouns.
Proper nouns name unique people, places, or things, rather than identifying them based on the categories to which they belong. They always start with a capital letter.
Count nouns express enumerable things. They occur in both singular and plural forms.
Collective nouns – or mass nouns – refer to things that are normally countable, either because they are abstract or because they denote an indeterminate number of people or things.
Abstract nouns name things you can't see, hear, smell, taste, or touch. They describe feelings, ideas, or concepts.
Pronouns Pronouns replace nouns. Using them can make sentences less cumbersome. Pronouns have different forms or cases, depending on how they function in a sentence:
1384
Subjective pronouns replace nouns that act as the subjects in sentences. In other words, they replace nouns describing who or what performs the action described by a verb.
Objective pronouns act as the objects in sentences. They replace nouns identifying who or what is the recipient of the action expressed by a verb.
Possessive pronouns indicate ownership, or possession. The possessive pronouns my, our, your, his, her, its, and their can be used as adjectives to qualify nouns – as in "my report." Each possessive pronoun also has a corresponding independent form that can stand alone, without a noun. With the independent form, the thing possessed may be either an antecedent or something understood. The independent form can also be the subject or object of a verb.
Some personal pronouns are compounds that use the suffix self or selves. These pronouns are used for two main purposes – for emphasis, as in "I will do it myself," or to refer to the subject of the verb, as in "They support themselves." When they are used for emphasis, they are called intensive pronouns. When used to refer to a subject, they are called reflexive pronouns. A reflexive pronoun looks the same as an intensive pronoun but has a different function. It reflects the action that the verb describes by renaming the subject, whereas an intensive pronoun adds emphasis and gives force to a sentence. And intensive pronouns take the subjective case, whereas reflexive ones don't.
Verbs Verbs are commonly described as "action" words. That's because verbs typically describe the performance or occurrence of actions, as in runs or writes. But verbs can also indicate a state of being or condition. Helping or auxiliary verbs combine with some verb forms. They may indicate tense or obligation, or provide other additional meaning. These combinations of helping verbs with other verb forms are known as verb phrases. Commonly used helping verbs are versions of the verb to be. These include am and is in the present tense, was and were in the past tense, and will in the future tense.
Adverbs Adverbs describe, qualify, limit, or modify verbs, adjectives, and sometimes other adverbs. You can classify adverbs into three types. Adverbs of time tell you when something occurs. Adverbs of manner describe how something is done. And adverbs of place tell you where something occurs. Adverbs commonly end in the letters ly. Adverbs often modify verbs, but they can also modify adjectives, which are words that describe nouns. Adverbs can also modify other adverbs.
Adjectives Adjectives describe nouns or pronouns. They answer questions such as Which one? What kind? or How much? Conjunctions Conjunctions join words, phrases, or sentences. There are two types of conjunctions:
1385
Coordinating conjunctions join words or groups of words that are of equal importance – that is, independent elements.
Subordinating conjunction introduces a clause that is dependent on the main clause of a sentence.
You may remember being taught at school that you should never start a sentence with a conjunction like And, But, or So. However, it's now generally considered acceptable to do this if a previous sentence makes it clear what the conjunction is referring to. It's also appropriate to start a sentence with a conjunction like Because or Since if the sentence begins with an introductory clause that modifies another clause that follows.
Interjections Interjections are words, phrases, or clauses that denote strong feeling or emotion. They're often followed by exclamation marks. Avoid using interjections in formal business writing unless you're quoting someone directly.
Prepositions A preposition is a word or phrase that links an object to another word in a sentence to show the relationship between them. A preposition's object is usually a noun or pronoun. Different prepositions indicate different types of relationships:
Prepositions such as on, above, and below identify spatial relationships – they specify where something is in relation to something else
prepositions like before, after, at, and until indicate time relationships, and
prepositions such as by, to, and with identify logical relationships
Being able to identify the eight parts of speech and use them correctly will help ensure your business writing is clear, professional, and effective.
Using Verbs Correctly Voice The verb is the most complicated part of speech. A verb changes form to express different information, including voice, mood, and tense. The voice of a verb reveals the relationship between the subject and the action itself in a sentence:
In the active voice, the subject comes before the verb.
In the passive voice, the subject comes after the verb or may even be left out of a sentence.
1386
In business writing, using verbs in the active voice can help you make a stronger impression. In the passive voice, helping verbs like "am" must be added to support a main verb. These can add to the length of sentences, and convey less energy and interest than action verbs.
Mood The mood of a verb indicates the way in which the verb expresses an action or state of being. There are three types of moods:
You use the indicative mood to state something as a fact, describe something give factual details, or to ask questions.
You use the imperative mood to issue commands or make requests. Sentences in the imperative mood usually have an understood "you" as the subject.
You use the subjunctive mood when referring to a possible act or state.
Verb tenses The tense of a verb reveals the time at which an act, state, or condition occurs or occurred. The three main divisions of time are present, past, and future. To form verb tenses correctly, you need to know the principal parts of verbs:
The plain form of a verb is the form you find in the dictionary.
The infinitive is the part of the verb that in its plain form may be preceded by to.
You form the present participle by adding ing to the plain form of the verb. A present participle is used with a to be verb to show that an action is in progress.
The past participle is usually the same as the past tense form – it takes an ed or d after its plain form.
Regular verbs have basic forms that don't change when you form different tenses. Irregular verbs, however, change form in different tenses. There are so many variations of irregular verbs that if you are unsure about how to form a tense, you should check a good dictionary. The verb to be has more irregular forms than any other verb. The three major categories of verb tenses break down further into simple, perfect, and progressive tenses:
The simple present tense indicates an action that is currently taking place, a recurring action, or something that is always true. To form this tense for regular verbs, you use the plain form of a verb – except when the subject is he or she, in which case you add an s.
The past tense describes an act, state, or condition that occurred or existed at some point in the past. Regular verbs form their past tense by adding ed to the verb.
The future tense indicates an expected act, state, or condition. This tense is formed by placing will before the plain form of the verb.
1387
The present perfect tense indicates that an act, state, or condition began in the past and may still be occurring. This tense uses the helping verb have or has along with the past participle of a verb.
The past perfect tense indicates that an act, state, or condition was completed before another specified past time or past action.
The future perfect tense describes an act, state, or condition expected to be completed before some other future act or time. This tense is formed by using will have with a past participle.
The progressive tenses indicate actions that are still in progress. You form all these tenses using a form of the verb to be with the present participle. So the present progressive tense indicates continuing or progressive action. To form this tense, you use the present tense forms of to be – am, is, or are – with the present participle.
The past progressive tense identifies an action that occurred for a certain amount of time in the past. To form this tense, you use was or were with the present participle. Last, the future progressive tense indicates an action that will be in progress at a certain time in the future. To form this tense, you use will be with the present participle.
It can be more difficult to form tenses correctly with irregular verbs. Common usage errors occur when using irregular verbs such as do, hang, and drink :
In perfect tenses, the past participle of do – which is done – must be used.
The verb to hang takes different past tense and past participle forms depending on the intended meaning.
The past tense of drink is drank and the past participle is has drunk.
An auxiliary or modal verb – is a very irregular verb used with other verbs. Using different modal verbs can change the meaning of a sentence. One modal verb that doesn't vary in its form in either the present or past indicative is ought. Moreover, it has no infinitive form or present or past participle. The verb is the most complicated part of speech because it changes form to express information, including voice, mood, and tense. The voice of a sentence is either active or passive. In business writing, active verbs make stronger impressions and are more concise. Statements and questions are in indicative mood, and commands are in imperative mood. The subjunctive mood expresses hypotheses or wishes. Verb tenses reveal whether actions or states happened in the past, present, or future. To form verb tenses, you should know the plain forms of verbs, their infinitives, and their present and past participles. Verb tenses are divided into simple, perfect, and progressive tenses, each of which is formed differently. An auxiliary or modal verb is used with other verbs to indicate time or add other meaning.
Using Adverbs and Adjectives Adverbs and adjectives give life to your writing, helping you to describe things more accurately and draw your readers in. When used correctly, they can make your sentences stronger and clearer. However, using too many adjectives and adverbs can clutter your sentences and make them harder to understand.
1388
It's important to be concise, especially in business writing. So you need to use adjectives and adverbs only when they add real meaning. Like including too many adjectives or adverbs, using them incorrectly can puzzle your readers and undermine your credibility as a writer. So it's important you know how to use them, as well as when to use them, in your writing. A characteristic of adjectives and adverbs is that you can use them in different forms to specify degrees of comparison. The three degrees of comparison are positive, comparative, and superlative:
In the positive degree, an adjective or adverb describes the quality, quantity, or manner of one person or thing. In the sentence "Alice wrote a long letter," the word long is an adjective in the positive degree. In the sentence "Alice arrived early," the word early is an adverb in the positive degree.
In the comparative degree, an adjective or adverb compares the quality, quantity, or manner of two people or things. An adjective in the comparative degree is longer in the sentence, "Alice wrote a longer letter than Betty." An adverb in the comparative degree is earlier in the sentence "Alice arrived earlier than Betty."
In the superlative degree, an adjective or adverb compares three or more people or things. It indicates that what's being described has a quality to a greater extent than anything it is being compared to.
The way you form the comparative and superlative degrees of an adjective or adverb depends on whether you have a one-syllable, two-syllable, or three-or-more-syllable word:
one-syllable word – You usually add er to make the adjective comparative or est to make it superlative. The same applies to most one-syllable adverbs that do not end in the letters ly. Exceptions apply for some irregular one-syllable words, such as good and bad. These become better and worse rather than gooder and badder. You can use a good dictionary to find the correct forms of comparison for irregular adverbs and adjectives.
two-syllable word – Some adjectives and adverbs with two syllables take the er and est suffixes, but most take more or most. And a participle used as an adjective - for example, boring – requires more or most before it. Sometimes, the way a word sounds will help you determine whether to use the suffix or the words more or most. For example, tranquilest does not sound natural, therefore most tranquil is probably the better form in this case. Consult a good dictionary to check if you are uncertain about which form to use. And remember, some adverbs and adjectives are irregular, so no rules guide their forms in the comparative and superlative forms.
three-syllable word – You usually form the comparative with more or less, and the superlative with most or least.
Remember, when using the comparative and superlative forms, you should use either the er / est endings or the words more and most – but not both. And some adverbs and adjectives, by their definitions, are absolute and can't be compared.
1389
Troublesome adjective-adverb pairs Some adjective-adverb pairs can cause confusion. They account for many of the common usage errors with adverbs and adjectives, in writing and speech. The adjective real is often used incorrectly in place of the adverb really – as in "John was real upset." This is incorrect because real in this context is modifying upset, which is an adjective – so the adverb really should be used. A simple way to check if you're using really and real correctly is to replace them with the word very. If the meaning of the sentence stays the same, you should be using the adverb really. But if not, use real. Confusion between the words bad and badly often arises when they are used with a linking verb. Whether these verbs are linking depends on their meaning in sentences. When the word after a verb modifies the subject, the verb is linking and the word should be an adjective, as in "The economy was bad in the first quarter." But when the word modifies the verb, it should be an adverb – as in "The plants grow badly in this rocky soil." If you were to write "The plants grow bad in this rocky soil," it would mean something different – that the plants somehow become bad. Similar confusion can occur between the adjective good and the adverb well.
Good describes nouns or pronouns and means commendable, worthy, virtuous, or valid.
The word well is most commonly used as an adverb, meaning to do something in a satisfactory way, skillfully, or in a kind way – as in "he treated her well."
The way adverbs and adjectives are formed differs depending on the intended degree of comparison. The three degrees of comparison are positive, comparative, and superlative. You usually form the different degrees based on the number of syllables in a word, although some adverbs and adjectives are irregular. It's important to avoid confusing certain adjective-adverb pairs, such as real and really, bad and badly, and good and well. Remembering which part of speech these words function as will help guide you in their correct use.
Using Nouns Correctly Nouns are an essential component of most sentences. Without them, there's little we could communicate. So it's no wonder these are the first group of words young children learn. Being able to identify different types of nouns can help you improve in three areas:
capitalization becomes easier when you know how to spot proper nouns
subject-verb agreement in a sentence depends on whether a noun is countable or noncountable, and
being able to spot abstract nouns and replacing them with concrete nouns can often help you write more clearly and vividly
1390
Whereas a common noun is the generic name of one thing in a class or group, a proper noun is the name of a person or the official name of a place or thing. So office or person is a common noun, but Simon is a proper noun. Proper nouns also include brand names, as in Scotch tape and Kleenex tissues. All proper nouns start with an initial capital letter. A common noun may become a proper noun. Moreover, sometimes a proper noun may be used figuratively and informally. When the correct form of a verb matches with the subject in a sentence, it's called subject-verb agreement. You'll be better able to apply the rules for subject-verb agreement if you can identify these types of nouns:
count nouns, which name things that can be counted – like customers, chairs, or invoices, and
noncount nouns, which name things that can't be or aren't usually counted – like advice, water, furniture, and wealth
Count nouns can be singular or plural, like brick or bricks and photo or photos. They then take the appropriate singular or plural verb forms. Noncount nouns are also called collective or mass nouns. When it is the subject of a sentence, a noncount noun usually takes a singular verb. However, if you express a quantity of units before a noncountable noun, it becomes countable and the verb must agree with the units. So tea on its own is a noncountable noun, but cups of tea are countable and take a verb in the plural form. Moreover, in a collective sense, a noncount noun may take either a singular or a plural verb form. A singular verb emphasizes the group; a plural verb emphasizes the individual members. Some collective never take the plural form. You must always use them with singular verbs. It's important to use definite and indefinite articles correctly with different types of nouns – in particular count and noncount nouns. An article comes before a noun or noun phrase. The article the indicates that the noun identifies something definite, whereas the article a or an indicates that the noun is indefinite. You use the indefinite article a or an before a singular count noun when you mention it for the first time. Plural count nouns are never preceded by a or an. Also, noncount nouns don't take an indefinite article, except when you're referring to different types of something that's not countable. Noncount nouns that represent a collection or a mass may be preceded by a phrase that indicates quantity, such as a lot of, a little, or some. The definite article points to a definite object that is so well understood that it does not need description. A singular or a plural count noun may take the definite article. Noncount nouns may also take the definite article. You use the before a singular count noun in three situations:
you have mentioned it before
you identify it immediately before or after you state it, or
it's unique or the only one in existence
1391
You don't ever use the indefinite articles a or an before a proper noun. In general, you don't use the either, but there are exceptions - for example, with plural proper nouns and with the names of organizations. Business writing should always use words that have clear, concrete, and specific meanings so that the writing is easy to understand. Abstract nouns denote feelings, thoughts, concepts, or ideas. You may find them useful sometimes, mainly in the broad statements that set the course for your writing, but their meanings can be interpreted differently by different people. Concrete nouns name people, places, or things you can experience through at least one of your five senses. They can be clearly visualized and are less likely to cause confusion. Using them, along with more specific adjectives, can help you write more clearly. It's important to use nouns correctly in sentences. Being able to identify the different noun types can help you apply correct grammar and punctuation in your business writing. Proper nouns always start with an initial capital. Specific rules determine whether you must use singular or plural verb forms with count and noncount nouns. Also, particularly in business writing, replacing abstract nouns with more concrete ones can make your writing clearer and more vivid.
1392
Rules for Constructing Prefixes and Suffixes Learn about the construction of prefixes and suffixes. Rules for Forming Plurals Understand how to correctly form plurals. Rules for Forming Possessives Learn the rules for forming possessives. Basic Spelling Rules Discover how to become a better speller.
Rules for Constructing Prefixes and Suffixes Prefixes are a standard set of syllables that are added to the beginning of root words to change their meaning. Suffixes are a standard set of syllables that are added to the ends of words to alter their meaning as well as their function. You can break prefixes down into four categories, depending on their meanings. Prefixes can be used to indicate
quantity
negation
time, or
direction or position
Suffixes can help you recognize which parts of speech certain words are. For instance, the addition of a suffix to a root word could change it from a verb to a noun. Another suffix could change the word to an adjective, whereas another might make it an adverb. The three categories of suffixes are as follows:
noun suffixes are those that change the root word to a noun
adjective suffixes change root words into adjectives, and
verb suffixes are added to root words to change them to verbs
So suffixes can be added to form nouns, adjectives, and verbs. And to form adverbs, you usually add the suffix ly.
General rules Using prefixes and suffixes correctly requires not only that you know what they mean, but also which guidelines to follow when attaching them to root words.
1393
In general, hyphens shouldn't be used when adding a prefix or a suffix to a word. There are some exceptions to the rule. Normally, the prefix mid doesn't require a hyphen, as in midday. However, when it's followed by a number, a hyphen must used. You should also use a hyphen when mid is followed by a proper noun such as mid-January or mid-Atlantic. When adding less or like to the end of a word, a hyphen has to be used if the addition results in three l's occurring in succession. The prefix re, meaning again, doesn't usually need to be followed by a hyphen. However, you should use a hyphen with it to distinguish the meaning of words with the same spelling. For example, you release a statement to the press, but you re-lease an apartment to a tenant. Another rule is to add hyphens to ensure clarity:
compound words – When adding a prefix to a hyphenated or a spaced compound word, it is necessary to use a hyphen.
"self" words – A hyphen is added when self is used as a prefix. However, a hyphen is not required when self is the base word and it's followed by a suffix, as is the case with the word selfish.
common elements – If you're using two or more prefixes with a common element, you use a suspending hyphen after each prefix to show its relationship to the common element. For example, "We completed pre-, mid-, and post -training assessments."
capital letters – When you place a prefix in front of a word that begins with a capital letter, you have to use a hyphen. This would include words like mid-June and trans-American.
You should also add a hyphen when a prefix ends in a or i and the root word begins with the same letter. But typically, when the prefix ends with e or o and the root word begins with the same letter, you don't use a hyphen. There are some exceptions, however, including co-owner, co-opt, and de-emphasize. When in doubt, consult your dictionary. The trend in spelling has been away from the use of hyphens. Although it's a trend – not a rule – it may sometimes help, when deciding whether to use a hyphen, to remember that the trend exists. And if ambiguity or confusion results from not including a hyphen, then you should add it. When adding a prefix to a word, the spelling of the root word is not altered in any way. However, when adding suffixes to words, the spelling of the root word may change. Because of this, there are certain rules for adding suffixes to root words. One of these rules relates to the silent e that appears in such words as become, like, and give. This e has to be dropped from the root word when the suffix being added begins with a vowel. Exceptions to this rule are the words changeable and noticeable. In these instances, the silent e is maintained because it follows a soft g or c. In some cases, you'll keep the silent e when adding a suffix. The silent e is kept if the suffix begins with a consonant. An exception to this rule is the word argument, which is formed when the silent e is dropped from the verb argue before the suffix is added.
1394
Another rule for adding suffixes is that you change the y in a root word to i if the letter before the y is a consonant. You keep the y in the root word if the suffix begins with an i, as is the case when you add the suffix ing to the word cry to form crying. You also retain the y in a root word in certain one-syllable words and if the letter before the y is a vowel. Sometimes it's necessary to keep the y when a suffix is added to certain one-syllable words. If you add a suffix to the root word dry, you keep the y to form the word dryness, for example. The y is retained if the letter before the y is a vowel, as is the case with the root word annoy when you add a suffix to form the word annoyance. The only exceptions to the rule about vowels before the y include for example the onesyllable words day and say, in which case the y is changed to an i. The basic component of any word is its root. You can modify the meaning of the word by adding a prefix before the root or a suffix after it. Prefixes can alter the meaning of the root word by indicating quantity, negation, time, and direction or position. Suffixes change the part of speech of the word. They can do this in three ways – by changing the root word to a noun, to an adjective, or to a verb. There are several general rules you need to follow when adding prefixes and suffixes to root words.
Rules for Forming Plurals Forming plurals can be tricky. But luckily, you can use several rules to guide you:
the basic rule – The basic rule when it comes to forming plurals is to add the letter s to the singular form of the noun. This is the simplest and most straightforward rule. For example, the singular committee becomes the plural committees, league becomes leagues, menu becomes menus, and quota becomes quotas.
rules relating to nouns ending in s, x, ch, sh, and z – When singular nouns end in s, x, ch, sh, or z, you add es to form plurals. Examples include the words businesses, faxes, sketches, and wishes. The only exception to this rule is the noun quiz. To make this plural, zes is added, forming the plural quizzes.
rules relating to nouns ending in y – When a noun ends in a y that's preceded by a consonant, you form the plural by changing the y to an i and adding es. For example, liability becomes liabilities, copy becomes copies, and policy becomes policies. However, when a noun ending in a y is preceded by a vowel, the letter s is added to form the plural, as in the words attorneys, boys, and delays.
rules relating to nouns ending in f, fe, and ff – You form the plurals of nouns that end in f, fe, or ff by adding s, as in tariffs, beliefs, and safes. The exceptions related to this rule refer to words such as leaves, halves, selves, and wives. These plurals are formed by changing the f or fe to ve and then adding s.
rules relating to singular nouns ending in o – You create the plural forms of singular nouns that end in o in two ways. First, if the o is preceded by a vowel, you add an s to form words such as stereos and ratios. But if the o is preceded by a consonant, you usually add es. For instance, hero and tomato become heroes and tomatoes.
Some special rules apply to three categories of nouns:
1395
proper nouns, which name individual people or things and should begin with a capital letter – The main rule for forming plurals of proper nouns is that the original spelling must not be altered. All that's added to the singular noun is an s. For example, "Mr. and Mrs. McCarthy " become the McCarthys, not the McCarthies.
foreign nouns, which have been adopted from other languages, such as Greek and Latin, into the English language – Foreign nouns use different rules to form plurals. Words ending in o in the singular sometimes change to i in the plural. For instance, concerto becomes concerti. And singular foreign nouns that end in on or um receive an a to form the plural. So, criterion becomes criteria.
irregular nouns, which include nouns surviving from Old English – Some nouns, especially those derived from Old English, are irregular because their plurals are formed by changing letters within the word or adding letters other than the usual s or e s. You're likely to be familiar with most of these words, but in cases where you are uncertain, you should refer to your dictionary.
Another area to consider is the plurals of hyphenated and open compound nouns. For hyphenated forms, you usually add an s to the element that is being pluralized – for example, fathers-in-law. In open compounds, the same applies – for example, accounts payable, rules of thumb, and notaries public. So, as a general rule, you attach the plural form of a compound word to the base element – the one that changes in number or the principal noun – regardless where the element falls in the term. If there is no clear principal noun, then the plural applies to the entire compound as in hand-me-downs or author critics. The only nouns that don't form plurals are noncount nouns. You don't add s to these types of nouns. Examples include bread, equipment, respect, and information. A common error in writing is to form plurals by adding an apostrophe s to the singular form of a noun. Remember that you use apostrophe s for possessive nouns, such as John's portfolio. It's not meant for creating plural nouns. However, you may find that certain handbooks teach the use of an apostrophe in the plural forms of numbers and letters. So, for example, in the sentence "She scored 10's in all quizzes," the score 10's contains an apostrophe, but it doesn't have to. This method of forming plurals is not formally agreed upon. You can follow several rules for creating plurals from singular nouns. The basic rule is to add s to the singular form of the noun. When singular nouns end in s, x, ch, sh, or z, you add e s to form plurals. Nouns ending in a y that are preceded by a consonant are formed by changing the y to an i and adding es. The plurals of nouns that end in f, fe, or ff are formed by adding s.
Rules for Forming Possessives The possessive case indicates not only simple ownership but also other relations. It can denote source or origin as well as description or classification possessive case also replaces an of phrase – for example, one month's salary is the same as the salary of one month. You use an apostrophe to indicate the possessive case. Two general rules apply for most nouns:
1396
For singular nouns, you add apostrophe s to form the possessive. The same rule applies to irregular plural nouns. You also apply the rule to indefinite pronouns like someone, anyone, no one, and everyone. Finally, you apply this to nouns – usually creative names – that end in punctuation marks. For instance, the possessive form of Yahoo!, the Internet search engine, is Yahoo!'s.
For plural nouns, you can add the apostrophe without the s. For instance, you add only an apostrophe to the plural managers in the sentence "The managers' evaluations have been positive."
The general rules for possessives cover most proper nouns in both singular and plural form, as well as numbers and letters. A rule of thumb for forming possessives is that you don't change the spelling of the noun itself – you always add something to it to form a possessive. Some nouns that end in s can take an extra syllable when they become possessive. So to match the pronunciation, you add apostrophe s instead of just the apostrophe. For example, you'd write "The witness's statement is strong." Here, witness's is pronounced witnesses. You can also leave out the s, as in "The witness' statement is strong," and pronounce the possessive. Consistency is the key, but the s after the apostrophe – as in witness's – is preferred because it represents the more common pronunciation. Personal pronouns are often wrongly given apostrophes when they're made possessive. They don't actually take an apostrophe – their spelling changes completely. It is the most common pronoun to be given the apostrophe incorrectly. The word its is the possessive form of it. The possessive its is often confused with it's, where the apostrophe is used to form the contraction for it is. Mastering the guidelines for using the apostrophe in different possessive structures will improve your business writing in several areas:
With separate ownership – when two or more nouns possess something separately – you use the possessive form with each noun. For example, Sarah's and Etienne's projects refers to Sarah's project and also Etienne's project. With joint ownership, you use the possessive of only the last noun. So if Sarah and Etienne are working on a joint project, you make only the second name possessive, as in Sarah and Etienne's project.
You can also use the possessive form to modify a gerund – a verb ending in ing – that is used as a noun. There are several ways to use this construction, and it often creates confusing or awkward sentences. But if you decide to use it out of personal preference, there's a good rule of thumb to help you avoid errors. The rule-of-thumb is to use this construction only in one particular instance – when the word before the gerund can be replaced with a possessive pronoun. This could be a personal pronoun such as I, you, or they, or any proper noun or name. While this rule has several exceptions, it should help you avoid most errors.
In compound nouns and noun phrases, you make the final word possessive – for example, a team member's reaction. However, when a compound noun is plural, as in the bank accounts' balances, it's often best to use an of phrase instead – so it becomes the balances of the bank
1397
accounts. With more complex compound nouns, it's even more important to use the of phrase. Rather than writing editors-in-chief's responsibilities, you'd write the responsibilities of the editorsin-chief. A fuzzy area in possessives is how to tell a possessive noun from an attributive noun – in other words, when it describes a following noun. For instance, in consumer advocate, consumer is used attributively to modify advocate. But take writers' conference, where writers is used possessively. Here you could leave out the apostrophe and write it attributively, but this isn't ideal. Generally, it's safer to retain the apostrophe. You omit the apostrophe – and use the attributive – only in proper names and where there's clearly no possessive meaning. Using the apostrophe to show possession involves several rules. The first is to add an apostrophe s for singular nouns to form the possessive. Second, you add just an apostrophe for plural nouns and nouns ending in s. Personal pronouns don't take apostrophes in the possessive case. When two or more nouns possess something separately, you use the possessive form with each noun. But when joint ownership exists, you use the possessive with the last noun only. You can use the possessive form to modify a gerund, but only when you can replace the word before the gerund with a possessive pronoun. In compound nouns and noun phrases, you only use the possessive case with the final word.
Basic Spelling Rules Computer spell checkers are good at picking up actual spelling errors. But they're limited; they can't pick up the very common error of confusing words with similar spellings. You might already be familiar with some of the rules for spelling, such as those that apply when you add suffixes to words that end in a silent e and in y, as well as rules for forming plurals. For example, for words that end in y, you change the y to i when you need to add es or ed. So comply becomes complies and complied. You may find spelling difficult because many words contain silent letters, other than e, for example:
silent b, as in debt, subtle, and doubt
silent c, as in obsolescence, acquaintance, and indict
silent g, as in foreign, freight, sign, height, strength, and through
silent k, as in knight, knock, and know
silent i, as in liaison, praise, and achieve
silent n, as in hymn, column, and condemn
silent p, as in psychology and pneumonia
silent t, as in mortgage, listen, and often
Some people find that mnemonics – or memory aids – are useful in remembering how to spell words that contain silent letters. You can also use pronunciation aids to help you remember the spellings of words.
1398
A useful memory aid is the phrase i before e, except after c. When a word has an i and an e together after any letter other than c, you spell the word with ie. Examples of this rule are achieve, yield, and retrieve. If it follows a c, you normally use ei, as in perceive, deceive, and receipt. There are several exceptions to the ie rule. When the word sounds like a as in weigh, the e comes first. Other examples are neighbor, reign, and feint. And exceptions when you have an ie after the c are science, ancient, and financier. A rule that applies when you add a suffix to a word is that you double the final consonant. There are two particular instances when you do this:
single syllable words that end with vowel and consonant – When a one-syllable word ends in one vowel followed by a consonant, and the suffix begins with a vowel, you double the final consonant. So scan plus the suffix ing becomes scanning – you double the n.
multisyllable words with accented final syllable – Whether you double the final consonant sometimes depends on how the word is pronounced. If there's more than one syllable and the last syllable is accented – and the suffix begins with a vowel – you double the final consonant. For instance, occur becomes occurred when you add ed and occurrence when you add ence.
You don't double this final consonant if it's a y, k, or x. So buy becomes buying, and the past tense of fix is fixed. Many other exceptions trip people up when a suffix is added. For instance, the plural of bus is buses.
Becoming a better speller You can become a better speller by following some tips. Remember that you just have to memorize some words. Many words have odd spellings or don't adhere to the rules. Examples include coolly, woolly, embarrass, harass, calendar, and itinerary. Words like yacht, buoy, and quay can be tricky too because their spelling differs from the way they're pronounced. Remembering two basic rules, one for adding prefixes and the other for adding suffixes, will go a long way in helping you to spell better. The rule for prefixes applies in every instance, whereas the rule for suffixes applies to one tricky suffix ending:
When you add a prefix, you don't drop letters from the original word. So equal becomes unequal.
When you add the suffix ful to a word, you always end with only one l. So hope becomes hopeful.
Another useful way to help your spelling is to improve the way you say words. For example, to help you remember that separate has two a's, pronounce it as "sep-a-rate." Other words that you pronounce as they're spelled are asterisk, boundary, and Arctic. You can become a better speller by doing certain things:
keep a list of difficult-to-spell words and review it often
use a dictionary whenever you're not sure
1399
use memory aids – for example, visualize a word that you struggle with
try to learn a new word, even if it's just one a day
play word games and do crossword puzzles
Several basic spelling rules can help you become a better speller. Some apply to words ending in silent e and words ending in y. The rule i before e except after c helps you know whether to use ie or ei in a word. Other rules apply to adding suffixes to words that end in consonants and memorizing exceptions and words that contain other silent letters. You can help yourself learn to spell better by recognizing that some words must be memorized, knowing rules for adding a prefix and suffix, and improving your pronunciation. Knowing your weaknesses, using a dictionary, and reviewing difficult words will also help.
Business Grammar: The Mechanics of Writing SkillBriefs The Correct Use of Abbreviations Explore the rules that govern abbreviations. The Correct Methods of Capitalization Discover the rules that govern capitalization. Writing Numbers Discover the rules that govern how you write numbers.
The Correct Use of Abbreviations Abbreviations are shortened forms of words or phrases. They're sometimes used in business documents to save time and space. But overuse and inconsistent use can make a document hard to follow. Two simple rules govern the use of abbreviations: "If in doubt, write it out" and "Be consistent."
Titles and names When using such social titles, you always use the abbreviation. Professional and academic designations follow an individual's full name and comma. Similarly, you use the full name with name suffixes like Jr. and Sr. A civil or military title is spelled out if used with just a surname. They are abbreviated if used with full names. You spell out the titles Reverend (Rev.) and Honorable (Hon.) if they are preceded by the. But they are abbreviated when the doesn't precede the title. The title is usually omitted when just the surname is used. It's generally accepted that you do not use a title and a designation before and after a name. Names that include the title esquire (Esq.) never take any other title, either before or after the name. Titles such as Rev., Mr., and Dr. should always precede a name. In some cases, designations can be used without a proper name, particularly if they signify or substitute for a person.
1400
It's not general practice to abbreviate given names, unless you are following a personal preference. And when Saint is part of a personal name, the individual's preference should be followed when deciding to use the abbreviation or not. The title Ms. is commonly used in three instances: if a woman prefers it to Miss or Mrs., if a woman's marital status is unknown, or if the marital status is irrelevant. In all but the most formal documents, you should abbreviate the names of well-known businesses and organizations, including labor unions, societies, associations, and government agencies. You may abbreviate parts of a company's name, such as Company, Corporation, and Incorporated.
Location and time The names of countries are always spelled out in running text. The names of U.S. states are always spelled out when standing alone and preferably – with the exception of D.C. – when following the name of a city. Although it's becoming more common to abbreviate the United States to U.S. when used as a noun, it's more acceptable to use the abbreviation only as a modifier. You should avoid abbreviating city names and prefixes of geographic names. Exceptions are sometimes made for names beginning with Saint when it's permissible to abbreviate the location prefix. The location name in an address on an envelope or a list may be abbreviated. However, these abbreviations are confusing when you use them in the main body of a business document and should always be spelled out. You're probably familiar with the abbreviations a.m. – which stands for ante meridiem or before noon – and p.m. – post meridiem or after noon. And it's often appropriate to abbreviate time zones such as Atlantic Standard Time (AST) or Greenwich Mean Time (GMT). You can also abbreviate units of time. The days of the week and names of months can also be shortened. However, you should avoid abbreviating days and months unless you need to save space, in a sales chart for example.
Units of measure Abbreviated measurements typically appear on charts and tables. Abbreviations for units of measure are the same in the singular and the plural. Remember to include a space between the number and the abbreviation. You typically don't use periods in abbreviations of units of measure. The one exception to this rule is the abbreviation for inches, which takes a period. When a measurement is used as a modifier, you include a hyphen between the amount and the abbreviated unit of measurement. If the unit of measure is spelled out, a hyphen shouldn't be used.
1401
When to include periods For abbreviations that consist entirely of capital letters, you don't include periods. Abbreviations that appear in lowercase letters usually include periods. Units of measure are exceptions to this rule. If an abbreviation consists of the first part of a word, then a period is generally included after the abbreviation. If an abbreviation ending in a period falls at the end of a sentence, then it is unnecessary to include a second period after the abbreviation.
When to use capital letters Usage is the determining factor in whether abbreviations – other than those standing for proper names – use capital letters. But some guides point out that noun forms are typically uppercase as in the case of CEO, for example, whereas adverbial forms are lowercase, such as the abbreviation for revolutions per minute.
When to use i.e. or e.g. The abbreviation i.e. stands for the Latin term id est and means that is or in other words. You use it when you want to specify or clarify something. You typically use e.g. – which stands for the Latin term exempli gratia, for example – in expressions similar to including
When to use a or an In general, the indefinite article a typically precedes words beginning with consonants, whereas an precedes vowels. With abbreviations, this varies depending on pronunciation – whether the starting sound of the abbreviation sounds like a consonant or a vowel. Acronyms are read as words and – except when used as adjectives – aren't usually preceded by a, an, or the. Abbreviations are sometimes used in business communications when they represent a shortened form of a word or phrase. In some cases, the letters forming the abbreviation are pronounced as a word. These abbreviations are known as acronyms. Most abbreviations fall into four general categories: titles and names, locations, time, and units of measure. Rules or guidelines can help you use abbreviations correctly. Keep in mind these two general rules: "If in doubt, write it out" and "Be consistent."
The Correct Methods of Capitalization In contemporary usage and business writing, you use uppercase letters mostly to highlight parts of written text and to emphasize important words. The first rule of capitalizing is to always start a sentence with an uppercase letter. This takes precedence over every other capitalization rule. You also capitalize the first word of any expression, including a fragment used as a complete thought.
1402
You should also capitalize a sentence that's used as dialog within another sentence. In addition, you capitalize the first word of a question within a sentence.
Headings, lists, and colons There are two ways of capitalizing headings:
Title case, where you capitalize all or most of the words, is most often used for titles of books, chapters, and documents.
Sentence case, where you apply the standard rules for capitalizing sentences, is often used for headings of sections within documents.
You can choose which case you prefer, as long as you are consistent. When using title case, you always capitalize the first and last word of a title. Another generally accepted rule is to capitalize most other words, including all nouns, pronouns, verbs, adjectives, adverbs, and certain conjunctions. Another rule of title case is that prepositions and the articles a, an, and the are usually lowercase, unless they're the first word of a title. There are two exceptions when you do capitalize prepositions:
when they're stressed, and
when they're used as adverbs or adjectives
You don't capitalize words that are coordinating conjunctions. And you don't capitalize to in infinitive verb forms. For sentence case, you capitalize only the first word in a title, the first word in a subtitle, and any proper name. Several general rules apply for capitalizing the first word in vertical lists, depending on the format:
numbered – Each list item begins with an uppercase letter.
unnumbered – List items begin with a lowercase letter when each item continues or completes a sentence. However, if a full sentence followed by a colon introduces the list and the list items are full sentences, each list item begins with an uppercase letter and ends with the appropriate punctuation.
bulleted – Each list item starts with a lowercase letter. Bullets are visual markers to highlight the start of new items so capitalization here is the same as in unnumbered lists.
You use a colon to introduce an element or a series of elements illustrating or amplifying what has come before the colon. You capitalize the first word after a colon when the colon introduces two or more sentences, or when it introduces a speech within dialog or an extract. But when a colon is used to introduce extra information within the sentence, you don't capitalize the first word after the colon unless it's a proper name.
1403
Names and titles When you capitalize people's names, every part of the name takes a capital letter. You also capitalize all initials or abbreviations of names. And when you use the name of an organization in your business documents, follow the organization's use of capitalization in its name. In general, most titles – whether civil, military, religious, or professional – are capitalized when they come immediately before a personal name. However, titles are usually lowercase when they come after a name or are used in place of a name. In business, senior employees are sometimes given official titles, such as president, director, or chairman. When an official title precedes a name, you capitalize it. If you're using a person's name after the title as an appositive – a word or phrase that renames or identifies the noun – you don't capitalize the title. Likewise, when the title comes after a name or replaces it completely, you don't capitalize it. You never capitalize the article in formal titles. Some companies capitalize official titles when they're used without the person's name in internal documents. In general, they should not be capitalized if they follow or replace a person's name. Official titles can be used with a last name alone. Titles referring to occupations are almost never capitalized. This applies wherever the title is used: before, in place of, or after a name. Occupational titles can't be used with a last name alone. You sometimes capitalize common nouns that substitute for proper nouns. This is usually the case in policy statements and legal contracts when you need to refer to longer proper nouns. Substitute terms should be defined early in the document.
Places, events, and other entities Continents, countries, cities, oceans, and other places that appear on maps are always capitalized. And words derived from place names – proper adjectives – are also capitalized. When referring to U.S. states, you capitalize the word state only when it follows the name of the state. If you use a capitalized geographical term that is made up of more than one word as an adjective, you don't hyphenate it. However, if a proper noun is used as a hyphenated adjective, you capitalize only the adjective derived from the proper noun. Topographical names and sections of a country are also capitalized. You capitalize the names of buildings and monuments. Names for important contemporary and historical events are generally capitalized. You also capitalize some
1404
formal organizations, including companies and groups like non-profit organizations, movements, and athletic groups
internal departments of companies
government entities, and
products, trademarks, brands, and creative names
You always capitalize
days and months
acts, treaties, and official documents, and
the words Internet and Net
You don't capitalize compass points and terms derived from them if they simply indicate direction or location. You also don't capitalize the seasons. You capitalize the start of sentences and dialog and questions within sentences. Various rules apply to capitalizing numbered, unnumbered, or bulleted list items. How you choose to capitalize headings, outlines, and titles depends mostly on the case you're using – either title case or sentence case. All proper nouns are capitalized. Abbreviations of proper nouns are also capitalized, as are names derived from proper nouns.
Writing Numbers Knowing the rules for writing numbers has several advantages:
you'll write documents containing numbers that are easy to read and understand
you'll avoid using misleading or confusing numbers in your documents, and
you'll effectively convey the importance of the numbers
In documents like technical and economic reports, research papers, and performance assessments, the significant numbers must catch the reader's eye. But in nontechnical documents, or high-level reports and correspondence, values can often be expressed in words.
Basic rules A simple rule you can follow when it comes to numbers is to spell out numbers one to ten and use numerals for all others. However, whether you follow this rule or not can depend on a number of factors:
Is the number an approximation or a precise quantity? – You always spell out imprecise or indefinite. But when you're sure of the exact value of a number.
Is the number large or small? – In general, you write long numbers in numerals because, in some cases, they take many words to write out. They're also easier to read as numerals. In addition,
1405
you can use a combination of numerals and words to express very large numbers, especially when they are fractional – for example, 2.4 million. And like any large round number, sums of money are expressed by a mixture of numerals and words.
What context does it appear in? – You almost always use numerals for very important numbers, such as exact amounts of money and scientific values. This helps to avoid errors and makes the numbers stand out on the page.
What if a sentence contains more than one number – one that should be written in numerals and the other in words? – In this case, you use the most convenient form – usually numerals – for both. An exception to all the rules is that you always spell out a number that begins a sentence.
Special rules When it comes to writing out times, you should keep in mind a couple of guidelines.
Use numerals when you want to emphasize exact times.
With the abbreviations a.m. and p.m., you typically use numbers. However, if the time is followed by o'clock, you spell out the time in words.
Numerals should never be used to express noon or midnight.
If you're using the 24-hour clock, don't include periods between the numerals representing hours and minutes. You write "The unit will make camp at 2100 and will be on the move again at 0500."
When you write dates, remember that years are expressed in numerals, except at the start of a sentence.
For specific dates, you use cardinal numbers, even though these may be pronounced as ordinals, as in "The meeting is on December 18."
In the United States, you typically write the date in the sequence "month day, year" with the month in words. The day and year are in numerals, separated by a comma. So you write "We started on June 12, 1996." But when you exclude the day, the month and year go together without a comma, as in "We started in June 1996." You can write time periods, such as decades, in numerals, as in the 1990s. And you can refer to a decade less formally by writing just the decade, preceded by an apostrophe, as in the '80s and '90s. Or you can write out the decade – the nineties. A point to remember is that time periods are plural, so you don't use an apostrophe before the final s. In the case of particular centuries, you can spell them out and use lowercase letters. It's also acceptable to use numerals. When it comes to money, numerals are better because they tend to be clearer and quickly understood. You can use numerals for all amounts of money – small or large. When working with fractions, you spell out simple fractions, use numerals for mixed-number fractions, and use numerals for decimal numbers. So you write out the fraction three-quarters but use numerals to express six and one-half yards – if the fraction doesn't appear at the start of a sentence. And you use numerals for decimal numbers such as 2.3 or 0.75.
1406
When deciding whether or not to use a hyphen in spelled-out fractions, these guidelines may help:
when to use the hyphen – The basic rule is that when you spell out an independent fraction, which is considered a single quantity, you hyphenate it – for example "One-third of the employees attended." You also hyphenate fractions that are extremely small, such as "She won by threehundredths of a second."
when not to use the hyphen – When individual parts of a quantity are in question, you don't use the hyphen. For example, "The chart is divided into four quarters."
While you write out most independent fractions, there is one exception to keep in mind. If the fraction is part of an adjective – it describes a measurement, for example – you express it in numerals to make it easier to understand. Rules also apply when you are using numbers with abbreviations, such as m for meter and km for kilometer, and with symbols like the percent sign and the degree sign. The basic rule is that you always use numerals if the number is followed by a symbol or abbreviation. The advantages of knowing how to write numbers are that the numbers in your documents will be easier to read and understand, will not be misleading or confusing, and will get their meaning across effectively. In technical reports, important numbers are usually written in numerals. In business writing, they're sometimes written in words; it depends on the context, how large the numbers are, and whether they are precise or approximations. One rule you might follow is to write out numbers of ten or less in words, and those above ten in numerals. Guidelines can help you use numbers with dates and times, as fractions and decimals, and with symbols.
1407
Interpersonal Communication: Communicating with Confidence SkillBriefs The Essential Elements of Confident Communication Learn about the benefits of communicating confidently. The Use and Impact of Confident Communication Behaviors Learn about confident communication behaviors. Trust, Credibility, Rapport, and Confidence Discover how to communicate confidently.
The Essential Elements of Confident Communication Benefits of confidence Being confident gives you the ability to speak freely, without fearing what others may think of you. It enables you to be assertive, and it reduces anxiety in others. When you are confident, you listen better, because your perception of what others are saying is not distorted by fears and anxiety. When speakers lack confidence, listening to them can provoke negative feelings and impressions. You may also find that you react to a person who lacks confidence rather than to the message this person is conveying. During interactions with speakers who lack confidence, it's harder to focus on the information being communicated and the interactions themselves are less satisfying. You may be less inclined to give speakers what they want, and they are less likely to help you or your organization to succeed. There are several advantages to communicating confidently:
more focused on what's being communicated – When you are confident, you can focus on the message itself and on understanding its meaning accurately, without distortions caused by insecurities. Your focus on what is communicated is also more likely to be mirrored by your listeners, because they won't be distracted by insecure communication behaviors on your part. If you're not worrying about how you come across, your listeners are less likely to focus on you and will listen to what you have to say.
more satisfying – When you're speaking with confidence, both you and your listeners will be more relaxed and attentive. There is more harmonious communication, building a sense of cooperation toward a shared goal. Ultimately, goodwill is generated, and you and your listeners feel more satisfied.
more likely to get what you want – When you are confident, people are more inclined to respond to you positively. Your confidence enables others to feel comfortable too. This means that they pay attention to what you are saying, so your message is clearer and has more influence over your listeners. This results in more favorable responses to your suggestions.
1408
contributes to the success of your organization – Being confident results in fewer misunderstandings when communicating with colleagues, customers, and other parties. This preempts many problems and can significantly increase the efficiency and effectiveness of your organization. Additionally, being confident can give you more influence over customers or suppliers, who'll sense a cooperative attitude. They are then more likely to want to continue doing business with your organization.
Elements of confident communication There are many situational and personal factors that affect the level of confidence you have when communicating. These vary from situation to situation and person to person. Among the main factors that affect confidence in most communication environments are how listeners feel about the speaker, the communication history of the speaker, and the speaker's behavior during the communication – including how the speaker carries him or herself. Experts in communication have identified the following key elements as enabling confident communication:
trust – This can be defined as the feeling you have that another person has good intentions and shares information openly and honestly. For you to trust another person, he or she has to be open to feedback and be able to admit to shortcomings. If you are open to feedback from others, for example, it enables trust because people feel safer when their views are taken into account. And when you know yourself to be trusted, you feel more confident.
credibility – This can be defined as being convincing or believable to others. Listeners decide whether a speaker is credible based on assessments of the speaker's motives, knowledge, and truthfulness. If you consistently keep your promises and honor your commitments, for instance, others find you credible. They can be sure that you keep your word. When others believe in what you say, you develop more confidence. Additionally, if you are accurate in what you say, this adds to your credibility.
confident behavior – This consists of the actions and mannerisms associated with confident communication. Open and relaxed body language, good posture, appropriate eye contact, and clear speaking are all examples of confident behavior. Others feel more comfortable around you when you behave confidently, and behaving in this way actually fosters a genuine feeling of confidence on your part.
Trust and credibility are closely related concepts, but they are not identical. Trust resides with the recipient, whereas credibility belongs to the speaker – in other words, I trust you because you are credible to me. Credibility is more rational, objective, and fact-based. Trust is more inherent and subjective. For example, you may trust the bookkeeper in your organization for subjective reasons. However, her credibility will be based on her training and work experience, and her history of honest and accurate communication. To create confident communication, you need all three elements in place. If one is missing, your confidence will be eroded and information will not be effectively communicated. If you lack the trust of your listeners or credibility among them, you cannot communicate with them effectively just by behaving –
1409
or trying to behave – confidently. Additionally, it's not possible to achieve credibility in an environment of mistrust, or vice versa. Lack of confidence when communicating is a stressful problem, which can make it difficult for you to interact effectively with others. Although lack of confidence can manifest itself in a variety of ways, it is usually caused by a feeling of fear. Anyone can become confident with practice once they understand how confidence is built. The key to building confidence is to earn the trust of others, establish your credibility, and carry yourself in a confident way. If you achieve these three goals, you can become a confident communicator.
The Use and Impact of Confident Communication Behaviors Preparing for confident communication Speaking with confidence takes preparation and practice. When preparing to communicate, you need to keep a few key points in mind:
develop your personal image – Being comfortable in your clothing and dressing appropriately for the occasion help you to feel more confident.
know what you want to say – This helps you to feel prepared and competent. So you need to prepare your message ahead of time if you think you might have trouble conveying it. Consider where your message may be unclear, because people don't always ask questions. Ensure the message is simple and specific, and includes arguments or examples to support your main points. Knowing what your audience wants and what their interests are can help you to speak to those interests while conveying your message.
address fears and self-talk – You may find that you are worrying when speaking, telling yourself that you will make mistakes or be rejected by your listeners. This type of self-talk erodes your confidence and increases stress. Another useful strategy is to imagine the worst possible outcome, and prepare yourself for it. If you are prepared, you are even more likely to succeed.
Confident vocalization Your voice and how you use it are important aspects of confident interpersonal communication. The critical areas to focus on are as follows:
inflection – Your voice's inflection is how it rises and falls as you speak. Without inflection, you will speak in a monotone, which is boring for listeners to follow. When your inflection or pitch goes down at the end of a sentence, it shows certainty and is authoritative. When your inflection goes up at the end of a sentence, it indicates a question or uncertainty.
volume – A confident voice is audible but not overpowering. If you shout, your audience will back away from your message. If you speak very quietly, people will struggle to hear you and may become frustrated or disinterested. Speaking audibly engenders confidence in the speaker as well as conveying confidence to the listener. People are more likely to overrule what you say if they struggle to hear it, which can create a cycle of weakening confidence. If you know that your voice is too quiet, practice speaking more loudly and opening your mouth to accentuate each word.
1410
tone – When speaking, you need to ensure that your tone matches what you want to say. If people think that you are joking when you are serious, you are not getting your message across. Typically, people find a lower tone more authoritative than a higher-pitched tone.
speed – The speed at which you talk affects your confidence and the confidence your audience has in you. Confident speech is typically fluent and slow enough for people to follow with ease, and free of lengthy pauses. Speaking rapidly often indicates nervousness and makes it difficult for a listener to follow your message. This is especially problematic when speaking in groups, because people in group situations are less likely to ask you to slow down. If you hesitate or pause frequently when you speak, your listeners will sense your uncertainty and may become bored waiting for your message to arrive. If you prepare well, you will hesitate less.
Confident body language How you use your voice can affect your projection of confidence when communicating. So can how you use your body. Confident communication relies on a few key items:
posture – How you carry yourself tells your listeners something about you and about how you feel about your listeners. Standing tall with your hands loosely by your sides shows that you are alert and relaxed. If you are sitting, you should sit upright with your arms by your sides, resting either on the arm rests, the seat, or on your thighs. A posture that is alert and relaxed helps you to become more alert and relaxed, and conveys confidence in yourself and interest in your audience.
eye contact – A steady gaze mixed with brief periods of looking away can be used to convey respect and interest in a person, and will enhance your message.
gestures and facial expressions – These are important ways of conveying information. If they don't match your words, you'll give mixed messages and appear inauthentic or unconvincing. Smiling and using open, relaxed, spontaneous gestures convey a relaxed warmth and build confidence.
If your posture is rigid and tense, you communicate insecurity or anxiety. If you slouch, you convey a lack of interest in your audience. Avoiding eye contact can cause you to miss important responses from your listeners, distances you from them, and conveys a lack of self-confidence. But excessive eye contact is considered rude. Worrying or criticizing yourself reduces your confidence and your ability to communicate. When you notice negative thoughts, replace them with positive and encouraging thoughts. Encouraging thoughts support you in your task and give you the confidence you need to succeed. It's helpful to pay attention to how your body feels. If your heartbeat is high, your stomach is queasy, or you feel tension in your muscles, you are probably feeling anxious. By focusing on your breathing and consciously relaxing your muscles, you can calm yourself. When preparing to communicate, you need to ensure that your appearance projects the image that you want it to. You should be clear about what you want to say, why you want to say it, and who your audience is. You should also prevent negative self-talk and ease your anxiety by ensuring you're prepared for the worst possible outcome, so you know you'll be able to handle this. To use your voice confidently, take note of how you use inflections, tone, volume, and speed. Confident body language includes alert and relaxed posture, and good eye contact. You should use spontaneous and open
1411
gestures to add meaning to your message, and ensure your facial expressions match the content of your message.
Trust, Credibility, Rapport, and Confidence Trust Without trust as a cornerstone, communicating is difficult. With trust, confident communication is much easier. If you can build trust in interpersonal communication, each person is able to express themselves more confidently. All communicating parties must trust one another for interpersonal communication to really work. This means you need to try to trust others to enable them to trust you too. This trust is not instantaneous. It develops step by step, over time. Trust takes work; it needs to be practiced and earned before a low-trust environment can turn into a high-trust environment. People in low-trust environments are suspicious of others' motives. When interpreting why others behave they way they do, people tend to assume the worst. This generally leads to more misunderstandings, low morale, and poor relationships. In higher-trust work environments, people tend to assume that others' motivations are positive. This leads to a greater willingness to try to understand one another, improved morale, and more satisfying relationships. It's clearly more beneficial and more comfortable to live and work in a high-trust environment. So building communication trust is important. To build this trust over time, you need to apply the following behavior:
communicate productively – Communicating productively means communicating with the aim of some positive or constructive outcome. Gossiping about someone's poor performance to a colleague doesn't meet these criteria. However, directly approaching a person and letting him know what he's doing right and how he might improve is productive. By giving constructive feedback or criticism, you help someone improve. When speaking with respect, you demonstrate that you value your relationship with the other party and further develop trust.
freely share information – Freely sharing information means sharing all relevant information with people who need to know it. It's primarily about being forthcoming with information that others need. It doesn't include breaking confidentiality. When you share information, people feel trusted and trustworthy. When you withhold information, people notice. This can result in anxiety, misunderstandings, wild speculation, and a drop in trust and productivity.
be candid and truthful – When you are truthful, you don't exaggerate, omit, or spin the truth. This truthfulness provides the basis for trust. By being candid and truthful, you show your respect for those you are communicating with and demonstrate that you trust them with the information.
accept constructive criticism – Learning from your mistakes is one of the quickest ways to grow and improve. By accepting constructive criticism, you show that you believe the person providing the feedback is interested in your well-being. If people know that you can accept constructive criticism gracefully, they won't be afraid of being truthful with you. Admitting it when you're wrong ensures you don't waste energy on covering up mistakes. Without an environment supportive of learning from mistakes, innovation is lost.
respect other parties' needs and interests – Being a trustworthy communicator involves respecting others, finding ways to speak to the other person's needs and interests, and honoring
1412
confidentiality. Breaches in confidentiality may cost you your job or a relationship. When information is sensitive or confidential, it's helpful to say you aren't able to share all the information. In this way, people feel informed, and that they can trust you with confidential information themselves. Respect for others and yourself fosters trust and also helps you become more confident and less self-critical.
Credibility Communicating in a way that builds trust increases your credibility as a communicator and your rapport with others. Credibility depends to a great extent on trust. And trust is dependent on credibility. If you have credibility, what you say is believable and people trust it. If people don't trust you, they won't believe you and you will lose credibility. Trust-building behaviors create credibility over time, but this credibility is fragile and can be undermined or destroyed by just a few actions or words. First, admitting it when you're wrong enhances your sincerity in others' eyes and so builds your credibility. Not admitting your mistakes undermines both credibility and trust. Second, a reputation for exaggeration undermines people's belief in your honesty and candor. These behaviors can ruin your credibility. In addition to trust, a number of other factors can help to build your credibility:
background – There's a direct connection between credibility and your background, previous positions, successes, or accumulated expertise. Your background shapes people's perceptions of you.
behaviors – Extrinsic behaviors can project competence and increase your credibility. This aspect of building credibility comes from your knowledge of the subject matter, use of confident body language, and the tone of voice that you use to deliver your message.
To build credibility, your behavior should foster trust and project confidence. These factors constantly interact to either increase or decrease your own and your audience's confidence in you. Increasing your credibility increases your confidence when communicating because you know others will have faith in what you are communicating.
Rapport and confidence The more your audience trusts you and believes in your credibility, the more you will feel confident when communicating. Increasing your trust and credibility strengthens your rapport with people. Through strengthening rapport in your relationships, you are better able to communicate confidently and influence others. By building trust, credibility, and rapport, you also help others to communicate confidently with you. So everyone in the relationship benefits. The basic building block for confident communication is trust. You foster trust through specific behaviors such as being candid, admitting your errors, respecting others, and disclosing information freely. These trust-building behaviors contribute to your credibility as a communicator. Other factors that bolster credibility are your background, knowledge, and how you project competence when you communicate. By improving trust and credibility, you generate rapport between yourself and your audience. This process is
1413
ongoing, interdependent, and fragile, so you need to be consistent. As rapport grows, you will gain confidence in yourself. Your audience will also gain confidence in you and will be more confident when talking to you.
1414
Business Writing: How to Write Clearly and Concisely SkillBriefs Techniques for Writing Clearly Explore the techniques you use to write clear sentences. Applying the Techniques of Concise Writing Discover the techniques you use to write concisely. Organizing Content to Increase Understanding Understand the most effective ways to organize content.
Techniques for Writing Clearly Often the importance of writing clearly in business is overlooked. But poor writing can mean you fail to get your message across, waste readers' time as they struggle to interpret what you mean, and make a bad impression overall. Clear writing needs to be read only once to be understood. It uses simple, straightforward words. In addition, it presents relevant examples – those that relate to readers' experiences. Specific guidelines can help you ensure your writing is clear. Using short, familiar words Business writing needs to be direct. So you should use short, familiar words that are easy to understand. Whenever there's a choice, use words with fewer syllables. As well as being easier to read, these make more of an impact. As well as using shorter words, you should choose familiar words – those that most readers are likely to know. Using too many uncommon words can make your writing harder to follow. It can also come across as stuffy, pretentious, or even silly. So as you write, it's a good idea to replace long words with shorter, simpler equivalents. Remember that using a formal or respectful tone doesn't have to involve being wordy. Similarly, you should replace uncommon words with more familiar equivalents. Another aspect of keeping your words short and familiar is avoiding industry-specific jargon, or "corporatese." Within organizations, it can be common for employees to develop acronyms and words that are specific to their work environments. It's best to avoid these in your writing because they might not be understood by people outside your organization, or by new staff. There are times when you need to use technical terms or jargon. In these instances, ensure that you initially define the terms or provide equivalents.
1415
You should also limit the use of cliches in your writing. These are stock phrases that have little impact because they're overused. In modern business writing, they often add to the length but not the meaning of a message. As well as avoiding cliches, you should avoid euphemisms. These are indirect terms that disguise or "soften" your intended meaning. In some cases, a euphemism is appropriate because it shows sensitivity to the reader's feelings. Being concrete and specific Concrete nouns refer to or name particular things, ideas, or actions. They vary in how specific they are. For example, you can move from identifying a broad category of entities to being highly specific. Typically, concrete words answer questions like who, what, where, when, why, or how. In other words, they provide concrete information. More abstract nouns name entities that aren't easy to visualize or sense. They often refer to qualities and ideas – for example, management, culture, or freedom. Although you may sometimes use them, they can be vague and have less impact. Often replacing more abstract words with concrete ones can make your writing clearer and easier to follow. Using appropriate connotations In addition to their literal meanings, words can have connotations – or implied meanings. These often have emotional associations. Words with similar meanings – like "aggressive" and "assertive" – can have different connotations. It's important to choose your words carefully based on what you want to convey. If you're not sure whether a word has a particular connotation, you can refer to an unabridged dictionary or word usage guide. Revising noun clusters Noun clusters are groups of nouns that aren't separated by functional words, such as articles and prepositions. The aim of clear writing is not simply to convey your message in as few words as possible. Sentences also become clearer when you add functional words. Using adjectives and adverbs sparingly Strong nouns and verbs are the framework of well-written sentences. And although modifiers like adverbs and adjectives can help create more accurate and complete images in the mind of your readers, you should use them sparingly.
1416
This is because using too many modifiers can detract from the importance of a message and make it harder to follow. When you take out the unnecessary modifiers in the sample text, its meaning becomes clearer. Generally, you should use adjectives and adverbs only when they're really necessary to clarify the meaning of your text. Using transitional words and phrases Another way to make your writing clear is to include appropriate transitional words or phrases. These make it clear how the ideas in your writing are linked. For example, words like "but" and "however" tell your reader that you're moving from one idea to a contrasting one. Words like "therefore" indicate you're moving from an explanation into a conclusion. Transitional words can come at the beginning, middle, or end of a sentence. And transitional words can be used to indicate several types of connections:
the addition of one idea to another, showing the reader that you are adding more information to what you have already stated
a concession about an initial idea, or showing compromise or allowance within text
a logical relationship, in which one idea leads to another or relates logically to another
place or direction
any similarity or difference between elements within text
time or sequence, connecting ideas and text by means of succession, progression, or time
Sometimes sentences don't make sense or are unclear because they need a transitional word or phrase. Using transitions effectively can help make your writing more clear. In a business context, it's especially important to write clearly. Techniques to help you do this include using simple, familiar words, being concrete and specific, and choosing words with appropriate connotations. In addition, you should avoid long noun clusters, use adverbs and adjectives sparingly, and include appropriate transitional words and phrases.
Applying the Techniques of Concise Writing A common complaint from business people about the text they have to read at work is that it's too wordy. Using more words than you have to can bury the core purpose of a message. And it forces readers to work harder to identify what you mean, which wastes time. In all business writing, it's vital to be concise. Concise writing is clear, focused, and uncluttered. It conveys ideas in as few words as possible, without watering them down. You can use four simple techniques for writing more concisely.
1417
Write short sentences Readers lose attention when text contains long sentences. This makes it more likely they'll miss vital information or have to read the same text more than once. So, ideally, you should aim to include a maximum of 15 to 17 words per sentence. Where possible, write some longer sentences as well as short ones to add more variety and rhythm to your writing. Remember, text can become rigid and boring if all sentences are the same length. The easiest way to keep sentences short and to the point is to ensure you include only one idea in each sentence. Avoid unnecessary words Avoiding unnecessary words can help you write concisely. Some words can pad or clutter sentences without adding to their meaning. Removing them makes messages clearer and more direct. So how do you identify which words can be cut out of the sentences you write? You can delete these types of words because they don't add any meaning:
long prepositional phrases
unnecessary repetition, where more than one word or phrase means the same thing
unnecessary sentence starters, which lead into the message
unnecessary phrases that can be replaced by single words
long-winded conjunctions
unnecessary modifiers, such as adjectives and adverbs that don't add meaning
The trick to avoiding unnecessary words is to identify what it is you wish to communicate to your readers. This will enable you to cut out any words that don't assist in conveying your message. Once the unnecessary words are identified and removed, the message becomes more direct and concise. It's also important to eliminate any unnecessary repetition in your text. Including more than one word or phrase that means the same thing just leads to cluttered writing. Use precise verbs Choosing precise verbs is another way to make your writing more concise. A verb is a word or group of words indicating the action or state of being of the subject in a sentence. Verbs tell the reader that something exists, acts in a certain way, or has certain features.
1418
As a writer, you can use fewer words to greater effect when you replace long strings of words containing vague verbs with more precise verbs. This adds force and impact to your writing. Forms of the verb "to be" – such as am, are, is, was, were, being, and been – are the most commonly used vague verbs. Often you can replace them with more precise action verbs to create more concise sentences. Other verbs, especially those that don't indicate action – such as "do," "exist," and "perform" – are often used vaguely. If you add more words to clarify the meaning of these vague verbs, the combination may make your document long and lifeless. Again, it's better to substitute precise verbs for vague ones and their additional terms. In this way, you can be more concise without having to sacrifice the clarity of your message. It's also possible for verbs that signify an action to be far from precise. For instance, the verb "look" is an action verb, but it's still vague. You may need to add other words to clarify the particular meaning of "look" when used in a sentence. Alternatively, to be more concise, you can replace "look" with a more precise verb, such as "glance," "observe," or "peer." Precise verbs should also be used to replace vague verbs linked with nouns. Nouns are words that designate a person, place, thing, state, or quality. In most sentences, you can replace verb-noun combinations with one precise verb without losing any vital information. Use the active voice In the active voice, a basic sentence includes three main parts in a specific order:
first a subject, which identifies who or what performs an action
then a verb that identifies the action
finally an object, which is the entity acted upon
In the passive voice, this order is reversed. In business writing, it's almost always best to use the active voice. This is because readers instinctively expect a subject to come before a verb. Reversing this relationship by using the passive voice can slow down a reader's understanding. Overall, the active voice is more concise, direct, and forceful. Although it's best to write in the active voice, there are times when the passive voice is appropriate. For example, it might be important to be subtle about who was responsible for an action or you may not know it. Sometimes using the odd passive sentence can help vary your writing style – but using this voice shouldn't become the norm. To help identify sentences written in the passive voice, you can ask yourself three questions:
1419
Who or what is the actor? In other words, what is the subject?
What is the action or verb?
What has been acted upon? This is the object of the sentence.
Concise writing is succinct and direct. It includes only the words required to convey a message effectively. Techniques for writing concisely include using short sentences, avoiding unnecessary words, using precise verbs wherever possible, and writing in the active voice rather than in the passive voice.
Organizing Content to Increase Understanding As a business writer, organizing your content is an essential part of the writing process. It involves combining sentences into coherent paragraphs, each of which has a clear purpose. The two key benefits of organizing your content well are as follows:
it's easier to follow – Your sentences may be clear and concise, but if they're not logically connected, or your main point is buried in a third paragraph, they may frustrate and confuse your readers. Organizing content so each element of a document leads clearly and logically into the next helps "lead" the reader through a document.
it's easier to understand – Organizing content well involves arranging it so that your purpose in writing is immediately clear. Further content should then support or expand on the main idea you're presenting. Doing this makes it far more likely readers will understand what you need to communicate. In turn, this makes it more likely they'll respond in the way you hope.
There's no one best way to organize a business document. Ultimately, this will depend on who you're writing for and on what your purpose is.
Methods of organizing content Four techniques can help you organize the content of your writing well. Include an introduction Your introduction should grab your readers' attention. Most readers are busy and need to be persuaded that it's worth their time to read your message. Include a hook that encourages the reader to continue reading – such as a general statement, a question, or an interesting fact. Your introduction should also include a brief statement of your key message and an explanation of the purpose of your document. A poor introduction fails to engage your reader with the rest of your text and does not get the message across to your audience effectively. A weak introduction can even confuse a reader and create some doubt as to what they're reading about.
1420
A good introduction serves to set the context for the reader from the outset so that they're clear about what the text is dealing with. Ensure the body of the document supports the main idea The body of a document is where you present the most information. It's important to remember that all this information should support or expand on the main idea outlined in your introduction. The body may include background details, supporting facts and statistics, anecdotes, or any other information readers need to understand the main idea of the text. The most important information should come first so it gets the reader's attention. If the body of a document must contain anything more than a few sentences, you should divide the text into paragraphs. This will make it easier to read. However, it's common for writers to start new paragraphs as soon as it appears as if there's a big enough chunk of text on the page. This is a mistake. Instead, paragraphs should group ideas logically. Using them should be a conscious part of how you get your message across. A good paragraph starts with a topic sentence. This provides the reader with a core point. Further sentences in the paragraph then expand on this point. As well as grouping sentences into logical paragraphs, you should consider how best to order your paragraphs. These are like the building blocks for a message. It's important they flow in a logical order to build an overall structure that will make sense to readers. These are some of the ways you can choose to organize content in the body of a document:
in chronological order, if you're outlining a sequence of events or steps in a process
divided according to advantages and disadvantages, if you're presenting an argument
according to level of importance – for example if you need to outline recommended actions
in categories, if you need to present, contrast, or compare different information types
Provide a clear conclusion to close the document After the body of a document, it's important to add a clear conclusion. This provides closure. It should also draw the reader back out from details in the body to the core purpose of your message. It may restate the message, discuss its implications, or request action. Use design and layout features to improve clarity Several aspects of a document's layout and design can affect readers' comprehension of text:
1421
white space – White space helps readers "breathe" as they navigate text. It makes text less dense and easier to digest. One good way to include white space is to ensure there's a large enough margin – generally of at least 25 millimeters – between your text and the edges of the page.
graphics – Appropriate graphics add visual interest and convey information, sometimes much more clearly than text alone. However, adding unnecessary graphics can detract from your message.
short lines – Short lines of text that don't all end at the same point are easier to read than long sentences of uniform length.
bullets – Bulleted lists are useful for presenting logically related points clearly and concisely. Use them for when they assist in the logical flow of information.
headings – Headings contribute significantly to the structure of text. They make it clear how text has been grouped and help break it into sections that are easy for a reader to identify. Once you've grouped points logically, you'll be able to identify where headings are required.
Ensuring the content in business documents you write is well organized will make your writing easier to follow and understand. Techniques for doing this include using an introduction to grab the reader's attention and outline your main message, following this with body text that supports the main message, and ending with a suitable conclusion. In addition, you should consider how the layout and design of a document can make it easier for readers to understand.
1422
The Components of the Communication Process
The Flow of Business Communication
How to Prepare for a Communication
How to Properly Send Messages
How to Properly Receive Messages
Five Barriers to Effective Communication
Understanding Verbal and Non-verbal Communication
Using Formal Business Communication
Using Informal Business Communication
The Components of the Communication Process The successful administrative support professional should not only have highly developed organizational skills, but also should possess effective communications skills. Why do you need to be a good communicator to be an effective administrative support professional? Because an administrative support professional assists everyone in the running of an office, and to do this job properly, you must be able to communicate well. In a single day, it would not be extraordinary for an administrative support professional to respond to a business letter, send a company-wide e-mail, greet prospective clients, transcribe an oral memo, or send a voice mail message. Effective communications skills can help you accomplish all these tasks properly and professionally. To send clear messages, and to ensure the messages you send are correctly received, you first have to understand how the communication process works, especially within a business context. The communication process involves a series of actions that bring about a result— and that result is information exchange. This process is composed of five major components: the sender, the receiver, the message, the response, and mental filters. Keep in mind that these five components are active in every communication, but they are not necessarily all active at the same time. The five components of the communication process are described below. 1. The Sender Two components of the communication process are linked—the sender and the receiver. The sender transmits the message to the receiver. If you have a sender and no receiver, or a receiver and no sender, the communication process would be incomplete. Senders are the source of messages, which they send to receivers. They use different media, 1423
such as speaking face-to-face or on the telephone, letters, e-mail, or video to transmit or give information to receivers. 2. The Receiver The receiver gets information—the message—from a source such as letters, literature, photographs, or people. 3. The Message In the communication process, a message includes all the information sent. A message has quantitative elements—the actual words or images used in a message. A message can also include qualitative elements—the information that comes along with the words, which communicates feelings and emotions through techniques such as intonation or body language. 4. The Response The response is a confirmation that the message has been received and can include a desire for clarification or a paraphrase of the message to demonstrate understanding. Depending on the method of communication, the response may be delayed or there may be no response at all. There can be a response only if there is a message, although not every message requires a response. 5. Mental filters Mental filters are created by experiences, upbringing, and culture. Consider how certain scents evoke vivid memories and certain words elicit certain emotions in people. Messages pass through these filters as they are sent and received. These filters affect how we perceive messages and responses. Mental filters encode messages as they are sent and decode messages as they are received. They affect how you transmit messages—word choice, medium, and emotional content—and affect how you understand a message that has been sent to you. Keep this in mind when sending or receiving messages, since you need to account for how each person's mental filters affect the information sent and received. Remember, effective business communication is fundamental to your success as an administrative support professional. By understanding the five components of the communication process, you'll be on your way to communicating more effectively.
The Flow of Business Communication It is important for an administrative support professional to know how communication travels. This flow of business communication is constantly moving, and you need to know where it is going. Why is it important for administrative support professionals to understand the flow of business communication? It is administrative support professionals who often send and receive internal 1424
and external messages, or set up communication exchanges between two different participants. They need to know who to contact in order to perform these duties. Consider how administrative support professionals in the following roles are involved in the flow of business communication.
Information officers. Administrative support professionals often act as an information nexus. They screen communication. Information flows through them; they direct the flow and distribute the information to those who require it. Office managers. Administrative support professionals may perform the duties of an office manager. In many large organizations, they manage an office and are responsible for many of the practical details of disseminating information internally and externally. Administrators. Bosses expect their assistants to look after details—if bosses had to provide detailed instructions for what they wanted done, they would just do it themselves. An administrative support professional needs to be aware of the possible participants in any business interaction.
In one day, you could talk to your boss, a colleague, a supplier, and a client. Talking with these four people can be divided into two broad areas—externally and internally. The flow of business communication externally and internally is examined below. Externally External business communication flows from within an organization to destinations outside of that organization, and from outside to inside an organization. The external flow of business communication travels in various directions outside of the company. Administrative support professionals may have contact with many different external sources. Participants in that communication include clients, suppliers, and partners. These three external communication destinations are all external stakeholders in an organization. Internally Internal business communication flows to and from destinations within an organization. It is important to know these internal destinations to ensure a message is received by the appropriate person. The internal flow can be divided into four directions—downward, upward, lateral, and diagonal.
Downward communication takes place when someone communicates to a person who works in a position below them. Downward communication only travels one way. Upward communication also travels one way. It takes place when someone communicates to a superior within the corporate structure. Lateral communication is the most common. It takes place when one person communicates with another person at the same responsibility level in the company. Lateral communication travels both ways. When someone from one department communicates with someone in a different position in another department, or vice versa, it is called diagonal communication. It
1425
travels both ways. Remember, the flow of business communication is constantly moving. As an administrative support professional, you need to know in which directions business communication travels both inside and outside of your organization, so you can communicate more effectively.
How to Prepare for a Communication Clear communication is important to everyone. As an administrative support professional, you need to be able to clearly and effectively communicate with people on all levels both inside and outside your company. To ensure you communicate clearly, you first need to prepare for communication before you can send and receive messages effectively. Just as you stretch before you exercise, you should prepare before you send a message. Listed below are three steps you can follow to prepare for a communication. 1. Know the purpose for the communication. The first thing you should consider in the process of preparing to communicate is the reason the message will be sent. In other words, you should know the purpose for the communication. To understand the purpose, you should identify the target, or receiver, of the message you will send. Then you can tailor your message to the specific needs and mental filter of your target. 2. Prepare the information. Once you have established the purpose of the communication, your next step is to prepare the information. To prepare the information, you first have to gather it. Compile all the necessary concepts, numbers, and visuals for the message. Then you may have to process the information you have gathered. You may have to give it a sense of order, make it presentable and user-friendly, and turn it into a logically flowing and understandable document. 3. Choose the medium. In the final step of preparing to send a message, you must choose a medium for the message. The word medium is defined as an agency by which information is conveyed or transferred. There are many different media you can use: phone, e-mail, fax, letter, and your own voice. When making decisions on media, consider different aspects of the information you will send, such as style, priority, size, and the receiver. Remember, it's important to prepare for communication in any business. By following the three steps outlined above, you can ensure that you are prepared to communicate, so that your message is clear and effective and achieves the results you seek. 1426
How to Properly Send Messages As an administrative support professional, you probably communicate with others in any number of ways—by telephone, fax, e-mail, or face-to-face. No matter what form of communication you use, your success will depend on your ability to communicate your message clearly with people both inside and outside your organization. To do that, you first have to prepare for communication, and then understand how to send a message properly. To successfully send messages, you have to ensure that they are correctly received and comprehended. For example, a message in a bottle is only successful when it is received and the castaway is rescued. To ensure you send messages properly, you can follow a two-step process, which is discussed below. 1. Transmit the information. The first step in the process of sending messages is to transmit the information. The information is made of all the concepts, ideas, and facts that need to be communicated through the transmission. In order to have a clear message you need to make sure you transmit the correct and complete information. 2. Verify the message is understood. To verify a message, you need to make sure that the information you sent was received and understood. Both sender and receiver are responsible for this action. The sender can request verification, and the receiver should then respond in some way. Verification methods include the following.
Paraphrase. A paraphrase is a restatement of a transmission using different words. A paraphrase shows reception and comprehension of a message. Clarification. Clarification involves asking questions concerning certain details of a transmission while repeating certain parts. It shows that a message is received, but the receiver requires more information in order to fully comprehend the message. Confirmation. Confirmation establishes that a message has reached its destination. It shows reception. Confirmation can be combined with paraphrase or clarification to help show that the message is understood.
Remember, to properly send a message, you first should transmit the information, and then verify that the message is understood. By following these two simple steps, you can communicate more effectively and successfully, which will help make you a better administrative support professional.
1427
How to Properly Receive Messages As an administrative support professional, you can follow several steps to ensure you communicate clearly with others. The first step is to prepare for your communication, and the second step is to send the message. The third element of effective communication—receiving the message—is equally important. You probably receive various office messages throughout your day. It's important to listen to these messages. Successful administrative support professionals use effective listening skills to help them receive messages. In addition, effective listening skills can help prevent communication barriers. Listening is a matter of focusing your attention on receiving a message. To listen to messages effectively, you can follow the four tips listed below. 1. Be prepared. An effective listener is a prepared listener. Prepare to receive a message in any interaction. Preparation helps you focus on receiving a message and avoid distractions. To be properly prepared, you should have a method to record the information, make sure you're in a comfortable position, and ensure you are familiar with the points to be discussed. 2. Listen actively. Effective listeners are active listeners. Successful listening is not passive because the receiver has responsibilities. Administrative support professionals should employ active listening techniques when they receive messages. These techniques help them to take on the role of an alert participant in the communication process. Specifically, an active listener focuses, interacts with the speaker, and takes notes. 3. Avoid anticipating what will be said. An effective listener avoids anticipating what will be said in a communication interaction. Simply listen to a message as it is sent. When you anticipate what a speaker will say, you turn your focus inward. You no longer focus on the message. Resist the urge to try and figure out the end of the message before it arrives. Concentrate on the speaker and what is being said. 4. Debrief the message. Debriefing a message is a great skill for effective listening. A message debrief will ensure that the receiver has the correct information and will act on it, and helps counteract any miscommunication due to individual mental filters. Debriefing may be a form of self-evaluation, it may be a group discussion, or it may involve only the sender and receiver of a message. There are three main steps of debriefing a message.
Recycling involves considering the message sent to you. Turn it over in your head and make sure you understand the content. Then provide the sender with feedback on the content of the message. Clarify the content of the message with the sender, if necessary. Always review your 1428
own thoughts and notes. Make sure you understand your responsibilities concerning messages sent, ensuring all details are correct. Perform any actions required by the content of the communication. Take responsibility and ownership of the message that was sent to you.
As an administrative support professional, you need to be able to successfully receive messages. And to receive messages correctly, you will need to develop good listening skills. Remember, properly receiving messages is an important step in effective communication
Five Barriers to Effective Communication As an administrative support professional, you have to be able to communicate clearly with individuals both inside and outside your organization. Clear communication involves a number of elements. You first have to prepare for communication, and then effectively send your message and receive other messages. In addition, you have to be able to identify and remove barriers to communication. Though there are many possible barriers to effective business communication, five of the most common are discussed below. By working to remove these barriers, you can communicate more clearly and effectively. 1. Different perspectives One barrier to communication is that people view situations differently, and process and communicate information from different perspectives. You may speak the same language, but you see things entirely differently. Perspective is defined as appearance of something relative to a viewer. Having differing perspectives can be a barrier to effective communication between two people, but is more likely to occur when communication is taking place within a group. The larger the number of involved individuals, the more differing perspectives there will be. To overcome this barrier, consider whole situations and encourage the participants to see the benefits of others' points of view. 2. Bias Biases, which can be a barrier to communication in any office, are preconceived judgments or opinions. Bias is not necessarily wrong. Everyone has preferences or "favorites." However, a barrier to communication can arise when people with different biases communicate. Bias is not necessarily about people, but may include certain words, music, pictures, or presentation styles. Some people have stronger or more comparatively marked biases than others. These biases act as barriers in a few ways—for example, one prejudges a situation and is not able to openly communicate. The stronger the bias, the stronger the mental filter, and the more difficult for that person to receive the message. Biases can create situations in which people only see what they wish to see. It is important to recognize when bias is the reason for communication problems. Everyone has biases— 1429
overcoming them is a matter of communicating beyond them. To resolve the problem, those involved need to consider the other person's values. 3. Different organizational structures Generally, organizational structures can be either strict or loose. Strict, or formal, organizational structures are characterized by regulated actions, strict rules, and a strong command structure. In a company with a loose organizational structure, any employee has the freedom to communicate with all management levels, and interactions are less structured. Communication barriers in strict organizations can result from an inability to communicate outside a command chain, and feelings of intimidation. In a loose structure, communication may not arrive at its appropriate destination, or it may be unclear. Communication barriers also can arise when people from conflicting organizational backgrounds interact. To resolve this problem, ensure that all employees understand how to communicate appropriately within the company, and provide training for new employees when necessary. 4. Word choice Word choice can be a barrier to effective communication. This barrier often creates confused or unclear messages. There are two specific types of problems caused by word choices. One involves semantic differences. This is when the words you use may mean one thing to you but something different to others. The other involves business jargon, which is the inside language of an organization. It can include the use of acronyms and codes. You need to ensure that the words you say and the meanings you associate with them are clear to the others involved in your communication interactions. Be sure to choose your words carefully, avoid the use of jargon, and always check for understanding when you communicate a message. 5. Difficulty reading the written word There are many people around the world who have some level of reading difficulty. The difficulty may be the result of dyslexia, illiteracy, or visual impairment. In these cases, the administrative support professional should consider different ways of communicating, make a special effort to communicate clearly, and refrain from making judgments. Remember, as an administrative support professional, you'll encounter various types of barriers as you strive to communicate clearly with others. Be on the lookout for these barriers, and use the strategies described above to overcome them. Only by recognizing and removing these barriers to communication can you ensure that all your messages are clearly received and understood.
Understanding Verbal and Non-verbal Communication 1430
To communicate clearly and effectively with others both inside and outside your organization, you can use several types of business communication. Understanding the different types of communication will help you to fully and successfully communicate your ideas, and maintain an open dialogue with those involved. The first two types of communication you will use frequently during your business day are verbal and non-verbal communication. In a face-to-face interaction, approximately 7 percent of a message's meaning is transmitted verbally, and as much as 93 percent is transmitted non-verbally. However, in situations where the non-verbal element is reduced or completely removed from an interaction, the importance of the verbal element of a message can increase up to 93 percent. Verbal communication consists of two components: written and oral. A written message is just that—anything written. An oral message is anything spoken. Typically, if you work in an office with a lot of human traffic, you would use more oral communication. If you are responsible for document or number processing, you probably would use written communication more often. The major element of a face-to-face communication is the non-verbal element. There are three components of non-verbal communication. 1. Body language. People use body language to communicate all sorts of messages. Body language is comprised of facial expressions, posture, and movement and positioning of body parts. 2. Physical space. Many people communicate emotions and feelings with the amount of physical space they leave as a buffer between themselves and others. 3. Paralanguage. Paralanguage is composed of the sounds people make that communicate emotion and focus level, such as laughter or saying "uh-huh." The important point to remember in communication situations that involve both elements is that your verbal and non-verbal messages should match. If they don't, then receivers may be confused by mixed messages. The verbal and non-verbal messages you send in face-to-face situations need to match. They should also match when you talk on the phone. Think about when you smile on the phone. The person on the other end realizes it. This helps the receiver understand the message you are conveying. The non-verbal element is non-existent in written verbal communication. If you need to communicate non-verbal tone and emotion in a written document, then you should use appropriate and precise wording. Remember, to communicate to your full potential, you must ensure that your verbal and nonverbal elements match. Also, when you send written messages, consider how much the written words must compensate for the lack of non-verbal cues. By being aware of the verbal and non-verbal types of communication you use during the business day, you can more effectively 1431
and successfully deliver all your messages.
Using Formal Business Communication Administrative support professionals may not dress in a formal uniform every day, but it is likely they send and receive formal messages often. Formal communication, which is one of four types of business communication you can use, involves a set of six socially known rules, and is determined by an individual's relative position to another individual hierarchically, relationally, or culturally. Differences in relative position govern your decision to follow the rules of formal communication. Use the formal communication rules when—using yourself as the median— the person with whom you interact has a different position in one, or all, of the following ways.
You may not have the same position hierarchically as the person with whom you are interacting. In other words, you and this person hold different positions of authority and responsibility within your company. Your relative position relationally with someone dictates the type of interaction. To discover this position, ask yourself how close you are to the receiver on a personal level. Your cultural position with an individual often depends on the social situations in which you find yourselves. Your culture also can dictate that you use formal communication with certain people no matter what situation you are in.
Communication interactions are generally formal with the following types of people: office superiors, clients, and people you're meeting for the first time. Sometimes it is difficult to identify formal communication situations within an office setting. The main point to remember is this: If you doubt how comfortable your relationship with someone is, use formal communication. Communicating in formal business interactions is a matter of following certain rules. These rules help guide your actions and manner of communicating. Administrative support professionals should consider these rules and incorporate them into their work habits. The six main rules to follow in formal business communication situations are listed below. 1. Use last names. Using last names maintains a level of formality in any interaction. It also is a way to demonstrate your respect for someone. Include social titles with the last name, such as Mr. or Ms. 2. Refrain from joking and using sarcasm. Some people may not have the same sense of humor as you do. In order not to offend or exclude someone, it is important to 1432
3. 4. 5. 6.
refrain from joking or using sarcasm. Show respect for the person. This is characterized by gracious consideration toward others. You should courteously defer to those you interact with in formal situations. Act your title. This means acting only in your capacity as an administrative support professional. Maintain a professional tone during your conversation. Confine communication to business matters. The parameters of your formal conversations should be within the confines of the business realm. Stay away from personal topics such as religion or politics. Generally, stick to business discussions. Use quiet body language. Close physical space implies a close or intimate relationship. Formality requires that a safe relational distance, and thus a safe physical distance, be maintained. Likewise, use small non-verbal actions. Keep your arms next to your sides and make small gestures with your hands.
Don't let formal situations intimidate you. As an administrative support professional, you will deal with them often. Just remember to use formal communication whenever you're in doubt about your relationship with another person, and keep the six rules for formal interactions in mind, and you'll find that you're much more effective and comfortable when communicating with others.
Using Informal Business Communication Informal business communication is an important type of communication for administrative support professionals, because it promotes openness and friendliness in your office environment. You'll use informal business communication daily in your office in unoffical situations and in situations that are casual, such as relaxed gatherings or conversations with friends. However, identifying informal business communication situations can be difficult sometimes. Identification depends upon the closeness and equality of your relationship with an individual, and the organizational structure within which you work. You can be fairly certain that in the situations below, you can follow the guidelines for informal communication.
Co-workers. When you are equal relationally, hierarchically, and culturally with your co-workers, you can use informal communication. Informal work structures. Internal communications in companies that have informal organizational work structures use the informal business communication guidelines. This covers situations such as receiving instructions from your supervisor or giving instructions to someone hierarchically lower than yourself. Long-time customers. Often, with customers you have known for a long time, you can use informal communication, since your relative position relationally overrides the regular formal situations.
When communicating informally with others, you can follow five main guidelines. Keep in mind that you do not necessarily employ one guideline at a time in informal communication. 1433
They work together, though some will be more useful at different points of an interaction than others. The five main guidelines to follow in informal business communication situations are listed below. 1. Use first names. This demonstrates closeness and friendship, and is a major demonstration of informality. Friends may be slightly offended if continually called by their last names or social titles. 2. Respect the other person. This is characterized by gracious consideration toward others. It's important to always respect and be sensitive to individuals. It is easier to respect someone you know because you are already familiar with any issues of contention and can act accordingly. 3. You can talk about personal things. Your discussion does not necessarily have to be confined to business topics. Knowing someone makes conversation "safer." You can range farther in topic discussion. 4. You can use humor and slang. You know each other, you know your sense of humor, and there is less chance of offending anyone. Once again, knowing someone makes conversation "safer" and more navigable. 5. You can use "loud" or big non-verbal actions. Loud non-verbals denote a high level of comfort, such as when you use your hands and make large gestures, or emphasize a point. This also can include reducing the personal space between you and the person with whom you are interacting. It is less likely that you will intimidate the other person. Remember, informal communication situations involve those individuals with whom you have close relationships culturally, hierarchically, and relationally. You will have these interactions everyday with people you know. Keep in mind that the informal communication guidelines listed above are flexible directions, but you should be familiar with them so you can communicate appropriately and successfully in informal situations
Using Informal Business Communication 1434
Informal business communication is an important type of communication for administrative support professionals, because it promotes openness and friendliness in your office environment. You'll use informal business communication daily in your office in unoffical situations and in situations that are casual, such as relaxed gatherings or conversations with friends. However, identifying informal business communication situations can be difficult sometimes. Identification depends upon the closeness and equality of your relationship with an individual, and the organizational structure within which you work. You can be fairly certain that in the situations below, you can follow the guidelines for informal communication.
Co-workers. When you are equal relationally, hierarchically, and culturally with your co-workers, you can use informal communication. Informal work structures. Internal communications in companies that have informal organizational work structures use the informal business communication guidelines. This covers situations such as receiving instructions from your supervisor or giving instructions to someone hierarchically lower than yourself. Long-time customers. Often, with customers you have known for a long time, you can use informal communication, since your relative position relationally overrides the regular formal situations.
When communicating informally with others, you can follow five main guidelines. Keep in mind that you do not necessarily employ one guideline at a time in informal communication. They work together, though some will be more useful at different points of an interaction than others. The five main guidelines to follow in informal business communication situations are listed below. 1. Use first names. This demonstrates closeness and friendship, and is a major demonstration of informality. Friends may be slightly offended if continually called by their last names or social titles. 2. Respect the other person. This is characterized by gracious consideration toward others. It's important to always respect and be sensitive to individuals. It is easier to respect someone you know because you are already familiar with any issues of contention and can act accordingly. 3. You can talk about personal things. Your discussion does not necessarily have to be confined to business topics. Knowing someone makes conversation "safer." You can range farther in topic discussion. 4. You can use humor and slang. You know each other, you know your sense of humor, and there is less chance of offending anyone. Once again, knowing someone makes conversation "safer" and more navigable. 5. You can use "loud" or big non-verbal actions. Loud non-verbals denote a high level of comfort, such as when you use your hands and make large gestures, or emphasize a point. This also can include reducing the personal space between you and the person with whom you are interacting. It is less likely that you will intimidate the other person.
1435
Remember, informal communication situations involve those individuals with whom you have close relationships culturally, hierarchically, and relationally. You will have these interactions everyday with people you know. Keep in mind that the informal communication guidelines listed above are flexible directions, but you should be familiar with them so you can communicate appropriately and successfully in informal situations
Developing an Effective VOICE Your voice is a vital communication tool. You use your voice constantly to express thoughts, feelings, ideas and hopes, but it is easy to take it for granted. Speech is a complex process. Your lungs, windpipe, voice box, throat, tongue, soft palate, and lips all work together to produce your words. The vibrating column of air coming from your vocal chords is shaped into speech sounds by your lips, tongue, soft palate, throat, jaw, and other facial muscles. These are called your moveable articulators. As a communicator, you must be sensitive to the influence that the quality of your voice will have on the receiver's interpretation of your message. Your objective is to speak with the right VOICE.
V is for volume
O is for output rate
I is for inflection
C is for clarity
E is for emphasis
The strength or loudness of your voice is reliant on the amount of air or breath your lungs produce during the respiration stage. And the rate at which your vocal chords vibrate during the phonation stage controls the pitch of your voice. The output rate or speed of speech is another important aspect of speech. Rapid speech is sometimes associated with knowledge and credibility. However, if you speak too quickly, listeners can't keep up. In contrast, speaking too slowly gives your listeners the impression that you are unsure of your message. They are also more likely to be distracted by other things as their minds have time to wander. Pitch, or the highness or lowness of your voice, is one of the most difficult aspects to control. A highpitched voice may get attention, but it is irritating and difficult to listen to for any length of time. People prefer lower-pitched voices, just as they prefer the tones of a church organ to the shriek of a fire siren. By varying your pitch, you can add inflection to your voice. Inflection gives variety and emphasis to the spoken word.
1436
When you speak in a monotone, without inflection, you do not express the emotion behind your message and are unlikely to engage or maintain the listener's full interest. Inflection also adds meaning. The same words, said with different inflection, can mean very different things. The clarity of your words is determined at the articulation stage by the movement of your articulators. People with poor articulation skills produce sounds, syllables, and words incorrectly. Sometimes this is caused by physical deformities that can be professionally treated, but it is more often the result of incorrect pronunciation or sloppy enunciation. Pronunciation has to do with saying a word the way a dictionary tells you it should be said. Sometimes words are pronounced incorrectly because you aren't familiar with the word, or you may have learned to pronounce it incorrectly. Enunciation has to do with saying all the sounds in a word clearly by moving your tongue and lips fully.
Truncate - One type of enunciation error stems from truncating words or dropping the ends of words, especially "g," "ing," "ed," "d," or "t." For example, "huntin', shootin', 'n fishin'" instead of "hunting, shooting, and fishing."
Replace - Other times, you might replace sharp "t" sounds in the middle of words, with a softer "d" sound because it requires less effort. For example, "better" might become "bedder."
Run together - Another cause of poor enunciation is running words together. "Whadidjagit?" and "Wuzzup?" look strange when written but are common incorrect enunciations of "What did you get?" and "What's up?"
Poor enunciation and incorrect pronunciation can prevent listeners from understanding you. They can also cause listeners to focus on your manner of speaking rather than your words and their meaning. Poor enunciation and incorrect pronunciation can be interpreted as signs of laziness, or even ignorance. Ralph Waldo Emerson said, "A man's style is his mind's voice. Wooden minds, wooden voices." Because your manner of speaking may be undermining your image and your message, you must become aware of your VOICE. By studying your volume, output rate, inflection, clarity, and enunciation, you can begin to develop a better manner of speaking, one more in keeping with the kind of image and message you want to project.
Methods for Improving Your Voice The best communicators know they must use their voices to hold their listeners' interest and add impact to their messages. You may have pearls of wisdom to share, but if no one is listening, they will be wasted. An inability to engage the attention of others for any length of time may not be because of what you are saying, but instead because of how you are saying it.
1437
A good speaking voice is clear, enjoyable, and convincing. Not everyone is born with a voice with these qualities, but they can be developed by focusing on the volume, speed, inflection and clarity of your voice. 1. Volume – Some people talk too softly, others too loudly. The volume of your voice should be dictated by the emotional and physical circumstances in which your conversation takes place. 2. Speed – Some people talk very quickly, others very slowly. Although speaking more quickly is associated with confidence, speaking too quickly can prevent people from understanding what you are saying. 3. Inflection – People who don't use varying pitch to add inflection have monotone voices that are much less expressive and interesting than those who do. Inflection also gives additional meaning to your words. 4. Clarity – Poor articulation, in the form of incorrect pronunciation or sloppy enunciation, may take less effort but can have an adverse effect on your professional image. If you have a poor speaking voice, it can be a big barrier to the success of your interpersonal communication. Fortunately, with the right exercises, voices can be reshaped, toned, and kept in good condition. Appropriate vocal exercises will enable you to improve and maintain correct volume, intonation, pitch, and articulation. The ability to control the pressure and flow of air is a large part of developing an appealing voice. Air is crucial to voice production and volume. It is the flow of air through the vocal tract that generates sound. Therefore, most people see immediate results when they improve their breathing. Using your chest muscles instead of your diaphragm results in shallow breathing and a potentially weak voice. The good news is you don't have to learn how to use your diaphragm because you can already do it! You were born breathing that way, and you breathe that way naturally when you sleep. Diaphragmatic breathing is the best method for producing sufficient expiratory force to speak. It supports your voice with a column of air that extends from your diaphragm to your mouth. As well as generating enough breath to talk at an acceptable volume, your goal is to have sufficient breath to be capable of vocal inflection. A monotone voice is usually due to a lack of awareness of how you sound. You can increase awareness and improve inflection by recording yourself reading aloud from a book, newspaper, or magazine. Play it back and evaluate your performance. Repeat the exercise, making the necessary adjustments. Each time you do this, you should hear marked improvement. People prefer to listen to lower-pitched voices. Opening your mouth wider when you speak will add depth to your voice. Be careful not to push your words out through your teeth like ventriloquists do – that's why their dummies talk in high-pitched voices. Their objective is to prevent their lips from moving. Your objective is to produce a voice that people want to listen to.
1438
Also, avoid eating, chewing, or smoking while you are speaking. These activities make it difficult for you to open your mouth, and this will force the pitch of your voice to go up. These activities also make it hard to keep your lips moving and articulate your words correctly. A failure to articulate or enunciate properly causes your words to be slurred and indistinct. Sloppy enunciation means you don't say all the sounds in a word clearly and often drop the endings and the final consonants. At the same time, don't overdo your articulation. Over-enunciation sounds stilted and false, and makes the speaker appear affected. The important thing is getting your words right, even if you have to speak at a slightly slower rate to do so. To improve your articulation, practice repeating the following sentences or "tongue twisters."
eleven benevolent elephants
girl gargoyle, guy gargoyle
rubber baby buggy bumpers
she stood on the balcony inexplicably mimicking him hiccupping and welcoming him in
One easy yet practical method of improving inflection, vocal range, and articulation is to sing. Depending on your confidence, you might prefer to do this in private, perhaps when you're alone in the shower or in the car. See how well you can carry a tune. Control phrasing and enunciate lyrics while using proper diaphragmatic breathing. Adopting better breathing and enunciation techniques help you to slow down if you talk too quickly. The average rate of speech for English speakers in the United States is about 150 words per minute. When you speak very rapidly, syllables and words run together without the usual pauses, making it difficult or impossible for the listener to understand what is being said. Your voice can be put under strain in the workplace. Some jobs require you to talk most of the day without a break. Other jobs are undertaken in workplaces where the environmental conditions have an adverse effect on the vocal mechanism itself. Your vocal chords need plenty of moisture to work efficiently. It's important to avoid becoming dehydrated by working in very dry environments. If you have to work in this type of situation, be sure to drink plenty of water. Dusty environments often contain allergens that can adversely affect your throat and upper respiratory tract. As you know, a sore throat has an immediate impact on your voice. Cigarette smoke, whether it's your own or secondary, is another drying agent. If you smoke, it would be beneficial to your voice if you quit. If you don't smoke, avoid spending too much time in a smoky atmosphere.
1439
A cold or upper respiratory tract viral infection is a common cause of laryngitis or temporary voice loss. Keep yourself warm and you should be able to avoid becoming hoarse. Many people injure their voices by working them too hard. Don't try to compete against the sounds of loud machinery, loud music, or crowd noise. It is important to be aware of how physical conditions impact your voice and take the necessary steps to avert temporary or even permanent damage. Remember, although your voice can be improved, it cannot be replaced. A healthy voice needs plenty of moisture so avoid agents that dehydrate the body, such as alcohol and caffeine, and drink plenty of water. Stress can affect your voice. When you are feeling tense or nervous, your throat muscles stiffen, raising the pitch of your voice, and making it difficult for you to sound relaxed. Inhale deeply through your nose, and hold your breath for three to five seconds. Now, slowly exhale through the mouth until your lungs have completely emptied. Repeat until the tenseness in your shoulders and neck subsides. Voice development is not restricted to actors, singers, and public speakers. Many people realize that their voices are important to their professional success – and that they don't have to live with the voices they were born with. With the proper practice, everyone is capable of developing a resonant and appealing voice. Once you own these vocal skills, you will command greater respect, and people will want to listen to you.
The Benefits of a Well-placed Pause It is not just what you say and how you say it that has an impact on the success of your interpersonal communication. Sometimes, not saying anything can improve the delivery of your message. Silent pauses are a very versatile and useful communication tool. Pauses can be used deliberately to express feelings such as: anger, confusion, disapproval, or disagreement. A pause can also be used to gain, direct, or maintain the listener's attention. Silent pauses
build suspense
emphasize particular elements of your spoken message
indicate that you are about to change the subject
shape your vocal delivery
Pauses can be used to make your voice sound more attractive and thereby sustain the listeners' attention and interest. Pauses shape the rhythm of your speech and can, when executed well, enhance a speaking voice by adding an almost musical quality to it.
1440
Pausing appropriately as you speak will prevent you from talking too fast. When you talk at an agreeable speed, the reception of your message is improved because your listener has time to take in and decode what you have said. A pause can be used to signal that you are about to change the subject. This prepares listeners for the change so they have a better chance of putting what they are about to hear in the right context. Even when people listen to what you say, they don't take in and remember every word. You can use silence to direct their attention to the more important part of your spoken message and emphasize a particular point. A brief pause before a word, a point, or a phrase acts as a verbal "space" and isolates the item from what has gone before, making it stand out. Pauses also help the listener commit multiple items to memory by preventing the details from running into one convoluted and complex sentence. Pauses should always be used before the point that you want to highlight, and not after. This is because the listener focuses more intently on the first thing that you say after a pause than on anything that has gone before. People speak at a rate of 100 to 175 words per minute, but they listen at a rate of between 600 and 800 words per minute. So it's easy for their minds to wander occasionally. When people aren't completely engaged in the conversation, they hear your voice as a rhythmic background hum. A longer pause that disrupts this rhythm can help you get their attention again. When used this way, silence can be employed to regain attention. There is an old saying that "silence is golden." It certainly can be when it is used effectively to enhance your communication and improve the listener's understanding of your message.
Understanding the Seven Levels of Listening Listening is a vital part of the interpersonal communication process, and it is critical to both personal and business relationships. Most people are born with the ability to hear, but listening is a skill that has to be learned. Hearing is simply the act of perceiving sound by the ear. Listening requires concentration to enable your brain to process the meaning of words and sentences. Listening is a process that involves seven stages: 1. During the first stage, you receive the "raw" sound. This will include all the background sounds around you. 2. During the second stage, your mind selects the auditory stimuli on which you will concentrate and filters out any other sounds.
1441
3. During stage three, you focus your attention on your chosen auditory stimuli. 4. Stage four involves assigning meaning to what you are hearing. 5. Suring the fifth stage, you evaluate what you are hearing, and decide what to do with the information. 6. Stage six involves storing what you are hearing in your memory bank. 7. During stage seven, you actively respond to what you are hearing or have heard. Now you can understand how it is possible to "hear" a conversation, but have no recollection of what was said – no matter how hard you tried. Mentally, you didn't progress past stage one. There are four levels of listening effectiveness: hearing, passive, attentive, and active. The least effective is hearing. The most effective is active. Your listening level is determined by how far along the 7-stage listening process you progress and how mentally engaged you are at the various stages. In terms of communicating, hearing can hardly be considered as listening at all. Although you physically receive the auditory signals, nothing registers in your conscious mind. Listening only truly begins once your mind is engaged in the process. This happens when you make a conscious selection of the auditory stimulus on which you intend to concentrate. At that stage of the process, you move up to the next level of effectiveness – passive listening. When you listen passively, you register the auditory signals, but you are not fully mentally and physically engaged in the conversation. You therefore absorb very little information and use very little energy. Passive listening is really little more than hearing. Although you focus on specific auditory input, your mental involvement ends there. Most of the information you acquire is lost within a couple of hours. In fact, you can lose it within a few seconds, such as when you forget the name of the person to whom you have just been introduced. Attentive listening commences as you move completely into the attending stage and start to listen with the intention of understanding. You do listen and, at a superficial level, understand the words spoken. However, you don't assign real meaning to them. You won't "take in" everything you are told. What you do absorb is put in your short-term memory, and 80 percent of it will be lost within five days. You may be able to repeat most of the words right after you hear them. However, you won't think about what they meant until later, if at all. Active listening is the most effective. When you listen actively, you do so with the objective of understanding the full meaning of the message and responding appropriately. You are totally focused on the speaker and his message. Active listening requires you to
maintain conscious awareness throughout the conversation
evaluate the information received
internalize the parts you regard as important
make an appropriate response
1442
To listen at the most effective level, you have to be motivated and willing to make the effort to overcome the various barriers that prevent you from being totally focused on the speaker and her message. When you are talking to someone, you can often tell from certain physical behaviors at what level he or she is listening. Even when people act as if they are really listening to you, certain telltale signs can give them away. For example, if you speak to someone who is listening at the hearing level, you will likely be ignored. The hearing listener is not connected to you or what you say. When people listen passively, they are not really paying attention. However, they pretend they are by occasionally grunting or making a similar sound to make you think you are being heard. They probably aren't even looking at you, and if they do, it is with a glazed or unfocused expression. If you were to ask them to repeat what you had just said, they would have a very hard time. The passive listener isn't really connected to the conversation at all. People who are listening attentively believe they are listening and will send physical signals of attention. Attentive listeners use supporting body language, such as leaning toward the speaker, nodding, and making eye contact. Despite this apparent attention, they frequently fade in and out of the conversation as they move back to the passive level. Sometimes, they will become focused on a specific point you have made but will then ignore other parts of what is being said. Later, they may be able to repeat what you said, but they have not truly understood what you meant. In some respects, the attentive listener is more connected to the speaker than to the message. Active listeners are easy to spot by the coherent responses they make to what you say. These responses usually convey their intention to understand the full meaning of your message. Active listening may raise the blood pressure and the pulse rate, and may even result in an increase in perspiration. So listeners at the active level may show signs of physical exertion or tiredness while having an extended or detailed discussion. Miscommunication and misunderstanding are more likely to occur when someone listens at the lower levels. To really listen, you need to be motivated to understand what is communicated and be prepared to focus your whole attention on the speaker's verbal and non-verbal messages. By striving to progress through the full listening process, the quality of your interpersonal communication will improve significantly.
The Most Common Obstacles to Listening Listening is more than just keeping quiet while the other person talks. Better listening requires you to make both mental and physical effort. It also requires you to concentrate on the other person rather than on yourself. It is because of these requirements that so few people listen successfully.
1443
True understanding in interpersonal communication can only be achieved by listening at the very highest level. This requires the motivation to be totally focused on the speaker and the message. External conditions, such as a noisy environment, can hinder or prevent you from listening effectively. However, most barriers to good listening are created within the listener. Daydreaming, dress rehearsal, "When is it my turn," information overload, aim to please, and tunnel listening are examples of psychological states which present a barrier to good listening.
Daydreaming – You are not listening because you have other things not related to the current conversation on your mind. Whatever you are concentrating on, it is not this discussion.
Dress rehearsal – You don't listen because you are busy thinking about what you are going to say next. You may even look interested, but you have heard very little, if anything, of what has been said.
"When is it my turn?" – You are not listening because you are just waiting for an opportunity to speak. The only thing you are listening for is a break in the conversation�one that is long enough for you to jump in with your opinion.
Information overload – You are not listening because you decide the information is too difficult to comprehend or too boring. You will switch on again when you are interested in what is being said.
Aim to please – You want to create a favorable impression with the speaker, so you nod and make "agreeing" noises. Your objective is not to listen, but to demonstrate support or agreement.
Tunnel listening – You are listening, but only to what you want to hear. Emotional filters prevent you from hearing what you do not want to hear, so you can focus your attention only on what pleases you.
These psychological barriers influence how much attention you focus on the communication, and they dictate how you respond. To listen well, you must delay thinking your own thoughts until the speaker has finished communicating. You must also strive to understand the speaker's meaning. Unfortunately, most people listen with the intent to respond and not with the objective to understand. A negative prejudgment about the speaker or message affects your answer. You use your response to fulfill your agenda for the exchange. You have no need to listen because you know what you want to happen, regardless of what he says. Your replies indicate your unwillingness to understand the true meaning of the words. When you reply in this way, your focus is on finding things with which to disagree. This communication model resembles that of the courtroom. You take what the other person says and try to disprove it. People can be irritated by your attempts to shift the conversation your way. They may see it as a lack of respect or an indication that you think the subject is unimportant. This kind of reply will frequently cause speakers to become indignant and stick religiously to their point of view, therefore not listening to you at all.
1444
Listening to others can be the most fundamental and powerful communication tool of all. When you commit to stop talking and begin to really listen to other people, your interactions become easier, communication problems are virtually eliminated, and conflict is greatly reduced.
Overcoming Self-made Barriers to Listening Stephen Covey, author of the best seller, "The Seven Habits of Highly Successful People," teaches that you can listen well only when you seek first to understand, then to be understood. Poor listening is commonly caused by not focusing on the speaker and his message and instead, focusing on:
yourself
your emotions and opinions
your own thoughts
your reply
other distractions
If you frequently find yourself concentrating on getting your opportunity to talk, interrupting, or wanting to change the subject, then it is unlikely you are listening attentively to what you are being told. Active listeners speak 30 percent of the time and listen 70 percent of the time. If you interrupt or dominate a conversation, this means that you are not listening effectively. You can overcome this tendency by listening to the whole message without interrupting, even if you don't agree with or approve of it. Wait to express your experience or point of view, and resist the temptation to speak for the sake of saying something. Keep in mind, the only acceptable reason to interject is to clarify or confirm what has been said. If you must talk when speakers are sharing something important, use short responses. Longer responses may cause the speaker to become impatient or divert him from his original train of thought. Sometimes you may not listen because you are busy rehearsing your reply or thinking or day dreaming about an unrelated subject. If this is a common occurrence, then you need to listen with a purpose. Be motivated to listen by setting a goal. It may be to gain information, obtain directions or instructions, solve problems, or understand how another person feels. Improve your ability to focus on what is being said by treating listening as a challenge. Mentally structure and summarize the verbal content of the communicated message by: indexing, sequencing, and comparing.
Indexing – is the process of mentally noting the key points or ideas being discussed, together with their associated and supporting points and items.
Sequencing – is listening for order or priority. Sometimes the order of what you are being told is important or even crucial.
1445
Comparing – is concentrating on the points being made, and discriminating between fact and theory, positive and negative, advantages and disadvantages. Then, you can evaluate the ideas, options, attitudes, facts, feelings, and beliefs.
To listen well, you must overcome any tendency to rehearse your response or allow your attention to drift. Give speakers your undivided attention. Look them in the eye when they are speaking – active listeners maintain eye contact for five seconds or more. Focus on the speaker, and only the speaker. Ignore internal distractions, such as your own thoughts, and external disruptions, such as telephones ringing and people talking. Another barrier to listening is an emotional response. When you react too emotionally, you tend to hear what you want to hear – not what is actually being said. You may focus on one comment out of context. You may only listen to some of what the other person says, filtering out the parts that don't confirm your own views and opinions. Another temptation is to disengage mentally because you judge what the other person is saying or will say is irrelevant, illogical, or inconsistent. You can prevent this from happening by remaining neutral, objective, and open-minded. Stay in tune with your own reactions and watch out for anger, boredom, or disinterest. Be aware of your biases and emotional triggers. For example, such things as a speaker's bad grammar, limited vocabulary, or accent might irritate you. Your awareness helps you control, or preferably eliminate, your emotional reactions, allowing you to concentrate on the speaker's message and not on the delivery. As a good listener, your behavior will demonstrate your intention to understand. Acknowledge speakers both verbally and non-verbally, and encourage them to continue by using your responses and body language to demonstrate your interest and attention. This requires you to
adopt an open, relaxed posture
face the other party, square on
lean slightly towards the other person
ask questions to confirm and clarify what is being said
Learning to overcome the self-made barriers to listening will help you to improve your ability to communicate. Listening more attentively to others will help you come to understand the people around you. Effective listening enables better collaboration and cooperation by helping to eliminate miscommunications and subsequent errors and mistakes. When both parties listen well, they are more likely to work together successfully and make sure that everyone's needs are met.
Recognizing Non-verbal Messages People communicate both verbally and non-verbally. Albert Mehrabian's research into communication determined that a significant amount of meaning is transferred through the non-verbal aspects of communication. To fully understand what people are saying, you must be skilled at decoding both verbal and non-verbal messages. Non-verbal communication is comprised of
1446
paralanguage – the vocal part of speech and its nuances
kinesics – static and dynamic use of the body in communication
proxemics – spatial relationships and perception of space
Unlike verbal communication and paralanguage, most body language is automatic. Even the pupils of your eyes communicate. When you are excited or particularly interested in something, the pupils of your eyes increase in size. That's why people obtain so much of the meaning of communicated messages from body language. Body language is considered a much more reliable indicator of a person's true feelings than the words they use. More than half of the understanding of interpersonal communication is generated by people's body language, so it is useful to know what behaviors you should observe in others and be aware of yourself. Humans are highly territorial as a species, but most humans aren't aware of this until their personal space is invaded. The distance you place between yourself and another person conveys a non-verbal message. How you orient yourself in relation to other people when you interact with them can often indicate your general disposition towards them. You may stand face-to-face, side-by-side, or even back-to-back. Shaking hands, touching, holding, embracing, pushing, or patting on the back, all convey messages. These examples of physical contact reflect the presence – or absence – of elements of intimacy or attraction. A person's posture also communicates feelings. It is not whether someone is sitting, standing, or lying down that tells the story. The message comes from whether they are slouched or standing straight, or have their arms folded, or have their legs crossed. The dynamic features of body language are the ones that people are usually more aware of. As the word suggests, these factors involve movement of a person's: face, eyes, body, hands and arms. Facial expressions openly display the attitude of the communicator. Movement of the mouth, lips, brows, and forehead can all convey information about how a person is feeling. Facial expressions continually change during interaction and are monitored instinctively and constantly by the recipient. The eyes can convey many emotions, so eye contact is a major feature of social communication. Much valuable insight into a person's emotional state can be gained by observing the frequency and the length of eye contact. Loss of eye contact can suggest disinterest or boredom, so it can signal when to continue talking and when to stop. Sustained eye contact can suggest attraction or aversion, so it is a good indicator of a person's reaction. The direction in which people move their body can convey information about how they are feeling. Whether the meaning is positive or negative depends on if the movement is forward or backwards, up and down, or side to side.
1447
Because most people use hand and arm movements or gestures regularly when talking, these are some of the most frequently observed examples of body language. But it is important not to "read" too much into individual gestures. You should interpret these individual gestures in the same way as you deal with words in a sentence – the meaning only becomes clear when you put all of the gestures, or words, together. Increased awareness of your own body language and that of others can make you a more perceptive communicator. This will have a positive influence on your approach to all your relationships, both personal and professional.
Interpreting Four Modes of Non-verbal Expression Body language provides important insights into the meaning behind a person's words. A person's posture and facial expressions tell you how they think and feel. Sometimes you may even detect a discrepancy between these non-verbal queues and what a person is saying. By learning to interpret body language, you can read between the lines to get at the truth or essence of any conversation. Body language is expressed in terms of facial expressions, eye contact, gestures, body orientation, physical contact, proxemis (personal space), and posture. Of these non-verbal queues, posture is one of the most significant. A person's posture may be open or closed, depending on their response to what is being said and who is saying it. People who are open and responsive generally sit with their legs outstretched, uncrossed, or with the knees apart. Their elbows are often away from the body; their hands are open or loosely clasped. They may lean forward toward the speaker as they listen, or display other signs of interest or agreement. People who are closed, defensive, or even combative may sit with their legs crossed at either the knees or the ankles. They fold their hands on their lap or fold their arms across their chest. They may lean back in their chairs or show other signs of escape, retreat or aggression. The open and closed, forward and backward posture groups combine to create four basic emotional modes: reflective, responsive, defensive, and combative. 1. Reflective mode An open and back posture may indicate a reflective state. When you are in reflective mode, you are receptive. You may be listening to the other person, evaluating what she has said. In this "interested" mode, your "static" (stationary) body language remains relatively constant and you will be relatively still. Dynamic (moving) body language will provide an indication of your specific feelings. When a person is responding positively to what you are saying, you may observe: a relaxed brow; an occasional nod of the head; the head tilted toward you; lots of direct eye contact. 2. Responsive mode A forward and open position shows that a person is responsive. In this mode, he may be demonstrating that he is comfortable and relaxed with you. Alternatively, he may have evaluated your message and now be showing his active agreement. Once your ideas are accepted or
1448
understood, heads nod affirmatively and eyes open wider. When people are responsive, they will probably move closer to you. If sitting, they may shift to the edge of their seats to achieve this. When rapport is very strong, they may even begin to mirror your body language. 3. Defensive mode If listeners are leaning back and have closed body positions, it may mean they are in defensive mode. They may be bored, disinterested, or uncertain. They may be anxious, nervous, or stressed. Whichever of these emotions they are experiencing, they want to escape and be somewhere else. These "fugitive" feelings are signaled by hunched shoulders, crossed arms or legs, and the feet may be pointing to the door. They may fidget and demonstrate a perceptible lack of eye contact as they look around or gaze down. People may unconsciously touch their bodies to relieve feelings of stress. Self-touch may indicate nervousness, confusion, or anxiety. It may also indicate deceit. Examples of self-touch include pinching the bridge of the nose clenching the hands massaging the hands, arms, or legs scratching, rubbing, or pinching the skin holding an arm or wrist touching the lips with the fingertips 4. Combative mode A forward and closed position signals the person is in combative mode. In this mode, feelings can range from disagreement to hostile aggression. When a person has an aggressive attitude, they may stand with hands on the hips or elbows out. This is a common method of enlarging the body's size to appear physically more powerful in order to dominate or threaten. It is common for people in combative mode to invade your personal space. They may stand uncomfortably close or they may poke or prod you. They may even push their heads forward until their faces are only inches from yours. The hands can indicate a combative attitude. A combative person tends to clench his fists or make short, sharp, "cutting" motions with his hands. With his palms down, a combative person may slap or beat on a table, desk, or other surface. Facially, you can expect to see someone in combative mode to have their eyebrows lowered into a scowl of anger or displeasure, and their lips compressed or pursed in disagreement. When you attempt to interpret non-verbal queues, it is important not to jump to conclusions based on a single gesture or posture. These elements of body language are like words in a sentence – they must be taken together to extract meaning. You have to "hear" the entire "silent sentence" for it to make sense.
1449
Body language can help you to extract deeper meaning when you speak and when you listen. By watching for non-verbal queues, you can see how your words affect others and gain insight when other people speak. Pay attention to how people are reacting, as well as what they are saying, and your communications skills will improve significantly.
Responding Appropriately to Body Language There are often discrepancies between what people are thinking, as communicated by their words and what they are feeling, as communicated by their body language. These different feelings can be categorized as
defensive – passive and rejecting
combative – active and rejecting
reflective – passive and accepting
responsive – active and accepting
People don't often consciously notice their own body language or that of others. Mostly, it is enacted and interpreted subconsciously. Body language can be very subtle, with each gesture and expression giving only part of the total emotional message. Body language becomes more apparent when it doesn't match the words it accompanies. For example, someone's words may be reflective and receptive, but their body language may be defensive and rejecting. Their words may convey acceptance, but if the body language says otherwise, the discrepancy will be obvious. When you notice that there is incongruence or a mismatch between a person's body language and his verbal message, you should try to address unvoiced resistance and facilitate understanding. "Probing points," such as tension observed in a friend's mouth should prompt the question, "What's wrong?" You will need to further investigate the other person's verbal response to your message by using questions specifically designed to target the unvoiced attitudes or hidden uncertainties indicated by the body language. Co-workers, friends, and family members will appreciate your acknowledgement of their feelings. They will also be encouraged to voice their true opinions, thereby avoiding unsuspected conflict at a later time. In addition to observing discrepancies between verbal and non-verbal queues, it is also important to remember to put any observable behavior in context with what is being said and with other examples of body language that is being displayed at the time. Postures, body movements, and facial expressions do not transmit accurate information when observed out of context. Certain "closed" movements, such as crossing the arms or the legs, may be done simply because the position is comfortable or because the person is trying to keep warm. Other movements, such as lowering the eyebrows can, depending on the degree, indicate either that the person is thinking or that he or she is angry.
1450
It is indeed helpful to have the ability to pick up on people's unspoken uncertainties and concerns, particularly when you need to know if someone's reaction to you or your idea is positive or negative. Once you have that information, you are better positioned to give the most appropriate response and ensure clear and mutually beneficial communication.
Workplace Communication Skills SkillBriefs Three Interpersonal Communication Styles Learn more about three interpersonal communication styles. Four Types of Assertive Responses Explore the four types of assertive responses.
1451
Assertive Interpersonal Negotiation Techniques Learn to use assertive interpersonal negotiation techniques. Using Constructive Criticism and Feedback Learn how to use constructive criticism and feedback. Criteria for Giving Constructive Criticism Explore the criteria for giving constructive criticism. Accepting Criticism in a Positive Manner Learn how to accept criticism in a positive manner. Using Open and Closed Questions Explore how to use open and closed questions. How to Use Exploratory Questions Learn how to use exploratory questions. Using Leading Questions to Persuade Explore how to use questions to lead to a specific response.
Three Interpersonal Communication Styles Unless you are extremely lucky or accommodating, it is unlikely that you will go through your career without ever disagreeing with a colleague. During disagreements, assertive communication comes into its own. But despite this, people often deal with difficult situations in either a passive or an aggressive manner.
1452
Assertiveness is based on the principle that people have the right to decide what treatment they will, or won't, accept from others. Individuals are entitled to stand up for their rights, but not at the expense of the rights of others. In other words, you have the right to ask for what you want, but the other person has the right to refuse you. On this basis, assertive communication is an effective way for adults to resolve their differences productively. Of the three interpersonal communication styles – passive, aggressive, and assertive – passive and aggressive styles are the most common, whereas people find it harder to be assertive. These styles become more pronounced during stressful situations. Behavior and communication can range from totally submissive (passive) at one extreme to overtly threatening (aggressive) at the other. Assertiveness is in the middle. More information about these three interpersonal communication styles is provided here.
The passive communication style When people behave passively, they hope they'll get what they need without having to ask for it outright. They're afraid that if they ask outright, people won't like them. They only hint at what they want, and then hold others responsible for not giving it to them. Passive people often adopt defensive postures, to make it appear that they are taking up less space. They keep eye contact to a minimum and are often soft-spoken, hesitant, and cautious. They also can behave passive aggressively and resort to sabotage in retaliation for not getting what they want. People act passively because they fear conflict or confrontation. Since passive people go out of their way to be liked, they think that they are building good relationships with co-workers. In fact, the opposite is often true. Work relationships become unstable, because colleagues tire of "second guessing" what passive people really want, and hearing about the "sacrifices" that passive people claim to have made.
The aggressive communication style When someone is adopting an aggressive communication style, being liked is not a priority. Being feared is more important. Aggressive people will say what they think, not caring about the impact on the receiver. Aggressive people demand what they want, and the only rights and feelings that concern them are their own. Aggressive people adopt a threatening stance, taking up as much space as possible by standing with legs apart and hands on hips. They act aggressively because it works – those around them take the easy route, and give in when faced with their offensive behavior. However, any gains are short term. Working relationships can't flourish in an atmosphere of resentment, and co-workers may even retaliate with sabotage or insubordination.
1453
The assertive communication style If you are being assertive, you care about other people's feelings, but don't feel totally responsible for them. You believe that you should take care of your own needs, and you trust others with theirs. You don't want to be feared, but you're not desperate to be liked, either. You are prepared to let others decide what they think of you. To behave assertively, stand straight, and maintain eye contact with the other person. Ask for what you need, and say what you think. You also should use "I" statements. Consider the following examples of assertive statements:
"I feel very uncomfortable when you use bad language, and I'd like you to stop."
"Well, I'm moving offices now. I can't stand this language."
By acting assertively, you guide others to your desired outcome by enabling them to see the connection between their action and your response. Acting assertively will help you to build more stable and effective relationships, both inside and outside of the workplace – although you won't necessarily be liked all of the time. Assertive communication is not always received well, so it takes courage to stand up for yourself. This is particularly true for passive people, who find it difficult to be direct. At first it can be hard to maintain your assertiveness. Initially, people may react negatively while they are getting used to the "new you." You need to judge when to speak assertively, and to whom, but it's worth the effort. The long-term results of assertiveness are all positive, including greater self-esteem and more successful negotiations. Sometimes it may feel uncomfortable, but people will soon be giving you the respect that you show them, which can only improve your work relationships.
Four Types of Assertive Responses How often have you been lost for words when someone interferes, interrupts, or makes an insulting remark? When others attempt to manipulate your behavior by telling you what you should do – or what they would do in your place – you may think your only options are to agree or to argue. However, there is a third option – an assertive response. By using this type of response, you can maintain both your self-esteem and your harmonious relationships with others.
1454
When you don't want to submit to unacceptable remarks or be confrontational, you can use some simple but effective assertive responses to take a lower-key approach. Four types of assertive responses you can use are explained here.
1. Persistent assertiveness You can use persistent assertiveness to put your point across even when you are being interrupted, or when someone is trying to change your mind. To use persistent assertiveness, you firmly restate your point or request after the other person has interrupted or spoken. When using persistent assertiveness, it's important not to get drawn into arguments or explanations. Ignore the other person's baiting, manipulation, or irrelevant logic. Keep repeating your point, using a low, pleasant voice. Don't get pulled into a discussion about the rights and wrongs of the situation.
2. Empathetic assertiveness If you find another person's words or behavior unacceptable, don't assume the person's purpose was to offend. The person may not realize the effect of what he or she has said or done. You can use empathetic assertiveness to comment on unacceptable remarks or behavior without causing conflict. To make your views known with empathetic assertiveness, you should describe the negative impact of the person's remarks or behavior, avoid accusations, and let the other person decide what to do. This type of response demonstrates empathy with the other person's position and shows that you're not out to pick a fight.
3. Indefinite assertiveness Use indefinite assertiveness to deflect unwelcome criticism or suggestions. This response is useful when you want to maintain a good relationship with the other person, but don't necessarily want to follow his or her suggestions. To use this approach, you vaguely agree with as many of the facts as you want to, but you don't make a commitment to changing your behavior or applying the suggested solution. Indefinite assertiveness enables you to sidestep manipulative advice or criticism without appearing to totally disagree.
4. Negative acknowledgment It's difficult to be assertive when you're receiving valid criticism, particularly when it's delivered in a hostile manner. Negative acknowledgment enables you to handle hostile but valid criticism calmly and to stay assertive even when you have to admit your mistakes. To use this approach, you focus on the content of the criticism and not its delivery. This enables you to prevent the discussion from escalating into an argument.
1455
These four assertive responses may not be effective every time, and they may not provide permanent solutions for all situations. But they can take the sting out of certain situations. Being assertive also feels better than being submissive. It enables you to maintain your self-esteem without resorting to the sorts of aggressive confrontations that destroy relationships, and enables you to sidestep interference, feel better about criticism, and get on with your work in your own way.
Assertive Interpersonal Negotiation Techniques When problems arise with work colleagues, it should be easy to make them aware of your wants and needs. Unfortunately, even as the words form in your mouth, your brain often starts thinking about the possible consequences of what you are about to say. You begin to have misgivings and eventually decide to stay silent. But silence won't get you results. That's why you need to learn to think and speak assertively. When you act aggressively, you place the responsibility for how you feel on the shoulders of others, and demand what you want. When you act passively, you take responsibility for other people's feelings, and hope that they will give you what you want. When you act assertively, you accept responsibility only for yourself, your actions, your needs, and your feelings. And you ask for what you want. Assertive interpersonal negotiation techniques enable you to convey your wants, needs, and intentions clearly without ignoring the rights of others. Four techniques you can use and their most common uses are
declarative assertiveness, to state what you think or want
confrontational assertiveness, to deal with unacceptable behavior
cooperative assertiveness, to reach a satisfactory compromise
assignation of accountability, to persuade people to deal with the consequences of their actions
You can use these techniques to handle a variety of situations and to ask others to change their behavior. But when negotiating assertively, you should always focus on what is right, not who is right. The basis of assertiveness is that you have the right to ask for what you want, and the other person has the right to refuse. This means that you won't always get the desired result. But it's better to try to negotiate your preferred solutions assertively, rather than being aggressive or passive. The success of assertive communication is affected by the balance of power. The declarative and confrontational assertiveness approaches are easier to use – and have more impact – when you have authority over the other party. When you have equal or less authority than the other party, cooperative assertiveness or assigning accountability may be more effective.
1456
There are occasions when people don't realize, or acknowledge, the negative results of their behavior. Either they believe that you are overreacting, or they expect you to accept the situation. You might feel that your only options are to shrug it off, or risk an argument. But there is another route. You can assign accountability. It's not unusual to feel unprepared for dealing with problem situations, because they usually arise unexpectedly. However, by practicing assertive communication approaches, you will be better equipped to reach an acceptable outcome without getting tongue-tied or angry. Once you accept that everyone has both entitlements and responsibilities, you can use assertive communication techniques more effectively. They will improve your ability to stand up for yourself and increase your chances of achieving acceptable outcomes to problem situations.
Using Constructive Criticism and Feedback For many people, the word criticism has negative connotations. That's because some people give "feedback" with the sole aim of delivering a personal attack and causing hurt. So it's not surprising that criticism isn't always gratefully received, even when the intention behind it is positive. People don't enjoy hearing that they are not perfect. And some claim to be giving constructive criticism when, in fact, they are just voicing their disapproval or dissatisfaction. These misunderstandings arise because people aren't aware of the differences between real criticism, feedback, and personal attacks.
Criticism is evaluative – You assess another person's performance or actions. Criticism becomes constructive when you include appropriate alternatives to boost the chance of improvement.
Feedback is descriptive – You describe the action or behavior in question and inform the person of your reaction to it. You retain accountability for your feelings and don't insist that your words are acted upon.
A personal attack is judgment of a person – A personal attack is also evaluative, but you voice your judgment of the person, not of the person's performance, actions, or behavior. Often, your assessment of someone is based on your assumptions about his or her intentions, opinions, and beliefs.
You can't give truly constructive criticism unless you are qualified to do so. To be qualified, you must be sure of the criteria against which the performance is being judged and be able to provide the tools to encourage the necessary improvement. This requires suitable credentials, such as experience, authority, or proven expertise. Without these, your criticism is unlikely to be accepted and acted upon. If you are unsure whether you have the right credentials, it's best to limit your comments to giving feedback. If you're not eligible to give constructive criticism, you can still offer advice, but only if it is
1457
sought. Nothing ignites conflict or resentment faster than someone giving an unsolicited or unqualified judgment of another's work. Don't use criticism to get your own way. There are assertive communication techniques you can use to reach a preferred outcome, or to defend yourself against the manipulative behavior of others. The only acceptable reason to give criticism or feedback of any kind is to try to improve a person's performance for his or her benefit, and that of the company. At work verbal personal attacks are always inappropriate. When you offer constructive criticism, you must be willing to take some responsibility for the results achieved – both good and bad. After all, you are the one who has used your superior position, knowledge, or experience to persuade someone to execute a task differently. Any other approach is unfair and guaranteed to cause discord. Only constructive criticism and feedback given together can positively affect interpersonal interactions. Criticism alone and personal attacks may jeopardize relationships by making receivers feel negatively about the givers. Whenever you are tempted to verbalize your judgment of someone else's behavior, make sure that your intention is to improve and not to punish. By keeping in mind the points discussed above, you'll be able to effectively use constructive criticism and feedback.
Criteria for Giving Constructive Criticism Giving criticism properly and constructively is not easy, particularly in the workplace. Fear of confrontation often prevents managers and team leaders from tackling unacceptable performance. However, deferring action can lead to an escalation of the situation, and then it becomes more difficult to handle. The main reason people don't take criticism well is because it is often used as a disguise for personal attack. The only acceptable reason for criticizing others at work is to gain performance improvements. True criticism evaluates the person's behavior, not the person. Use constructive criticism to make suggestions about how the person can improve his or her behavior. For criticism to be effective, it must meet five criteria, which are described. If your criticism meets these five criteria, your motive will appear to be supportive, not manipulative. This will enable the receiver to accept your criticism more easily. However, if your criticism fails to meet these criteria, then the recipient has every right to refuse it.
1. Criticism must be performance-related To be accepted by the receiver, criticism must be performance-related. This means that it should be given only when someone falls short of the company's accepted standards.
1458
You should criticize only things that have a direct impact on an individual's work. So, you can't criticize people for looking as if they've been out all night, but you might need to criticize the fact that their performances are below standard because they were out all night. Think carefully about what you expect to achieve by criticizing someone before you do it. Are you motivated by a desire to help the individual to improve his or her performance? Or are you trying to get the person to change his or her attitude? If the latter is true, you are criticizing someone for the wrong reason. You should focus on achievable, performance-related outcomes.
2. Criticism must be precise As well as being performance-related, your criticism also must be precise and based on fact. If you criticize in a vague way, then you run a high risk of the verbal exchange becoming confrontational. Often people become defensive when they are being criticized, and they try to protect their positions by attacking you. Many times, these counterattacks center on the validity of what you have said. If your information is incorrect, it will create further conflict. So make sure that you have all of the facts and that you understand the issues thoroughly before criticizing someone.
3. Criticism must be given in private Remember that the aim of criticism is to improve performance and not to humiliate the receiver. Only the person concerned should hear what you have to say.
4. Criticism must be delivered politely Just because someone's performance is below standard, doesn't give you the right to be rude. Ensure that you use appropriate language.
5. Criticism must be "posture-sustained" or backed up by the giver's body language You also need to make sure that your body language sends the same supportive message as your words. Avoid combative postures or threatening gestures, such as pointing your finger, clenching your fist, or invading the receiver's personal space. Physically demonstrate that you are prepared to listen to the other person's point of view. Being criticized is sometimes hard, but giving criticism is not easy either. Remember to approach your receiver as a problem-solving partner and not as an accusing adversary. Before giving criticism, remember that you must always be polite, and your body language should support what you say. But most importantly you should always give precise, performance-related criticism, in private. By keeping these five criteria in mind, you can ensure that your criticism is effective and that it is received as it is intended.
1459
Accepting Criticism in a Positive Manner You can't control what is said to you. But you can control the manner in which you respond to the comments of others. One of the most difficult communications to respond to is criticism, particularly when it does not appear to be constructive, or even justified. Whether criticism is valid or not, most people respond negatively to it. However, you need to be able to identify when it is in your best interest to accept criticism in a positive manner, and you should understand how to do this effectively. Criticism should be precise, performance-related, and "posture-sustained," which means backed up by the giver's body language. It should be given politely and in private. Preferably, the criticism should also be constructive, but that isn't always the case. When criticism doesn't satisfy these five essential criteria, you can choose to refuse it, or confront it. The most common reaction to any criticism is "fight or flight." This is a natural human reaction to a perceived attack. It triggers a rush of adrenaline that causes you to try to defend yourself. If you're willing to accept and act on valid criticism, you will achieve better performance and improved results. But an inability to receive valid criticism positively can result in
repeated criticism
conflict and blame
diminished self-esteem
Criticism becomes productive when you accept that your behavior can be changed, and you are willing to do so. It becomes unproductive when you are not open to change. Then the criticism process will simply repeat itself. It's not easy to accept criticism, even when you know that it's valid and that it can help you make a change. When your abilities are being attacked, your natural reaction is to fight back verbally. However, there's a better way to protect your self-esteem. Protection techniques enable you to accept valid criticism assertively, without arguing. Three protection techniques you can use are to
agree with the truth of the criticism
agree with the logic of the criticism
acknowledge that improvement is possible
Agreeing with the truth or logic of criticism isn't a commitment to behavior change. Neither is acknowledging that improvement is possible. These three approaches merely limit the potential conflict that could arise from your instinctive need to retaliate. They help you to avoid feeling bad about yourself, even when the criticism is justified. By agreeing with the critic verbally, you'll feel less victimized.
1460
Performance will be maximized in a work environment where criticism is given constructively and received positively. When people are not afraid to share their knowledge and others aren't too proud to receive and use it, criticism can work to the benefit of all.
Using Open and Closed Questions A conversation between two people seems to be a simple enough undertaking. But you can never be sure how it will play out. Sometimes, the other person will say little. At other times, the other person won't stay quiet long enough to take a breath! Fortunately, certain kinds of questions can help you in these situations. They enable you to get the quiet people to speak up, and the others to quiet down. These questions are either open or closed. Using open and closed questions is like using a faucet. Open questions open the "faucet," allowing the water – or words – to pour from the other person. Closed questions turn the "faucet" in the opposite direction, reducing the flow to a more controlled stream of information. There are many situations where you might want to increase or decrease the flow of information without being too obvious about it. Although you could say, "Tell me all about yourself" to a quiet person, he or she probably wouldn't know where to start. You also could say, "Shut up" to a talkative person, but that would be impolite. Open and closed questions offer a far more subtle approach. You can use open questions when you're eager to learn all about a new acquaintance. These types of questions also are useful when you want to obtain as much information as possible from a job applicant. You can use closed questions to prevent another person from diverting the conversation away from the subject you wish to discuss. These types of questions also are useful in cases of information overload, to stop another person from talking so much. Open questions are based on the words who, how, where, when, which, why, and what, and can't be answered easily with just a "yes" or a "no" answer. Open questions can help you gain information. Of course, it is still possible for people to give minimal responses to open questions, but they'll seem ignorant or rude if they do. Here are a few examples of open questions.
Who was responsible for introducing you to your best friend?
Where do you live, and why?
When you were young, what did you want to grow up to be?
Closed questions are used to gain confirmation, clarification, or commitment. Closed questions can be answered with simple "yes" or "no" answers and are based on words such as can, do, is, should, and will. The skill of questioning lies in being able to use a combination of question types to direct a conversation and gain the information you need without it sounding unnatural. If you use too many open questions, people may feel as if they are being interrogated. But too many closed questions can make them feel that they are not being allowed to speak.
1461
The risk in using open questions repeatedly is that you can get a lot of information and yet still not reach the heart of the matter. That's when closed questions are most useful. With a combination of open and closed questions, you can elicit a lot of valuable information, and then make an informed evaluation of what you have been told. Whether you want information or confirmation, careful questioning will help you to achieve your objectives and put you in the conversational driver's seat.
How to Use Exploratory Questions Quite a few common work situations involve or require extended questioning. Salespeople identifying the needs of customers, managers conducting selection interviews or staff reviews, and consultants investigating the causes of problems all need to ask questions to achieve their objectives. On occasions such as these, it's important to keep the conversation light and unthreatening. Open questions are best for uncovering information. These are questions based on words such as what, where, which, when, who, how, and why. Unfortunately, if you use too many open questions, you can sound as if you are interrogating. In particular, "Why?" type questions can seem threatening. Depending on your tone of voice, they can send a variety of messages – not all of them positive. People don't enjoy being asked a succession of "Why?" type questions, because it can be unnerving. Fortunately, exploratory questions serve the same purpose, but are more acceptable. Exploratory questions are indirect questions and begin with the following phrases and ideas:
"Describe to me..."
"Explain to me..."
"Clarify for me..."
"Tell me..."
Exploratory questions enable you to ask for details and investigate the rationale behind a person's statement, decision, or policy without repeatedly asking "Why?" or "What?" or "How?" They also are less likely to trigger conflict. Consider the following examples.
Instead of asking, "Why does your company use its current supplier?" you could say, "Explain the reasons for your company using its current supplier."
Instead of asking, "Why have you decided to look for another job?" you could say, "Tell me what's prompted your decision to look for another job."
As you can see from these examples, exploratory questions are more sympathetic than just asking, "Why?" Sympathy and a soft approach are essential factors when asking someone a lot of questions. They will help you to keep the other person interested and positive, instead of making the person defensive.
1462
People like to talk about themselves, their thoughts, and their opinions. They also like the company of others who take an interest in them. But they don't want to feel as if they are under a microscope. This is why exploratory questions are so useful. They enable you to get the information you need, while still enjoying a relaxed and natural conversation.
Using Leading Questions to Persuade Imagine this scene: You make what you believe is an acceptable suggestion to a customer or colleague, but no matter how you try to explain it, the person does not see the logic of your proposal. In fact, the more you talk, the more he or she seems incapable of making a decision. The benefit is obvious to you, but the other person just can't see it. In this situation, you can use a leading question to persuade. The purpose of leading questions is to lead another person towards a specific decision or response. That's why these questions often are used in court. The lawyer phrases the question so that by obtaining a simple "yes" or "no" answer, an important point has been made. Consider the following example.
The lawyer asks, "So, would you say that there was longstanding and deep hostility between the defendant and the deceased?"
The witness answers, "Ah...yes, I guess so," and the opposing lawyer jumps up and shouts, "Objection! Attempting to lead the witness, Your Honor!"
In addition to guiding a person to give a preferred response, you can use leading questions to direct people towards certain decisions. In essence, leading questions summarize the advantages to be gained by making a choice, delivered in the form of an inquiry. Leading questions may appear to be manipulative, but they only work if they are linked to something that the other person wants. For your questions to succeed, the person must want what's being offered more than what's required in return. Some other points to keep in mind when using leading questions are listed here.
Leading questions shouldn't be too complicated. You need to keep them as simple and straightforward as possible to guide others to the responses you want.
To direct people towards a specific response, keep your leading questions closed.
Your leading questions should offer an obvious preference. Don't make decisions difficult by asking someone to choose between two equally attractive or unattractive options.
The skill in asking effective leading questions comes from knowing what the other person wants. The success comes from being able to show how it can be obtained. Leading questions enable you to present the other party with a simplified choice that effectively speeds up the decision process. Use them correctly, and you'll be better able to "close the deal" on successful interpersonal negotiations.
1463
Listening Basics SkillBriefs The Seven Components of Communication Discover the seven components of the communication process. Eight Variables That Affect Communication Discover the eight variables that affect communication. How People Communicate Simultaneously Explore the ways in which people communicate simultaneously.
1464
How You Receive Information Explore the different ways in which you receive information. Three Types of Attention Problems Discover the three types of attention problems. Common Causes of Misinterpreted Messages Discover four common causes of misinterpreted messages. Strategies for Improving Your Listening Skills Improve your listening skills using these four strategies. Factors That Influence Your Listening Attitudes Discover nine factors that influence your listening.
The Seven Components of Communication Do you have problems truly listening? Do you find your mind wandering in the middle of conversations. Then you need to develop effective listening skills. To do this, you first have to understand how the communication process works. This will enable you to exchange your ideas and emotions more clearly. To begin, you should be aware of the components of the communication process. A typical conversation involves the following seven key components. 1. The speaker – The speaker starts the communication process by wanting to talk about an idea with you or asking you a question.
1465
2. The communication channel – The speaker selects the best channel to send a message. The channel can be verbal or nonverbal, such as vision or touch. Telecommunication devices are also channels. Each channel limits what can be expressed. 3. The message – The speaker turns an idea into appropriate verbal and nonverbal language to create a message. The message must reflect the channel chosen. For example, the telephone requires more verbal description since there is no visual channel. 4. The listener – A message is always meant for someone. The listener is often the intended target of a message. For successful communication to occur, you must receive and decode the verbal and nonverbal message from a speaker. However, you also can be influenced by other components of the communication process. 5. The feedback – Once you receive a message, you interpret it and respond with verbal or nonverbal feedback. The feedback may cause the speaker to send a new message to clarify or answer your questions. 6. The environment – External components to communication can influence a message. The environment is the situation in which communication takes place. For example, a setting may be formal or informal. Aspects of physical environment such as light, temperature, and room size also influence a message. 7. The noise – Another component is noise. Internal noise may involve a preoccupation with a personal problem or the development of an emotional barrier in response to a word or idea. External noise includes background activity, talk, or static. As you can see, each component is influenced by other components. Together, they form a simple model of communication. By knowing the seven components of the communication process, you can better understand how communication happens – and when you understand how communication happens, you'll be well on your way to communicating more clearly.
The Seven Components of Communication Do you have problems truly listening? Do you find your mind wandering in the middle of conversations. Then you need to develop effective listening skills. To do this, you first have to understand how the communication process works. This will enable you to exchange your ideas and emotions more clearly. To begin, you should be aware of the components of the communication process. A typical conversation involves the following seven key components. 1. The speaker – The speaker starts the communication process by wanting to talk about an idea with you or asking you a question. 2. The communication channel – The speaker selects the best channel to send a message. The channel can be verbal or nonverbal, such as vision or touch. Telecommunication devices are also channels. Each channel limits what can be expressed.
1466
3. The message – The speaker turns an idea into appropriate verbal and nonverbal language to create a message. The message must reflect the channel chosen. For example, the telephone requires more verbal description since there is no visual channel. 4. The listener – A message is always meant for someone. The listener is often the intended target of a message. For successful communication to occur, you must receive and decode the verbal and nonverbal message from a speaker. However, you also can be influenced by other components of the communication process. 5. The feedback – Once you receive a message, you interpret it and respond with verbal or nonverbal feedback. The feedback may cause the speaker to send a new message to clarify or answer your questions. 6. The environment – External components to communication can influence a message. The environment is the situation in which communication takes place. For example, a setting may be formal or informal. Aspects of physical environment such as light, temperature, and room size also influence a message. 7. The noise – Another component is noise. Internal noise may involve a preoccupation with a personal problem or the development of an emotional barrier in response to a word or idea. External noise includes background activity, talk, or static. As you can see, each component is influenced by other components. Together, they form a simple model of communication. By knowing the seven components of the communication process, you can better understand how communication happens – and when you understand how communication happens, you'll be well on your way to communicating more clearly.
How People Communicate Simultaneously Have you ever noticed how many people can talk and listen at the same time? These components of communication can occur simultaneously because people naturally want to respond to interesting or confusing messages they hear. Because listening and speaking can occur at the same time, one person's role as a listener or speaker can change many times during communication. The other components of communication – the message, the channel, and the environment – can also change. The simultaneous model of communication illustrates how each component of communication interacts with and creates change in the other components. The model, which is a continuous cycle or process, demonstrates how a speaker conveys a message to a listener, who then becomes a speaker, conveying a message back to the first person, who is now the listener. The speaker's goal is to get the listener to recall knowledge and compare it to the new information outlined in the speaker's message. The listener must inform the speaker if the listener doesn't understand. The speaker creates better understanding by responding with a modified message. Listeners gain understanding by switching speaking and listening roles throughout the cyclical process. People may interrupt and finish each other's ideas, showing that understanding and speaking have
1467
occurred simultaneously. A confused listener will seek clarification or express misunderstanding during the message's transmission. The speaker and listener continuously change roles as the listener tries to understand the speaker's message. The messages are affected by the environment and the channel used to communicate. The cycle continues until the understanding of a message finally occurs. During this cycle, the speaker and listener are responsible for making sure the message is understood by remaining constantly aware of how the components of communication influence understanding. Changes occur in the channel or method of communication, in the message content or tone, and in the environment in which communication happens. A speaker and listener constantly adapt to changes in these components to ensure they understand. Changes can occur in the following ways.
Channel – The channel may change in mid-process if the speaker perceives the listener didn't receive the message. For example, a visual channel may need to change to verbal or a telephone call to face-to-face. Also, it's possible for a listener to make a visual reply such as nodding "yes" while the speaker is talking.
Message – During a conversation, the message may change to address problems with other components, such as loud background noise or a change in channel. Also, the speaker may perceive the need to clarify a point before continuing. The tone also can change as the listener begins to understand.
Environment – The initial background environment, including noise, may disrupt understanding, and the location may have to change. The environment also may be too formal or relaxed for the type of conversation. A discussion of a personal issue, for example, should occur in private.
The simultaneous communication process shows how communication occurs in the real world, where a person can often talk and listen at the same time. The speaker's and listener's roles must be interactive to create meaning and understanding. By being aware of the simultaneous model of communication, you'll have a better understanding of how people communicate with each other.
How You Receive Information Have you noticed that when you're listening to someone, you not only hear the person's message, you also can "see" that message? This is because you receive both aural and visual messages while you're listening to someone. Receiving information involves the physical reception of a message by a listener. This information can be seen visually, by the eyes, or heard aurally by the ears. Visual messages include situational background activity, the speaker's complementary hand motions, body posture, eye contact, and head motions. Aural messages include both background noises and verbal messages, such as the speaker's choice of words, tone of voice, and vocal inflection. The visual information a listener receives makes up a large portion of communication. Studies estimate that the visual component can range from 65 percent to 93 percent of a message. Since the visual
1468
component of a message can be so important in listening, you should understand what visual information the listener can see. Visual messages can take the following forms.
Interpersonal space – Interpersonal spacing is the distance between two or more people. The space between two friends or coworkers should be about one-and-a-half to four feet when talking. The listener becomes uncomfortable if the speaker is too close. Likewise, too great a distance indicates disinterest with the speaker and subject.
Graphical, object, or color reinforcement of ideas – A message can be reinforced by visual images such as pictures and presentation aids. In casual conversation, reference can be made to objects or people nearby to provide comparison information or direction. Color plays an important role when referring to aesthetic qualities, contrasting graphical information, regulating traffic, or indicating significance.
Facial expressions – A speaker's facial expressions send important visual messages that either match or contradict the aural message. The face conveys a wide variety of emotions or feelings. Some common facial expressions are happy/agree, interested/thinking, unhappy/disagree, and bored/disinterested.
Body movement and position – The last visual component a speaker uses to send a visual message or emphasize a point is body movement and positioning. For example, an up-down nodding of the head shows agreement, or "yes," while left-right shaking of the head shows disagreement, or means "no." The positioning of various parts of the body also can send a message. For example, crossed arms or yawning can signal disinterest.
Visual information is an important aspect of communication. However, hearing is still the foundation of listening, as a message must be audible to a listener. During the course of a conversation or a presentation, a listener hears a variety of aural information. The types of aural information include the choice of words, contextual sounds, and noise.
Choice of words – The choice of words contains the key information a speaker wishes to convey. The message is usually composed in such a way to inform the listener or to get the listener to react in a manner desired by the speaker. The choice of words can aid or confuse understanding.
Contextual sounds – Contextual sounds add emphasis to a message by using vocal tone, enunciation, and other situational sounds. An example of a situational sound involves emphasizing a word by pounding a fist. Also, the use of sarcasm, humor, or emphasis adds meaning to a message.
Noise – Noise is any external sound or internal thought process that interferes with the successful reception of information. External noise can include office noise, construction, or interruptions. Internal noise includes emotional responses to words or focusing on other ideas or problems.
Remember, receiving information is both seeing and hearing messages. Your awareness of how you receive information can help you become a better listener.
1469
Three Types of Attention Problems To listen effectively, you must pay attention to the speaker. This may sound like an obvious point, but paying attention is sometimes more difficult than you may think. The process of paying attention occurs when you prioritize the many messages you hear so you can focus in on the message that interests you. Your message prioritization can be affected by the following attention problems.
1. Selective attention It's natural for you to be selective about what you pay attention to. If you paid attention to all the messages you see or hear, you would quickly overload your brain. Almost everyone has a flexible and selective process of allocating attention to competing priorities. To deal with the many demands for your attention, you create listening priorities about the relative importance of each message. Unconscious and conscious decisions determine your priority list.
Unconscious decisions – Unconscious decisions are those that are usually automatic. This involves responding to a sudden noise or paying attention to a person who calls out your name. The speaker or action catches your attention and you stop listening to competing messages.
Conscious decisions – When you make conscious decisions, you use logic and rational thought to determine which message you should focus on. Listening to your boss will take priority over other messages, such as a ringing phone or a coworker speaking.
2. Energetic attention This is the amount of effort you place on paying attention and remembering. You use more mental energy when the listening task is difficult or your attention is divided between listening tasks. For example, you may have noticed that focusing on a complex oral argument, such as a technical discussion, causes you to ignore other messages. Likewise, if you're trying to talk to someone on a busy street, it may be hard to focus on what the person is saying due to the noise, people, and traffic. Similarly, when you receive too much information, you tend to scan and hear only certain highlights, or none at all. This can occur at busy social functions when you can hear only parts of many conversations. Do you possess the energy to always pay attention and then remember everything that is said? Most people can't do this. Your ability to pay attention often depends upon the message you receive. People tend to be more energetic listeners when a message is simple and easy to remember.
3. Fluctuating attention Fluctuating attention involves the gradual fading in and out of your attention during a listening situation. This is a natural human condition. Fluctuating attention can occur in a warm room, during long
1470
presentations, when a person is tired, or when you focus on the unstated or perceived hidden message in a conversation and you miss part of what has been said. The influences of selective, energetic, and fluctuating attention directly impact your ability to listen. By being able to identify the three types of attention problems, you can become a much better listener.
Common Causes of Misinterpreted Messages Understanding information is often a difficult task. Making sense of information relies on your ability to interpret or assign meaning to what you hear. To assign meaning to a message, you have to evaluate what you hear so that you develop an understanding of the communicated idea. Understanding occurs at several levels. You must examine what was said for content, how it was said for tone, and why it was said to determine any actions required from you. When assigning meaning, you're trying to match your understanding of the intent of a message to the intended message of the speaker. However, this can be difficult, since it is almost impossible to read another person's mind exactly. In fact, many of the assigned-meaning problems people encounter are actually problems related to how they think. Listed below are some common causes for incorrect assigning of meaning. Keep in mind that not all of these common causes will always be apparent.
Frame of reference – This is also known as your point of view. It can alter a listener's interpretation of a speaker's words. Culture, experience, attitudes, knowledge, skills, feelings, expectations, values, beliefs, biases, and other personality-shaping influences can affect your frame of reference.
The information selection process – This is based on your frame of reference. Often, many people pay attention or seek out information only when it supports a personal viewpoint. Information to the contrary is often disregarded or the speaker is ignored.
Control over linguistics – Many people incorrectly assign meanings to words due to poor understanding of linguistics. Often, they are unaware of the correct context in which words are used. Incorrect choices of words on the part of the speaker also create misunderstandings or emotional responses.
Emotional triggers – You likely have certain words, ideas, topics, or phrases that trigger emotional responses. You may have immediate and unthinking positive or negative reactions to these triggers. This will cause you to miss or assign the wrong meaning to a message.
Your ability to recognize how the meaning of a message can be influenced will help you understand why you may not always comprehend what you hear. Pay careful attention to the common causes of misinterpreting messages, and you'll be better able to listen more effectively.
1471
Strategies for Improving Your Listening Skills To become a better communicator, you have to learn how to listen more effectively. To do that, you can use a number of successful strategies to modify and improve your listening skills. Four strategies you can use to improve your listening skills are described below.
1. Understand yourself Before you can improve your listening, you need to know how your thinking influences your present listening abilities. Once you understand yourself better, you'll be able to stay more motivated while you listen. Understand that your personal value system has stereotypes that can negatively affect your listening. Don't let your biases interfere with your willingness to listen to a message. Workshops and self-help books are two of the many resources you can use to better understand yourself.
2. Be motivated Listening is an active process that requires your constant attention. You must make a considerable effort to listen to others' views or ideas, rather than expressing your own. Your motivation depends on your willingness to listen to others, as well as on the personal goals you set.
Your willingness to learn depends on how well you know and respect the speaker, how important the content is to you, and which environmental conditions influence the communication.
Setting personal goals helps motivate you to be a better listener. This type of motivation isn't a material incentive like money or a promotion. Instead, it comes from setting a goal and then achieving it through better listening.
3. Listen actively Once you're motivated, you need to listen actively to what is said. Active listening requires you to participate in the conversation, ask questions, listen carefully, and show the speaker that you are paying attention. This will help you to better understand what a speaker is trying to say. To listen actively, you need to pay attention and drop all other activities. Make eye contact with the speaker, move to a comfortable speaking range, and lean toward the speaker to show you're paying attention. You also can show the speaker you're listening by occasionally stating "uh-huh" or "I see what you mean." Ask questions to clarify information or to get more specifics.
4. Send appropriate feedback To indicate to the speaker your degree of understanding, you need to send appropriate feedback. When giving feedback, keep your personal feelings or evaluations separate from the message. Give prompt feedback that is clear and concise, and avoid using complicated words and concepts. Also, make sure
1472
the feedback is pertinent to the message or situation. Clear up any ambiguous points, and wait to be asked before giving advice. To succeed in today's complex business world, you have to be a good communicator, and specifically you need to be a good listener. By using the four strategies described above – understanding yourself, motivating yourself, listening actively, and sending feedback – you can improve your listening skills and become a more effective listener.
Factors That Influence Your Listening Attitudes There are a wide variety of factors that influence your listening attitudes. These factors range from your own culture to your personal preferences. Many of these factors are based upon your experiences over your lifetime. The nine factors that influence the way you listen are as follows.
1. Culture Listening can be affected by cultural differences. Culture involves the customs, behaviors, beliefs, traditions, perceptions, and language of a group of people. Some cultures place higher value on listening to specific groups of people, such as men or authority figures.
2. Hemispheric specialization Listening also can be affected when the left or right side of the brain has dominance over certain body functions or thinking processes. This is called hemispheric specialization, and it depends on how a person's brain has developed. The left side of the brain has different functions than the right side of the brain. The left side can identify names and concepts, recognize sound, and analyze and create concepts. The right side is linked to feelings and emotions.
3. Physical and psychological state Other factors that influence the listening process include a person's physical and psychological state. Listening is physically affected when hearing and vision deteriorate. Your psychological state can influence how you receive information, pay attention, and understand information. Worrying about finances, job security, or family interferes with listening.
4. Listener apprehension Apprehension can occur when a person is uncomfortable with a subject, speaker, or method of communication. It also can occur when one misinterprets messages, or is incapable of understanding or handling complex or emotional messages.
1473
5. Self-concept Self-concept is the way you feel about yourself. People who are frequently told to "pay attention" or "listen up" often develop a negative self-concept of being a poor listener. They may then behave as a poor listener. People who hear encouraging phrases, such as "Good job, you were paying attention," develop a positive self-concept and tend to be better listeners.
6. Gender Social conditioning causes most men and women to listen differently.
7. Age As you get older, you lose aural and visual abilities, making it harder to receive messages. Older people's listening needs, attitudes, and behavior also change over time as a result of their life experiences.
8. Time If you don't have time to participate in a conversation, you may be more concerned about the next activity than the present listening situation. This may cause you to miss essential details. The time of day also can affect your ability to listen effectively.
9. Listening preferences Listening preferences involve a fondness for certain listening situations. You develop these preferences over time as usual responses to recurring situations. Your personality can also affect your listening preferences. A wide variety of factors influence the way you listen. Awareness of these factors will help you determine where your listening strengths and weaknesses lie. Once you have this awareness, you can work on techniques that will help you develop better listening habits.
1474