Read Aloud the Text Content

This audio was created by Woord's Text to Speech service by content creators from all around the world.


Text Content or SSML code:

664 Chapter 13 Programming Languages and Program Development Computer Programs and Programming Languages Although you may never write a computer program, information you request may require a programmer to create or modify a program. Thus, you should understand how programmers develop programs to meet information require- ments. A computer program is a series of instruc- tions that directs a computer to perform tasks. A computer programmer, often called a developer, creates and modifies computer programs. To create a program, programmers sometimes write, or code, a program's instructions using a pro- gramming language. A programming language is a set of words, abbreviations, and symbols that enables a programmer to communicate instruc- tions to a computer. Other times, programmers use a program development tool to create a pro- gram. A program that provides a user-friendly environment for building programs often is called a program development tool. Just as humans speak a variety of languages (English, Spanish, French, and so on), programmers use a variety of programming languages and tools to create programs (Figure 13-1). Several hundred programming languages exist today. Each language has its own rules for writing the instructions. Languages often are designed for specific purposes, such as scientific applications, business solutions, or Web page development. When solving a problem or building a solution, programmers often use more than one language; that is, they integrate the languages. Two types of languages are low-level and high-level. A low-level language is a programming language that is machine dependent. A machine- dependent language runs on only one particular type of computer. These programs are not easily portable to other types of computers. Each 9.03 Figure 13-1 Programmers must decide which programming languages and program development tools to use when they create programs. Programming Languages and Program Development Chapter 13 673 • Visual C++ is a programming language based on C++. Not only is Visual C++ a powerful object-oriented programming language, it enables programmers to write Windows, Windows Mobile, and .NET applications quickly and efficiently. Features that make Visual C++ so powerful include reusable templates, direct access to machine level memory locations, an optimizing compiler, and advanced error reporting. • Visual C# is a programming language that combines programming elements of C++ with an easier, rapid development environ- ment. The purpose of Visual C# is to take the complexity out of Visual C++ and still provide an object-oriented programming language. Programmers familiar with the C/C++ programming language family often migrate to the easier-to-use Visual C#. Visual Programming Languages A visual programming language is a language that uses a visual or graphical Ribbon Project-CodeGear RAD Studio for Microso Windowsbbon DemoMainForm interface for creating all source code. The graphical interface, called a visual programming environment (VPE), allows programmers to drag and drop objects to develop programs. Examples of visual programming languages include Alice, Mindscript, and Prograph. Delphi Borland's Delphi is a powerful program development tool that is ideal for building large-scale enterprise and Web applications in a RAD environment (Figure 13-11). Programmers use Delphi to develop pro- grams quickly for Windows, Linux, and .NET platforms. Delphi also provides visual modeling tools based on the UML. Recall from Chapter 12 that the UML (Unified Modeling Language) has been adopted as a standard notation for object modeling and development. With Delphi, programmers easily link the UML designs to the working solutions. File Edit Search View Refactor Project Run Component Tools Window Help Welcome Page RibbonDemoMainForm Default Layout Class Explorer Container Ribbon Project - Ribbon DemoMainFom globals RibbonDemok TFleFormat Activate RibbonProject.dprej - Pr... 9 Liew Ribbon Project Remove Home Insert Page Layout Control Types Document1-CodeGear Ribbon Project References Sync Expand Collapse TmAbbonDemoMair Calibri (Body) Ribbon Project Copy Paste globals Ribbon Project Format Painter Bex Clipboard Font Paragraph Product Description Fle ProjectGroup2 RibbonProject.exe Build Configurations RibbonDemoMainForm.pas Properties Events ActionManager Ribbon Align alTop Anchors Caption CaptionFont ColorMap Cursor on Project (TFont) Ribbont- aDefault Custom Hint Documentame Documen Integrated c EA/Stu Business mo DT/Stu... Data transfo QPowerS SQL IDE for Schem Automated DBArtis Cross-platfo DSAudi Network-ba File name SmallImages Timageli EdtCut 1:TEdeCut EdtCopy1:TEdtCopy Frit Parte 1 TFPate Structure Class Explorer Object Inspector Ribbon1 TRibbon [Left,ak AlignwithMargins false ApplicationMenu (TApplica CodeGear Products Delphi Object Pascal ba Welcome to the world of Unicode with Delphi 「 Delphi 將帶您進入Unicode 的世界!! Bu Coo based RAD Delphi によるUnicodeの世界にようこそ!! Builder Eclipse-based la Interface SQL-compliant. Καλώς ήλθατε στον κόσμο του Unicode με 3rdRail Powerful IDE for Delphi Delphi... The only RAD PF Добро пожаловать в мир Юникода Blackfis SQL-compilant DatabaseGear Products ER/Stu... Model-drive XRapids сиспользованием Дельфи Resources for RibbonProject.dproj Resource files RoRibb Mod... Dat Tool Palette Search Vista Dialogs Ribbon Controls Туре Enabled Font Height HelpContext HelpKeyword true (TFont) 145 o Autumn Le... RCData Creek.jpg RCData Desert Lan... RCData Deck.jpg RCData Forest.jpg RCDeta Forest Flo... RCDeta All shown TRibbon TRibbonComboBox TRibbonSpinEdit ScreenTipsManager TScreenTipsPopup DataSnap Chent dbGo InterBase Indy Clients Indy Servers Indy 1/0 Handlers Indy Intercepts Figure 13-11 The latest version of Delphi, shown in this figure, makes Windows development tasks faster, better, and easier by supporting Microsoft's .NET Framework with both Delphi and C# languages, as well as Delphi for Windows applications in a RAD environment. Properties Identifier Resource Identifer: bolmage_4 Jpgimage pgimage 2 pgimage 3 pgimage 4 Jpgimage_5 pgimage_6 Resource Type: RCData Add... Remove OK Cancel Help 674 Chapter 13 Programming Languages and Program Development marketing - All TEAS Fle Ed 440 PowerBuilder PowerBuilder, developed by Sybase, is another powerful program development RAD tool that is best suited for Web-based, .NET, and large- scale enterprise object-oriented applications. Programmers also use PowerBuilder to develop small- and medium-scale client/server appli- cations. PowerBuilder includes a consistent interface, wizards, and many other features that enable programmers to develop applications quickly (Figure 13-12). In terms of complexity, PowerBuilder is comparable to Delphi. 16 V119)-Powerbuilder View Insert Format Design Rows Run Tocks Window Help Arial Bales orders_by_rep (mis) (c:\dsp115marketings amples 115wess datawindow.pbt)-Window emp prent orders.background.gradient.spread Design-d sales orders_by_sp Expressions Rep ID Name Detail sale employee_emp 11 Trader group sales_order_sales_sup1 Summary ! Prevesa · d_sales_onders_by_rep Rep ID Name Punctions: Columns sales order sales rep aus) aA) aur(s) atan(s) meg for al bitmap(s) mployee mp hame compute mp_prant orders mp orders 9.77% 129 Chin, Philip 57 148 Jordan, Julie 2 p.31% 195 Dill, Marc 50 .69% 299 114 Cancel 8334 Vesty Hilp Scale Spread Repetition Mode p pront onder Postion Tools By Repetition Count (0) Repettion Court Other Programming Languages and Development Tools The following sections discuss a variety of other programming languages and program development tools. 4GLS A 4GL (fourth-generation language) is a nonprocedural language that enables users and programmers to access data in a data- base. With a nonprocedural language, the programmer writes English-like instructions or interacts with a graphical environment to retrieve data from files or a database. Nonprocedural languages typically are easier to use than procedural languages. Many object-oriented program development tools use 4GLs. One popular 4GL is SQL. As discussed in Chapter 10, SQL is a query language that allows users to manage, update, and retrieve data in a relational DBMS (Figure 13-13). These powerful languages allow database administrators to define a database and its structure. They also enable users to maintain and access the data in the database. Figure 13-12 PowerBuilder is a program development RAD tool ideal for building large-scale and Web-based applications. QUIZ YOURSELF 13-1 Instructions: Find the true statement below. Then, rewrite the remaining false statements so that they are true. 1. An interpreter is a program that converts an entire source program into machine language before executing it. 2. C and COBOL are examples of assembly languages. 3. C# is an object-oriented programming language based on PowerBuilder. SQL SELECT LAST_NAME, FIRST_NAME, GROSS_PAY FROM EMPLOYEE WHERE OVERTIME_HOURS > 0 ORDER BY LAST_NAME; LAST_NAME Antiqua FIRST_NAME GROSS_PAY Martin 780.00 Charles Leslie 715.00 4. Delphi is an object-oriented programming language developed by Sun Microsystems. Guillan Anita 847.50 5. Two types of low-level languages are machine languages and Source languages. 6. Visual Studio is Microsoft's suite of program development tools that assists programmers in building programs for Windows, Windows Mobile, or operating systems that support .NET. Quiz Yourself Online: To further check your knowledge of pages 664 through 674, visit scsite.com/dc2011/ch13/quiz and then click Objectives 1 - 3. results Figure 13-13 SQL is a 4GL that can be used to query database tables. This query produces an alphabetical list of those employees who receive overtime pay; that is, their overtime hours are greater than 0. Programming Languages and Program Development Chapter 13 ? FAQ 13-1 Why is it necessary for programmers to know SQL? Programmers often write programs that interact with a database in some fashion. For this rea- son, programmers must know SQL so that their programs can communicate with the database. For more information, visit scsite.com/ dc2011/ch13/faq and then click SQL. Classic Programming Languages In addition to the programming languages discussed on the previous pages, programmers sometimes use the languages listed in Figure 13-14, which were more popular in the past than today. Read Looking Ahead 13-1 for a look at the future of programming. LOOKING AHEAD 13-1 Selecting Programming Languages with Long Lives Choosing the best programming language can be a dilemma that affects programmers for years to come. If they select a language that remains popular for at least five years, chances are that employees at that time will be able to modify and enhance the code. COBOL, for example, } byte) protected) double 2 byte[] sted2 = protection out.writeuTFCUsers out.writeInt(protected. Teng out.write(protected2); out. flush(): Classic Programming Languages Ada ALGOL APL BASIC Derived from Pascal, developed by the U.S. Department of Defense, named after Augusta Ada Lovelace Byron, who is thought to be the first female computer programmer ALGOrithmic Language, the first structured procedural language A Programming Language, a scientific language designed to manipulate tables of numbers Beginners All-purpose Symbolic Instruction Code, developed by John Kemeny and Thomas Kurtz as a simple, interactive problem-solving language Forth Similar to C, used for small computerized devices FORTRAN HyperTalk LISP public static void main(st String host = args[0]: int port = 7999; String user = "John"; String password = "sh Socket s = new Socke Logo client client = new client.sendAuthent Modula-2 was developed in the 1960s, and COBOL pro- grammers still are being sought on popular employment Web sites. Some languages that are experiencing popularity today are expected to continue growing in use. JavaScript, for example, is gain- ing momentum, as are Ruby on Rails and Perl. Many programs for the iPhone are written in Cocoa, and Google's App Engine uses Python, so programmers knowing these languages are in demand. As programming evolves, some trends to watch are the blending of popular languages, the development of scripting languages for the Web and for cloud computing, the ability to insert customized code easily in a browser, and the rise of amateur programmers who will use new, graphical languages to improve their computing experience. For more information, visit scsite.com/ dc2011/ch13/looking and then click Programming Future. Pascal PILOT PL/1 Prolog RPG Smalltalk FORmula TRANslator, one of the first high-level programming languages used for scientific applications An object-oriented programming language developed by Apple to manipulate cards that can contain text, graphics, and sound LIST Processing, a language used for artificial intelligence applications An educational tool used to teach programming and problem solving to children A successor to Pascal used for developing system software Developed to teach students structured programming concepts, named in honor of Blaise Pascal, a French mathematician who developed one of the earliest calculating machines Programmed Inquiry Learning Or Teaching, used to write computer-aided instruction programs Programming Language One, a business and scientific language that combines many features of FORTRAN and COBOL PROgramming LOGic, used for development of artificial intelligence applications Report Program Generator, used to assist businesses with generating reports and to access/update data in databases Object-oriented programming language Figure 13-14 Classic programming languages. 675 676 Chapter 13 Programming Languages and Program Development Application Generators An application generator is a program that creates source code or machine code from a specification of the required function- ality. When using an application generator, a programmer or user works with menu-driven tools and graphical user interfaces to define the desired specifications. Application generators most often are bundled with or are included as part of a DBMS. An application generator typically consists of a report writer, form, and menu generator. As dis- cussed in Chapter 10, a report writer allows you to design a report on the screen, retrieve data into the report design, and then display or print the report. A form is a window on the screen that provides areas for entering or changing data in a database. Figure 13-15 shows a sample form design and the resulting form it generates show- ing sample data a user may enter in the form. A menu generator enables you to create a menu for the application options. If you create three reports and two forms for an application, for example, the menu would contain at least six options: one for each report, one for each form, and one to exit, or quit, the application. Figure 13-15a (form design) Form Header Employee Form Go to Unbound F Detail General Hours First Name First Name Last Name Company Job Title Last Name Company Job Title Phone Numbers E-mail Save As Outlook Contact Attachments E-mail E-mail Address Web Page Web Page Employee Details Joe Close Employee Form Macros A macro is a series of statements that instructs an application how to complete a task. Macros allow users to automate routine, repetitive, or difficult tasks in application soft- ware such as word processing, spreadsheet, or database programs. That is, users can create simple programs within the software by writ- ing macros. You usually create a macro in one of two ways: (1) record the macro or (2) write the macro. If you want to automate a routine or repetitive task such as formatting or editing, you would record a macro. A macro recorder is similar to a movie camera because both record all actions until turned off. To record a macro, start the macro recorder in the software. Then, perform the steps to be part of the macro, such as clicks of the mouse or keystrokes. Once the macro is recorded, you can run it anytime you want to perform that same sequence of actions. For example, if you always print three copies of certain documents, you could record the actions required to print three copies. To print three copies, you would run the macro called PrintThreeCopies. When you become familiar with program- ming techniques, you can write your own macros instead of recording them. Many pro- grams use Visual Basic for Applications (VBA), which can work with Visual Studio Tools for Office, or a similar language as their macro Figure 13-15b (resulting filled-in form) Save and New Email Save As Qutlook Contact Close Notes Business Phone Business Phone Notes Home Phone Home Phone General Hours Mobile Phone Mobile Phone Fax Number Fax Number Address Street Address City State/Province Zip/Postal Code Country/Region City State/Province ZIP/Postal Code Country/Region First Name Last Name Company Job Title Phone Numbers Business Phone Home Phone Western Electronics Sales Representative Kara Bergner Figure 13-15 A form design and the resulting filled-in form created with Microsoft Access. E-mail [email protected] Web Page www.westermelectronics.com Notes Mobile Phone Fax Number 309-555-2020 309-555-1828 309-555-9998 309-555-9899 Hours: Monday-Friday: 8-6 Saturday: 9-5 Address Street 50 Spencer Boulevard City State/Province Zip/Postal Code Country/Region Highland IL 60604 USA Record: M 1 of 1 THE GF Search Programming Languages and Program Development Chapter 13 677 programming language. The macro in Figure 13-16a shows an Excel VBA macro that auto- mates the data entry process to determine the monthly payment, total interest, and total cost Figure 13-16a (VBA macro) Microsoft Visual Basic atoralum-Sheet Code El Edit View Desert Format Debug Bun Ieols Add-Ins Window Help of an auto loan. Figure 13-16b shows the dialog Macros box generated from the macro that prompts the user to enter the car model. Read Ethics & Issues 13-1 for a related discussion. For more information, visit scsite.com/dc2011/ch13/ weblink and then click Macros. Type a question for help KNIVE In 14 Cal Click CommandButton New Auto Loan button acco Dace Created: 12/16/2011 Pun front Functions Author: James Washington Loan Analysis sheet by clicking button labeled New Auto Loan Then executed, this macro accepts loan data which causes Excel to calculate a monthly payment and other loan information. Private Sub CommandButton1_Click() Figure 13-16b (macro dialog box in Excel window) Car Loan Calculator Microsoft Excell Range("C3:C8").Select Selection. Clear Contents Page Layout Formulas Dats Reitew View Range("C3").Value InputBox ("Car model?", "Enter") Car Price InputBox ("Price of car?", "Enter") Do While CarPrice 12000 or Car Price > 80000 Loop Range ("C4").Value CarPrice Record Macre Visual Magos Use Relative References Macre Security Car Price InputBox ("Price of car must be $12,000 and Code Insert Design Mode Controll Properties Qew Code un Dislog Source Developer Mas Properties Expansion Pads Refresh Data Add-Ind Import Export XML B16 Down Payment InputBox ("Down Payment 2", "Enter") Do While DownPayment <1500 Or DownPayment > 55000 Down Payment Input box | "Down payment must be > $1,500 a Loop 1 Range ("C5").Value DownPayment B C D My Loan Calculator Range ("C6").Value-price-down payment" Interest Rate Do While Interest Rate 0.03 Or Interest Rate > 0.22 Interest Rate InputBox ("Interat Rate must be 3 and Loop Range ("C7").Value Interest Rate Time in Tears InputBox ("Time in Years?", "Enter") Do While TimminTears <1 Or TineinTenge > 9 Time in Tears InputBox | "Time in years must be > 1 and 8 Loop Range ("C6").Value Time inYears InputBox("Interest Pate in 42", "Enter") 13 2345678 Date Car Model January-11 Lexus Enter Car model? Price $62,000.00 Down Payment $12,750.00 Loan Amount $49,250.00 Interest Rate Years 8.50% 6 g Monthly Payment $875.59 10 Total Interest $13,792.15 Range ("C13").Select End Sub 11 Total Cost $75,792.15 12 13 New Loan 14 15 Loan Analysis Sheet2 Sheet3 Ready✔ macro dialog box OK Cancel clicking New Loan button causes macro to run Figure 13-16 The left screen shows a VBA macro used to automate an auto loan. After a macro is written, the user clicks the New Loan button to run the macro. The right screen shows the macro guiding the user through part of the data entry process. ETHICS & ISSUES 13-1 Who Should Be Held Accountable for Macro Security Threats? Years ago, an individual downloaded and opened a small document that contained a virus from an Internet newsgroup. Upon opening the document, a macro was executed that sent the same document to the first 50 e-mail addresses in the person's e-mail contact list. The simple action of opening the document started a chain reaction that resulted in more than 100,000 infected computers and more than $80 million in damage. Today, such viruses, known as macro viruses, are the most common type of virus. Malware authors find that one of the easiest ways to spread viruses and worms is by dis- tributing documents containing macro viruses. The convenience and simplicity of macros are both their greatest strengths and weaknesses. These are weaknesses because hackers find it easy to exploit technologies with such traits. As a result of damaging macro viruses, antivirus companies and software com- panies have strengthened their efforts against macro viruses. Companies often prohibit employees from running macros on their computers. Both responses have made the use of macros more difficult and confusing for users, who prefer the convenience and simplicity of the earlier days. Many claim that software compa- nies that include the capability to use macros should be responsible for making it impossible for malware authors to take advantage of security problems in the software. Software companies and others blame users who open documents from unknown sources. Should users or software companies be held accountable for macro security threats? Why? Should a macro in a word processing document have the capability to access a person's e-mail contact list? Why or why not? How can users best be educated regarding handling documents from unknown sources? H Programming Languages and Program Development Chapter 13 language instruction in a low-level language usually equates to a single machine instruction, discussed further in the next section. With a high-level language, by contrast, each language instruction typically equates to multiple machine instructions. High-level languages often are machine independent. A machine-independent language can run on many different types of computers and operating systems. The following pages discuss low-level languages, as well as several types of high-level languages. Visual Basic Low-Level Languages Two types of low-level languages are machine languages and assembly languages. Machine language, known as the first generation of programming languages, is the only language the computer directly recognizes (Figure 13-2). Machine language instructions use a series of binary digits (1s and 0s) or a combination of numbers and letters that represents binary digits. The binary digits correspond to the on and off electrical states. As you might imagine, coding in machine language is tedious and time-consuming. With an assembly language, the second generation of programming languages, a pro- grammer writes instructions using symbolic PHP C# Ajax ToolBook XHTML XML COBOL ASP.NET Flash SQL C++ Perl Expression Web 0000DE 5A50 35AA 0000E2 47F0 2100 000102 1B77 015AC 00102 000104 5870 304E 01050 C Java F# 000108 1C47 00010A 4E50 30D6 010D8 00010E F075 30D6 003E 010D8 0003E 000114 4F50 30D6 010D8 PowerBuilder 000118 5050 3052 01054 000110 58E0 30B6 010B8 000120 07FE 00122 000122 50E0 30BA 010BC 000126 1B55 000128 5A50 304E 01050 00012C 5B50 3052 01054 000130 5050 305A 0105C 000134 58E0 30BA 010BC 000138 07 FE 665 Figure 13-2 A sample machine language program, coded using the hexadecimal number system. For information about hexadecimal, see Appendix C at the back of this book. 666 Chapter 13 Programming Languages and Program Development comments begin with an asterisk instruction codes (Figure 13-3). Symbolic instruction codes are meaningful abbreviations. With an assembly language, a programmer writes abbreviations such as A for addition, C for compare, L for load, and M for multiply. Assembly languages also use symbolic addresses. A symbolic address is a meaningful name that identifies a storage location. For example, a programmer can use the name RATE to refer to the storage location that contains a pay rate. Despite these advantages, assembly languages can be difficult to learn. In addition, program- mers must convert an assembly language program into machine language before the computer can execute, or run, the program. That is, the computer cannot execute the assembly source program. A source program is the program that contains the language instructions, or code, to be converted to machine language. To convert the assembly language source pro- gram into machine language, programmers use a program called an assembler. One assembly language instruction usually equates to one machine language instruction. In some cases, however, the assembly language includes macros. An assembly language macro generates many machine language instructions for a single assembly language instruction. Macros save the programmer time during program development. Today, assembly languages primarily are used to increase the performance of critical tasks or to control hardware. THIS MODULE CALCULATES THE REGULAR TIME PAY 14, SAVERTPY 14, SAVERTPY 14 THIS MODULE CALCULATES THE OVERTIME PAY 14, SAVEOTPY 5,OTPAY CALCSTPY EQU * ST SR 4,4 SR 7,7 SR 5,5 PACK DOUBLE, RTHRSIN CVB 4, DOUBLE PACK DOUBLE, RATEIN calculates regular time CVB 7, DOUBLE pay ST 7, RATE MR 4,7 ST 5, RTPAY L BR * CALCOTPY EQU ST TEST1 CLI CODEIN,C'O' BH TEST2 SR 5,5 A 5,=F'0' ST B AROUND TEST2 SR 4,4 SR 7,7 SR 5,5 PACK CVB PACK CVB 7, RATE MR 4,7 MR 4,-F'1.5' ST 5,OTPAY AROUND L 14, SAVEOTPY BR 14 * CALCGPAY EQU * ST 14, SAVEGPAY SR 5,5 A 5, RTPAY A 5,OTPAY ST 5, GRPAY L 14, SAVEGPAY BR 14 Figure 13-3 DOUBLE, OTHRSIN 4, DOUBLE DOUBLE, RATEIN evaluates overtime hours and calculates overtime pay THIS MODULE CALCULATES THE GROSS PAY calculates gross pay An excerpt from an assembly language payroll program. The code shows the computations for regular time pay, overtime pay, and gross pay and the decision to evaluate the overtime hours. Procedural Languages The disadvantages of machine and assembly (low-level) languages led to the development of procedural languages in the late 1950s and 1960s. In a procedural language, the program- mer writes instructions that tell the computer what to accomplish and how to do it. With a procedural language, often called a third-generation language (3GL), a pro- grammer uses a series of English-like words to write instructions. For example, ADD stands for addition or PRINT means to print. Many 3GLs also use arithmetic operators such as for multiplication and + for addition. These English-like words and arithmetic symbols simplify the program development process for the programmer. * As with an assembly language program, the 3GL code (instructions) is called the source program. Programmers must convert this source program into machine language before the com- puter can execute the program. This translation process often is very complex, because one 3GL source program instruction translates into many machine language instructions. For 3GLs, pro- grammers typically use either a compiler or an interpreter to perform the translation. A compiler is a separate program that con- verts the entire source program into machine language before executing it. The machine lan- guage version that results from compiling the 3GL is called the object code or object program. The compiler stores the object code on storage media for execution later. Programming Languages and Program Development Chapter 13 While it is compiling the source program into object code, the compiler checks the source program for errors. The compiler then produces a program listing that contains the source code and a list of any errors. This listing helps the programmer make necessary changes to the source code and correct errors in the program. Figure 13-4 shows the process of compiling a source program. A compiler translates an entire program before executing it. An interpreter, by contrast, translates and executes one statement at a time. An interpreter reads a code statement, converts it to one or more machine language instruc- tions, and then executes those machine language instructions. It does this all before moving to the next code statement in the program. Each time the source program runs, the interpreter trans- lates and executes it, statement by statement. An interpreter does not produce an object program. Figure 13-5 shows the process of interpreting a program. One advantage of an interpreter is that when it finds errors, it displays feedback immediately. The programmer can correct any errors before the interpreter translates the next line of code. The disadvantage is that interpreted programs do not run as fast as compiled programs. This is because an interpreter must translate the source program to machine language each time the program executes. Once a program is compiled, by contrast, users simply execute the object code to run the program. Many programming languages include both an interpreter and a compiler. In this case, the programmer can use the interpreter during program development. When the program is complete and error free, the programmer can compile the program so that it runs faster when it is placed into production for users to execute. Source Program Compiler Object Program Results Source Program Data Program Listing Data Interpreter 667 * COMPUTE REGULAR TIME PAY * * MULTIPLY REGULAR-TIME-HOURS BY HOURLY-PAY-RATE GIVING REGULAR-TIME-PAY. COMPUTE OVERTIME PAY IF OVERTIME-HOURS > 0 COMPUTE OVERTIME-PAY = OVERTIME-HOURS * 1.5 * HOURLY-PAY-RATE ELSE MOVE O TO OVERTIME-PAY. COMPUTE GROSS PAY ADD REGULAR-TIME-PAY TO OVERTIME-PAY GIVING GROSS-PAY. Figure 13-4 A compiler converts the source program into a machine language object program. If the compiler encounters any errors, it records them in the program-listing file, which the programmer may print when the entire compilation is complete. When a user wants to run the program, the object program is loaded into the memory of the computer and the program instructions begin executing. Results Figure 13-5 With an interpreter, one line of the source program at a time is converted into machine language and then immediately executed by the computer. If the interpreter encounters an error while converting a line of code, an error message immediately is displayed on the screen and the program stops. 668 Chapter 13 Programming Languages and Program Development C For more information, visit scsite.com/dc2011/ch13/ weblink and then click C. Hundreds of procedural languages exist. Only a few, however, are used widely enough for the industry to recognize them as standards. These include C and COBOL. To illustrate the simi- larities and differences among these program- ming languages, the following figures show program code in these languages. The code solves a simple payroll problem computing the gross pay for an employee. The used to compute gross pay can process vary from one system to another. The examples on the following pages use a simple algorithm, or set of steps, to help you easily compare one programming language with another. Read Innovative Computing 13-1 to find out about some useful and fun online programs. C The C programming language, developed in the early 1970s by Dennis Ritchie at Bell Laboratories, originally was designed for writ- ing system software. Today, many programs are written in C (Figure 13-6). This includes oper- ating systems and application software such as word processing and spreadsheet programs. C is a powerful language that requires profes- sional programming skills. Many programmers use C for business and scientific problems. C runs on almost any type of computer with any operating system, but it is used most often with the UNIX and Linux operating systems. ! INNOVATIVE COMPUTING 13-1 Online Calculators Answer Life's Questions At practically every phase of life, people can benefit from some sort of calcu- lator. For example, one program can help expectant parents calculate the date their child will be born and another can generate possible baby names. Once the child is born, they can use another calculator that attempts to estimate the total cost of raising the child through the teenage years. One Web site has collected a wide variety of calculators: Your Life, Calculated. This MSN-sponsored site organizes the calcula- tors in a variety of categories. The Career section includes a millionaire calculator to determine how much money will need to be saved each month to reach $1 million, and it also includes amortization tables and mortgage and car loan calculators. Other tools are the tip calculator, a calcu- lator that determines the chances of a suc- cessful personal relationship, the body mass index to measure body fat based on height and weight, the college cost calculator, and the financial aid calculator. When using online calculators, keep in mind that some are subjective in nature, and the results reflect the thoughts and/or opinions of the calculator's author. For more information, visit scsite.com/ dc2011/ch13/innovative and then click Online Calculators. comments begin with a slash followed by an asterisk * Compute Regular Time Pay, rt_pay rt_hrs pay_rate; /* Compute Overtime Pay if (ot_hrs > 0) calculates regular time pay evaluates overtime hours and calculates overtime pay ot_payot_hrs * 1.5 pay rate; else ot_pay = 0%; /* Compute Gross Pay gross = rt_payot_pay; calculates gross pay / Print Gross Pay printf("The gross pay is %d\n", gross); < */ prints gross pay Figure 13-6 An excerpt from a C payroll program. The code shows the computations for regular time pay, overtime pay, and gross pay; the decision to evaluate the overtime hours; and the output of the gross pay. COBOL COBOL (COmmon Business-Oriented Language) evolved out of a joint effort between the United States government, businesses, and major universities in the early 1960s (Figure 13-7). Naval officer Grace Hopper, a pioneer in computer programming, was a prime developer of COBOL. COBOL is a programming language designed for business applications. Although COBOL programs often are lengthy, their English-like statements make the code easy to read, write, and maintain. COBOL espe- cially is useful for processing transactions, such as payroll and billing, on mainframe computers. COBOL programs also run on other types of computers. comments begin with an asterisk Programming Languages and Program Development Chapter 13 669 COMPUTE REGULAR TIME PAY MULTIPLY REGULAR-TIME-HOURS BY HOURLY PAY-RATE GIVING REGULAR-TIME-PAY. * COMPUTE OVERTIME PAY IF OVERTIME-HOURS > O calculates regular time pay * ELSE COMPUTE OVERTIME-PAY = OVERTIME-HOURS * 1.5 * HOURLY-PAY-RATE MOVE O TO OVERTIME-PAY. COMPUTE GROSS PAY ADD REGULAR-TIME-PAY TO OVERTIME-PAY calculates gross pay evaluates overtime hours and calculates overtime pay GIVING GROSS-PAY. * PRINT GROSS PAY MOVE GROSS-PAY TO GROSS-PAY-OUT. WRITE REPORT-LINE-OUT FROM DETAIL-LINE K prints gross pay AFTER ADVANCING 2 LINES. Figure 13-7 An excerpt from a COBOL payroll program. The code shows the computations for regular time pay, overtime pay, and gross pay; the decision to evaluate the overtime hours; and the output of the gross pay. Object-Oriented Programming Languages and Program Development Tools Computer programmers use an object-oriented programming (OOP) language or object- oriented program development tool to imple- ment an object-oriented design. Recall from Chapter 12 that an object is an item that can con- tain both data and the procedures that read or manipulate that data. An object represents a real person, place, event, or transaction. A major benefit of OOP is the ability to reuse and modify existing objects. For example, once a programmer creates an Employee object, it is available for use by any other existing or future program. Thus, programmers repeatedly reuse existing objects. For example, the payroll pro- gram and health benefits program both use the Employee object. That is, the payroll program would use it to process employee paychecks and the health benefits program would use it to process health insurance payments. Programs developed using the object-oriented approach have several advantages. The objects can be reused in many systems, are designed for repeated use, and become stable over time. In addition, programmers create applications faster because they design programs using existing objects. In addition to being able to work with objects, an OOP language is event driven. An event is an action to which the program responds. Examples of events include pressing a key on the keyboard, typing a value in a text box, moving the mouse, clicking a button, or speaking an instruction. An event-driven program checks for and responds to events. Some programming languages are event driven but are not complete OOP languages. Other programming languages, such as Java, C#, F#, C++, and the latest versions of Visual Basic, are complete object-oriented languages. Object-oriented programming languages and program development tools work well in a RAD environment. RAD (rapid application development) is a method of developing software, in which a programmer writes and implements a program in segments instead of waiting until the entire program is completed. Users begin working with sections of the program as they are completed. An important concept in RAD is the use of pre- built components. For example, programmers do not have to write code for buttons and text boxes on Windows forms because they already exist in the programming language or tools provided with the language. Most object-oriented program development tools are IDEs. An IDE (integrated development environment) includes tools for building graphi- cal user interfaces, an editor for entering pro- gram code, a compiler and/or interpreter, and a 670 Chapter 13 Programming Languages and Program Development Java Platforms For more information, visit scsite.com/dc2011/ch13/ weblink and then click Java Platforms. debugger (to remove errors, which is discussed later in the chapter). Some IDEs work with a single programming language; others, such as Eclipse support multiple languages. Eclipse is an open source, advanced development environment that works with a variety of programs including Java and C++, which are discussed next. The following sections discuss a variety of object-oriented programming languages and program development tools. Java Java is an object-oriented programming language developed by Sun Microsystems. Figure 13-8 shows a portion of a Java program and the window that the program displays. When programmers compile a Java program, the resulting object code typically is called bytecode, which is machine independent. Java then uses a just-in-time (JIT) compiler to convert the bytecode into machine-dependent code that is executed immediately. Programmers use Java Platform, Standard Edition (Java SE), developed by Sun Microsystems, to create stand-alone programs for desktop computers and servers. Similarly, programmers use Java Platform, Micro Edition (Java ME) to create programs for smart phones and other mobile devices. Java EE (Java Platform, Enterprise Edition) is a set of technologies built on Sun's Java SE that allows programmers to develop and deploy large applications for organizations, often used in Web 2.0 environments for Web applications. The goal of Java EE is to simplify and reduce program development time by developing standard, reusable objects. .NET The Microsoft .NET Framework, or .NET (pronounced dot net), is a set of technologies that allows almost any type of program to run on the Internet or an internal business network, as well as stand-alone computers and mobile devices. Similarly, ASP.NET is a Web application framework that provides the tools necessary for the creation of dynamic Web sites. Features of .NET include the CLR and classes. The CLR (Common Language Runtime) is an environment that enables programmers to develop .NET programs using a variety of languages. A .NET-compatible language com- piles the program source code into Microsoft Intermediate Language (MSIL). The CLR then converts the MSIL into object code using a just- in-time compiler. The CLR supports classes so that .NET programmers can access a variety of common functions in their programs, which saves development time. Using .NET and/or ASP.NET, programmers easily can develop Web applications, Web services, and Windows programs. Examples of languages that support .NET include C++, C#, F#, Visual Basic, Image logo; //declare an Image object int inches, pounds; public class Body MassApplet extends Applet implements ActionListener //declare variables double meters, kilograms, index; //construct components Button calcButton = new Button("Calculate"); Label weightLabel new Label ("Enter your weight to the nearest pound TextField weightField = new TextField(10); Label companyLabel = new Label("THE SUN FITNESS CENTER BODY MASS INDEX CALCULATOR"); Label heightLabel = new Label("Enter your height to the nearest inch TextField heightField = new TextField(10); "); "); } } Label outputLabel = new Label( "Click the Calculate button to see your Body Mass Index. "); } inches = Integer.parseInt(heightField.getText()); pounds = Integer.parseInt(weightField.getText()); meters inches 39.36; kilograms = pounds / 2.2; index = kilograms/Math.pow(meters, 2); outputLabel.setText("YOUR BODY MASS INDEX IS " + Math.round(index) + "."); public void paint (Graphics g) g.drawImage(logo, 125, 160, this); Applet THE SUN FITNESS CENTER BODY MASS INDEX CALCULATOR Enter your height to the nearest inch Enter your weight to the nearest pound 67 145 Calculate YOUR BODY MASS INDEX IS 23. Figure 13-8 A portion of a Java program and the window the program displays. Applet started. Programming Languages and Program Development Chapter 13 671 Delphi, and PowerBuilder. The following sections discuss each of these languages. C++ Developed in the 1980s by Bjarne Sroustrup at Bell Laboratories, C++ (pronounced SEE-plus-plus) is an object- oriented programming language that is an extension of the C programming language. C++ includes all the elements of the C lan- guage, plus it has additional features for working with objects, classes, events, and other object-oriented concepts (Figure 13-9). Programmers commonly use C++ to develop database and Web applications. Much application software, such as word processing and spreadsheet programs, also is written in C++. A programmer does not need C programming experience to be a successful C++ programmer. C# C# (pronounced SEE-sharp) is an object-oriented programming language based on C++ that was developed primarily by Anders Hejlsberg, Microsoft chief archi- tect and distinguished engineer. C# has been accepted as a standard for Web appli- cations and XML-based Web services. Recall from Chapter 9 that Web services describe standardized software that enables program- mers to create applications that communicate with other remote computers over the Internet or on an internal business network. Like Java, C# uses a JIT compiler but its resulting code is MSIL. C# applications can be built on existing C or C++ applications, saving development time for companies migrating from C or C++. F# F# (pronounced EFF-sharp), which is included with the latest version of Visual Studio (discussed in the next section), is a programming language that combines the benefits of an object-oriented language with the benefits of a functional language. A functional language is a programming language whose natural programming structure is useful in mathematical programs. Benefits of programs written in F# include easy access to .NET libraries and performance similar to that of C# programs. // portion of a C++ program that allows users to create // a new zip code from a string or a number and expand // zip codes, as appropriate, to a 10-digit number ZipC::ZipC( const unsigned long zipnum ) } ostringstream strInt; strInt << zipnum; code = strInt.str(); const string ZipC::getCode() { return code; } void ZipC::setCode(const string newCode) { code newCode; } void ZipC::expand) const string suffix ) { if(code.length() } } == == 5 && 4) // small size? // length ok? suffix.length() code = "" ; code.append(suffix); Figure 13-9 Sample C++ program. Visual Studio Visual Studio is Microsoft's suite of program development tools that assists pro- grammers in building programs for Windows, Windows Mobile, or operating systems that support .NET. Visual Studio includes enhanced support for building security and reliability into applications through its programming languages, RAD tools, IDE, a specialized query language called LINQ (Language Integrated Query), and other resources that reduce development time. For example, Visual Studio includes code snippets, which are prewritten code and templates associated with common programming tasks. Visual Studio Tools for Office (VSTO) is a set of tools integrated in Visual Studio that enables developers to create programs that work with Microsoft's Office suite, including Word, Excel, PowerPoint, Outlook, and Project. The next sections discuss the programming languages in the Visual Studio suite. Visual Studio Tools for Office For more information, visit scsite.com/dc2011/ch13/ weblink and then click Visual Studio Tools for Office. 672 Chapter 13 Programming Languages and Program Development • Visual Basic is a programming language that allows programmers easily to build complex task-oriented object-based programs. Visual Basic is based on the BASIC programming language, which was developed by Microsoft Corporation in the early 1990s. This language is easy to learn and use. Thus, Visual Basic is ideal for beginning programmers. The first step in building a Visual Basic program often is to design the graphical user interface using Visual Basic objects (Steps 1 and 2 in Figure 13-10). Visual Basic objects include items such as buttons, text boxes, and labels. Next, the programmer writes Creating a Visual Basic Program Step 1 The developer designs the user interface, such as for the mobile device shown here. Linear Feet is a text box in which the user enters data. Pine, Oak, and Cherry are option buttons the user can click to choose the wood type. Calculate and Clear are buttons. All other objects are labels. File Edit Toolbox instructions to define any actions that should occur in response to specific events (Step 3 in Figure 13-10). Finally, the programmer generates and tests the final program (Step 4 in Figure 13-10). To learn more about how to design a user interface, complete the Learn How To 1 activity on pages 708 and 709. An event in Visual Basic might be the result of an action that a user initiates. For example, when a user clicks a button in a Visual Basic program, the program executes the Click event. Programmers create events in Visual Basic by writing instructions (code) with its built-in programming language. View Project Build Debug Data Format Tools Test Window Step 2 The developer assigns properties to each object. Objects include text boxes, option buttons, buttons, labels, and the form itself. Properties radPine System.Windows.Forms.f All Device Controls Common Device Con... Pointer ab Button CheckBox ComboBox A Label A LinkLabel frm WoodCabinetEstimate.vb [Design]' дх DateTimePicker DocumentList labels Linear Feet? (Name) Anchor radPine Top, Left Wood Type: Pine text box BackColor Checked LightGray True ContextMenu (none) Oak O Cherry Dock Enabled None True Cost Estimate: 0000.00 Font ForeColor Tahoma, 12pt ControlTex- ListBox 2 ListView MonthCalendar NumericUpDown option buttons PictureBox ProgressBar label Ô RadioButton ++ Splitter button Calculate Clear Step 4 The developer tests the program. The Cost Estimate is displayed after the user clicks the Calculate button. Figure 13-10 abl TextBox 0-TrackBar T 15 16 17 18 10 Linear Feet? 12 19 13 Step 3 The developer writes code to define the action of each event the user triggers. 14 Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnCalculate. Click The btnCalculate event handler calculates the estimated cost of cabinets based on the linear feet and the wood type. 'Declaration Section Dim decLinearFeet As Decimal 20 21 Wood Type: O Pine 22 Dim decCost Per Foot As Decimal Dim decCost Estimate As Decimal Dim decPineCost As Decimal = 100D Dim decOak Cost As Decimal = 150D 24 Dim decCherryCost As Decimal = 250D 25 26 O Oak Cherry Cost Estimate: $3,000.00 Calculate Clear 27 28 29 30 20 31 21 32 32 33 33 34 34 Did user enter a numeric value? If IsNumeric (Me.txt Linear Feet. Text) Then decLinearFeet = Convert.ToDecimal (Me.txtLinearFeet. Text) Is Linear Feet greater than zero If decLinearFeet > 0 Then 55 35 36 37 38 39 40 41 42 43 Else 44 'Determine cost per foot of wood If Me.radPine. Checked Then decCost PerFoot = decPineCost ElseIf Me.radoak. Checked Then decCost PerFoot decOak Cost ElseIf Me.radCherry. Checked Then decCost Per Foot = decCherryCost End If Calculate and display the cost estimate decCost Estimate = decLinearFeet * decCost PerFoot Me.lbl Cost Estimate.Text = decCost Estimate.ToString("C") *-* error message if 110-- value This figure shows how to create a Visual Basic program.