How to learn C++ programming for Beginners

how to program c++ loop and how to compile c++ program from command prompt and how to run c++ program from terminal and how to understand c++ programming language
Dr.NaveenBansal Profile Pic
Dr.NaveenBansal,India,Teacher
Published Date:25-10-2017
Your Website URL(Optional)
Comment
CHAPTER 1 Writing an ANSI C++ Program This chapter introduces the reader to the ANSI C++ programming world. Some gen- eral ideas on programming are discussed, and a number of elementary programs are thoroughly explained. The basic ideas presented here become the foundation for more complete explanations that occur in later chapters. An emphasis is placed on the basic input/output functions of C++. Getting information into and out of a machine is the first task to be mastered in any programming language. C++ uses the operators and for output and input, respectively. The use of both of these operators is explained. Other topics discussed in this chapter include the use of variables to store values and the use of expressions and assignments to change the value of a variable. Throughout this chapter and throughout the text, many examples are given. Included are many complete programs, which often are dissected. This allows the reader to see in detail how each construct works. Topics that are introduced in this chapter are seen again in later chapters, with more detailed explanation where appropriate. This spiral approach to learning emphasizes ideas and techniques essential for the C++ program- mer. C++ is largely a superset of C. By learning C++, you are also learning the kernel language C. A companion book, C by Dissection: Fourth Edition, by Al Kelley and Ira Pohl (Addison-Wesley, 2000), teaches the rest of C that is not found here. Most chapters also have a comparison between C++ and Java programs. Java is partly based on C++. However, unlike C++, some C concepts do not work in Java or have a dif- ferent meaning. Increasingly, people who begin to program in C++ have started from a Java background. An introduction to the Java programming process can be found in the companion volume Java by Dissection, by Ira Pohl and Charlie McDowell (Addison- Wesley, 1999). The modern programmer needs to be comfortable in all three C-based languages.Ira Pohl’s C++ by Dissection 1.1 Getting Ready to Program 2 1.1 1.1 Getting Ready to Program Programs are written to instruct machines to carry out specific tasks or to solve specific problems. A step-by-step procedure that accomplishes a desired task is called an algo- rithm. Thus, programming is the activity of communicating algorithms to computers. We have all given instructions to someone in English and then had that person carry out the instructions. The programming process is analogous, except that machines have no tolerance for ambiguity and must have all steps specified in a precise language and in tedious detail. The Programming Process 1. Specify the task. 2. Discover an algorithm for its solution. 3. Code the algorithm in C++. 4. Test the code. A computer is a digital electronic machine composed of three main components: pro- cessor, memory, and input/output devices. The processor is also called the central pro- cessing unit, or CPU. The processor carries out instructions that are stored in the memory. Along with the instructions, data also is stored in memory. The processor typ- ically is instructed to manipulate the data in some desired fashion. Input/output devices take information from agents external to the machine and provide information to those agents. Input devices are typically terminal keyboards, disk drives, and tape drives. Output devices are typically terminal screens, printers, disk drives, and tape drives. The physical makeup of a machine can be quite complicated, but the user need not be concerned with the details. The operating system consists of a collection of special programs and has two main pur- poses. First, the operating system oversees and coordinates the resources of the machine as a whole. For example, when a file is created on a disk, the operating system takes care of the details of locating it in an appropriate place and keeping track of its name, size, and date of creation. Second, the operating system provides tools to users, many of which are useful to the C++ programmer. Two of these tools are of paramount importance: the text editor and the C++ compiler. We assume the reader can use a text editor to create and modify files containing C++ code. C++ code is also called source code, and a file containing source code is called a ‘source file. After a file containing source code (a program) has been created, the C++ compiler is invoked. This process is system-dependent. (Section 1.6, Writing and Run- ning a C++ Program, on page 14.) For example, on many UNIX systems, we can invoke the C++ compiler with the command CC pgm.cpp where pgm.cpp is the name of a file that contains a program. If there are no errors in pgm.cpp, this command produces an executable file—one that can be run, or executed. Although we think of this as compiling the program, what actually happens is more complicated.Ira Pohl’s C++ by Dissection 1.1 A First Program 3 When we compile a simple program, three separate actions occur: First the preproces- sor is invoked, then the compiler, and finally the linker. The preprocessor modifies a copy of the source code by including other files and by making other changes. The com- piler translates this into object code, which the linker then uses to produce the final exe- cutable file. A file that contains object code is called an object file. Object files, unlike source files, usually are not read by humans. When we speak of compiling a program, we really mean invoking the preprocessor, the compiler, and the linker. For a simple program, this is all done with a single command. After the programmer writes a program, it has to be compiled and tested. If modifica- tions are needed, the source code has to be edited again. Thus, part of the programming process consists of this cycle: edit compile execute When the programmer is satisfied with the program performance, the cycle ends. 1.1 1.1 A First Program A first task for anyone learning to program is to print on the screen. Let us begin by writing the traditional first C++ program which prints the phrase Hello, world on the screen. The complete program is In file hello1.cpp // Hello world in C++ // by Olivia Programmer include iostream // I/O library using namespace std; int main() cout "Hello, world" endl; Using the text editor, the programmer types this code into a file ending in .cpp. The choice of a file name should be mnemonic. Let us suppose hello.cpp is the name of the file in which the program has been written. When this program is compiled and exe- cuted, it prints the following message: Hello, worldIra Pohl’s C++ by Dissection 1.1 A First Program 4 cout “Hello, world” Hey, Heidi, Alpha Centauri says ‘Hello’ and it’s in C++ Dissection of the hello Program // Hello world in C++ // by Olivia Programmer The // symbol is used as a rest-of-line comment symbol. Also, the program text can be placed in any position on the page, with white space between tokens being ignored. White space are characters such as blanks, tabs, and new lines. White space, comments, and indenta- tion of text are all used to create a well-documented, readable pro- gram but do not affect program semantics. include iostream // I/O library The C++ program is compiled after the preprocessor executes -des- ignated directives. The preprocessor precedes the compiler transla- tion of the resulting program into machine code. The include directive found in the example program hello.cpp imports any needed files, usually library definitions. In this case, the I/O library for a typi- cal C++ compiler system is found in the file iostream. The compiler knows where to find this and other system files. using namespace std; On C++ systems, standard C++ I/O header files are wrapped in namespace std. The using declaration allows names to be used without std:: prepended to each name. The include files could have been coded without namespace and using, as follows: include iostream.h // I/O library Most systems provide older style library_name.h header files. These libraries do not require the using namespace std; statement. Ira Pohl’s C++ by Dissection 1.1 A First Program 5 int main() A C++ program is a collection of declarations and functions that begins executing with the function main(). cout "Hello, world" endl; The identifier cout is defined in iostream as the standard output stream con- nected by most C++ systems to the screen. The identifier endl is a standard manipulator that flushes the output buffer, printing everything to that point and going to a new line. The operator is the put-to output operator, which writes out what comes after it to cout. Note that without the using std statement, we could have written std::cout "Hello, world" std::endl; The :: operator is called the scope resolution operator. It tells the compiler what scope to examine to understand identifier cout. The scope of an identifier is the program text where the name may be used. This ends the function main(). In C++, braces are paired, an open brace can be understood as a begin construct and a closing brace means end construct. A function in C++ has a return type that can be void, indicating that no value is to be returned. The special function main() returns an integer value to the runtime system. Implicitly the function main() returns 0, meaning that termination was normal. This could have been written explicitly, return 0; just before the closing brace. The expression cout some string is used to print across the screen. It moves to a new line when a newline character is read or it sees the endl. The screen is a two- dimensional display that prints from left to right and top to bottom. To be readable, output must appear properly spaced on the screen. Let us rewrite our program to make use of two cout statements. Although the program is different from our first one, its output is the same.Ira Pohl’s C++ by Dissection 1.1 A First Program 6 In file hello2.cpp // Hello world in C++ // by Olivia Programmer // Version 2 include iostream // I/O library using namespace std; int main() cout "Hello, "; cout "world" endl; Notice that the string in the first statement ends with a blank character. If the blank were not there, the words Hello, world would have no space between them in the output. As a final variation to this program, let us add the phrase Hello, universe and print the statements on two lines: In file hello3.cpp // Hello universe in C++ // by Olivia Programmer include iostream // I/O library using namespace std; int main() cout "Hello, world" endl; cout "Hello, universe" endl; When we execute this program, the following appears on the screen: Hello, world Hello, universe Notice that the two cout statements in the body of main() could be replaced by the sin- gle statement cout "Hello, world\nHello, universe" endl; In this version, the special character \n is the newline character. This has the same effect as an endl.Ira Pohl’s C++ by Dissection 1.2 Problem Solving: Recipes 7 1.2 1.2 Problem Solving: Recipes Computer programs are detailed lists of instructions for performing a specific task or solving a particular type of problem. Instruction lists, called algorithms, are commonly found in everyday situations. Examples include instructions for cooking a meal, knitting a sweater, and registering for classes. Examining one of these examples is instructive. Consider this recipe for preparing a meat roast. Sprinkle the roast with salt and pepper. Insert a meat thermometer and place in oven preheated to 150ºC. Cook until the thermometer registers between 80ºC and 85ºC. Serve roast with gravy prepared from either meat stock or from pan drippings, if there is a suffi- cient amount. The recipe is typically imprecise—what does sprinkle mean, where exactly is the ther- mometer to be inserted, and what is a sufficient amount of pan drippings? However, the recipe can be formulated more precisely as a list of instructions by reading between the lines. Cooking a Roast 1. Sprinkle roast with 1/8 teaspoon salt and pepper. 2. Turn oven on to 150ºC. 3. Insert meat thermometer into center of roast. 4. Wait a few minutes. 5. If oven does not yet register 150ºC, go back to step 4. 6. Place roast in oven. 7. Wait a few minutes. 8. Check meat thermometer. If temperature is less than 80ºC, go back to step 7. 9. Remove roast from oven. 10. If there is at least 1/2 cup of pan drippings, go to step 12. 11. Prepare gravy from meat stock and go to step 13. 12. Prepare gravy from pan drippings. 13. Serve roast with gravy. These steps comprise three categories of instructions and activities—those that involve manipulating or changing the ingredients or equipment, those that just examine or test the state of the system, and those that transfer to the next step. Steps 1 and 6 are exam- ples of the first category; the temperature test in step 8 and the pan drippings test inIra Pohl’s C++ by Dissection 1.2 Problem Solving: Recipes 8 step 10 are instances of the second category; and transfers in steps 5 and 8 (go to step x) are examples of the last category. By using suitable graphical symbols for each of these categories, a simple two-dimen- sional representation of our cooking algorithm can be obtained, as shown in the follow- ing illustration: Place roast Sprinkle roast in oven Yes 1/2 cup drippings Wait a few Set oven to 150º minutes No Insert thermometer Prepare gravy Roast at 80º from stock No Wait a few minutes Prepare gravy Yes from drippings Oven at Remove roast Yes No 150º Serve roast Such a figure is called a flowchart. To perform the program (prepare the roast), just fol- low the arrows and the instructions in each box. The manipulation activities are con- tained in rectangles, the tests are shown in diamonds, and the transfer or flow of control is determined by the arrows. Because of their visual appeal and clarity, flow- charts are often used instead of lists of instructions for informally describing pro- grams. Some cookbook authors even employ flowcharts extensively. 1.2.1 Algorithms—Being Precise Our recipe for preparing a roast can’t be executed by a computer because the individual instructions are too loosely specified. Let’s consider another example—one that manip- ulates numbers instead of food. You need to pay for some purchase with a dollar bill and get change in dimes and pennies. The problem is to determine the correct change with the fewest pennies. Most people do this simple, everyday transaction unthinkingly. But how do we precisely describe this algorithm? In solving such a problem, trying a specific case can be useful. Let’s say that you need to pay 77 cents and need change for a dollar. You can easily see that one dollar minus the 77 cents leaves you with 23 cents in change. The correct change having the fewest coins in dimes and pennies would be two dimes and three pennies. The number of dimes is the integer result of dividing 23 by 10 and discarding any fraction or remainder. The number of pennies is the remainder of dividing the 23 cents by 10. An algorithm for performing this change for a dollar is given by the following steps.Ira Pohl’s C++ by Dissection 1.2 Problem Solving: Recipes 9 Change-Making Algorithm 1. Assume that the price is written in a box labeled price. 2. Subtract the value of price from 100 and place it in a box labeled change. 3. Divide the value in change by 10, discard the remainder, and place the result in a box labeled dimes. 4. Take the integer remainder of change divided by 10 and place it in a box labeled pennies. 5. Print out the values in the boxes dimes and pennies with appropriate labels. 6. Halt. This algorithm has four boxes, namely, price, change, dimes, and pennies. Let’s exe- cute this algorithm with the values given. Suppose that the price is 77 cents. Always start with the first instruction. The contents of the four boxes at various stages of exe- cution are shown in Table 1.1. Table 1.1 Making Change Box Step 1 Step 2 Step 3 Step 4 Step 5 price 77 77 77 77 77 change 23 23 23 23 dimes 2 2 2 pennies 3 3 To execute step 1, place the first number, 77, in the box price. At the end of instruc- tion 2, the result of subtracting 77 from 100 is 23, which is placed in the box change. Each step of the algorithm performs a small part of the computation. By step 5, the cor- rect values are in their respective boxes and are printed out. Study the example until you’re convinced that this algorithm works correctly for any price under one dollar. A good way to do so is to act the part of a computer following the recipe. Following a set of instructions in this way, formulated as a computer program, is called hand simula- tion or bench testing. It is a good way to find errors in an algorithm or program. In com- puter parlance, these errors are called bugs, and finding and removing them is called debugging. We executed the change-making algorithm by acting as an agent, mechanically following a list of instructions. The execution of a set of instructions by an agent is called a com- putation. Usually, the agent is a computer; in that case, the set of instructions is a com- puter program. In the remainder of this book, unless explicitly stated otherwise, we use program to mean computer program. The algorithm for making change has several important features that are characteristic of all algorithms.Ira Pohl’s C++ by Dissection 1.3 Implementing Our Algorithm in C++ 10 Algorithms The sequence of instructions will terminate. The instructions are precise. Each instruction is unambiguous and subject to only one interpretation. The instructions are simple to perform. Each instruction is within the capabil- ities of the executing agent and can be carried out exactly in a finite amount of time; such instructions are called effective. There are inputs and outputs. An algorithm has one or more outputs (answers) that depend on the particular input data. Our description of the change-making algorithm, although relatively precise, is not writ- ten in any formal programming language. Such informal notations for algorithms are called pseudocode, whereas real code is something suitable for a computer. Where appropriate, we use pseudocode to explain an algorithm or computation to you without all the necessary detail needed by a computer. The term algorithm has a long, involved history, originally stemming from the name of a well-known Arabic mathematician of the ninth century, Abu Jafar Muhammed Musa al-Khwarizim. It later became associated with arithmetic processes and then, more par- ticularly, with Euclid’s algorithm for computing the greatest common divisor of two integers. Since the development of computers, the word has taken on a more precise meaning that defines a real or abstract computer as the ultimate executing agent—any terminating computation by a computer is an algorithm, and any algorithm can be pro- grammed for a computer. 1.3 1.3 Implementing Our Algorithm in C++ In this section, we implement our change-making algorithm in the C++ programming language. You need not worry about following the C++ details at this point; we cover all of them fully in the next two chapters. For now, simply note the similarity between the following C++ program and the informal algorithm presented earlier. You not only have to be able to formulate a recipe and make it algorithmic, but you also have to express it in code. Ira Pohl’s C++ by Dissection 1.3 Implementing Our Algorithm in C++ 11 In file change.cpp // Change in dimes and pennies include iostream using namespace std; int main () int price, change, dimes, pennies; cout "Enter price (0:100): "; cin price; change = 100 - price; // how much change dimes = change / 10; // number of dimes pennies = change % 10; // number of pennies cout "\n\nThe change is :" dimes " dimes "; cout pennies " pennies." endl; Dissection of the MakeChange Program int price, change, dimes, pennies; This program declares four integer variables. These hold the values to be manipulated. cout "Enter price (0:100): "; This line is used to prompt you to type the price. Whenever a pro- gram is expecting a user to do something, it should print out a prompt telling the user what to do. The part in quotes appears on the user’s screen when the program is run. cin price; This statement obtains the input typed in from the keyboard. The value read is stored in the variable price. The symbol is called the insertion operator. At this point, you must type in an integer price. For example, you would type 77 and then hit Enter. change = 100 - price; // how much change This computes the amount of change from one dollar.Ira Pohl’s C++ by Dissection 1.4 Software Engineering: Style 12 dimes = change / 10; // number of dimes pennies = change % 10; // number of pennies The number of dimes is the integer or whole part of the result of dividing change by 10. The symbol /, when used with two integers, computes the integer part of the division. The number of pennies is the integer remainder of change divided by 10. The symbol % is the integer remainder, or modulo operator. So if change is 23, the integer divide of 23/10 is 2 and the integer remainder, or modulo, of 23 % 10 is 3. cout "\n\nThe change is :" dimes " dimes "; cout pennies " pennies." endl; The quoted string prints out the characters between the quotation marks. This includes two newlines advancing the cursor down the screen. Then the value in dimes is printed followed by the string " dimes ". Finally, the value of pennies is printed. For an input value of 77, the output would be The change is : 2 dimes 3 pennies The endl in the last print statement indicates that a newline should be sent to the console, ending the line of output. 1.4 1.4 Software Engineering: Style A good coding style is essential to the art of programming. It facilitates the reading, writing, and maintenance of programs. A good style uses white space and comments so that the code is easier to read and understand, and is visually attractive. Another impor- tant stylistic point is to choose names for variables that convey their use in the program to further aid understanding. A good style avoids error-prone coding habits. Software needs to be maintained. Frequently, maintenance costs are higher than the cost of initially writing the code. Good programming style is part of good documenta- tion, and programs need to be readable. This includes commenting the code, choice of identifiers, and associated documentation, such as a manual page or online help. In this text, we are following the Bell Laboratories industrial programming style. We place all includes, int main()s, and braces and that begin and end the body of main() in the leftmost position on the line: include iostream int main() ····· Ira Pohl’s C++ by Dissection 1.5 Common Programming Errors 13 The declarations and statements in the body of main() are indented three spaces. This visually highlights the beginning and ending of the function body. There is one blank line following the includes, and one between the declarations and statements in the body of main(). An indentation of two, three, four, five, or eight spaces is common. We use three spaces. Whatever is chosen as an indentation should be used consistently. To heighten readabil- ity, we put a blank space on each side of the binary operators. Some programmers do not bother with this, but it is part of the Bell Labs style. There is no single agreed-upon good style. As we proceed through this text, we often point out alternate styles. Once you choose a style, use it consistently. Good habits rein- force good programming. Caution: Beginning programmers sometimes think they should dream up their own distinctive coding style. This should be avoided. The pre- ferred strategy is to choose a style that is already in common use. 1.5 1.5 Common Programming Errors When you first start programming, you make many frustrating, simple errors. One such error is to leave off a closing double quote character to mark the end of a string. When the compiler sees the first ", it starts collecting all the characters that follow as a string. If the closing " is not present, the string continues to the next line, causing the compiler to complain. Error messages vary from one compiler to another. Here is one possibility: Unterminated string or character constant Another common error is to misspell a variable name or forget to declare it. Compilers readily catch this kind of error and properly inform you of what is wrong. However, if you misspell the name of a function, such as sqr() instead of sqrt(), the compiler informs you that the function cannot be found. If you do not notice that the error mes- sage refers to sqr instead of sqrt, you may be quite mystified. Even elementary errors, such as forgetting to place a semicolon at the end of a state- ment or leaving off a closing brace, can result in rather mystifying error messages from compilers. As you become more experienced, some of the error messages produced by your compiler will begin to make sense. Exercise 4 on page 23 suggests some program- ming errors you may want to introduce on purpose to experiment with the error mes- sage capability of your compiler.Ira Pohl’s C++ by Dissection 1.6 Writing and Running a C++ Program 14 1.6 1.6 Writing and Running a C++ Program The precise steps you have to follow to create a file containing C++ code and to compile and execute it depend on three things: the operating system, the text editor, and the compiler. However, in all cases, the general procedure is the same. We first describe in some detail how it is done in a UNIX environment. Then we discuss how it is done in a Windows environment. In the discussion that follows, we use the CC command to invoke the C++ compiler. In reality, however, the command depends on the compiler that is being used. For exam- ple, if we were using the command line version of the Borland C++ compiler, we would use the command bcc or bcc32. Steps for Writing and Running a C++ Program 1. Using an editor, create a text file—say pgm.cpp—that contains a C++ pro- gram. The name of the file ends with .cpp, indicating that the file contains C++ source code. To use an editor, the programmer must know the appropri- ate commands for inserting and modifying text. For example, to use the vi editor on a UNIX system, we would give the command vi pgm.cpp 2. Compile the program. This can be done with the command CC pgm.cpp The CC command invokes the preprocessor, the compiler, and the linker in turn. The pre- processor modifies a copy of the source code according to the preprocessing directives and produces what is called a translation unit. The compiler translates the translation unit into object code. If there are errors, the programmer must start again at step 1, edit- ing the source file. Errors that occur at this stage are called syntax errors or compile-time errors. If there are no errors, the linker uses the object code produced by the compiler, along with object code obtained from various libraries provided by the system, to create the executable file a.out. The program is now ready to be executed. 3. Execute the program. This is done with the command a.out Typically, the program completes execution, and a system prompt reappears on the screen. Any errors that occur during execution are called runtime errors. If, for some rea- son, the program needs to be changed, the programmer must start again at step 1. If we compile a different program, the file a.out is overwritten and its contents lost. If the executable file a.out is to be saved, the file must be moved or renamed. Suppose we give the command CC hello.cpp This causes executable code to be written automatically into a.out. To save this file, we can give the command mv a.out helloIra Pohl’s C++ by Dissection 1.6 Writing and Running a C++ Program 15 This moves a.out to hello. Now the program can be executed with the command hello In UNIX, it is common practice to give the executable file the same name as the corre- sponding source file, except to drop the .cpp suffix. If we wish, we can use the -o option to direct the output of the CC command. For example, the command CC –o hello hello.cpp causes the executable output from CC to be written directly into hello, leaving intact whatever is in a.out. Different kinds of errors can occur in a program. Syntax errors are caught by the com- piler, whereas runtime errors manifest themselves only during program execution. For example, if an attempt to divide by zero is encoded into a program, a runtime error may occur when the program is executed. Let us now consider the Windows environment. Here, some other text editor would most likely be used. Some C++ systems, such as Borland C++, have both a command line environment and an integrated environment. The integrated environment includes both the text editor and the compiler. In Windows, the executable output produced by a C++ compiler is usually written to a file that has the same name as the source file, but with the extension .exe instead of .cpp. Suppose, for example, we are using the command line environment in Borland C++. If we give the command bcc hello.cpp then the executable code is written to hello.exe. To execute the program, we give the command hello.exe or, equivalently, hello To invoke the program, we do not need to type the .exe extension. If we wish to rename this file, we can use the rename command. No, mother, I didn’t say “our secret pizza sauce code would make us rich,” I said “our secret piece of source code would make us rich.” Ira Pohl’s C++ by Dissection 1.7 Dr. P’s Prescriptions 16 1.6.1 Interrupting a Program The user may want to interrupt, or kill, a program that is running. For example, the pro- gram may be in an infinite loop. (In an interactive environment, it is not necessarily wrong to use an infinite loop in a program.) Throughout this text, we assume that the user knows how to interrupt a program. In Windows and in UNIX, a control-c is com- monly used to effect an interrupt. On some systems a special key, such as delete or rubout, is used. Make sure you know how to interrupt a program on your system. 1.6.2 Typing an End-of-File Signal When a program is taking its input from the keyboard, it may be necessary to type an end-of-file signal for the program to work properly. In UNIX, this is done by typing a control-d. In Windows, a control-z is typed instead. 1.7 1.7 Dr. P’s Prescriptions Dr. P’s first rule of style is Have a style. Be consistent in whatever style you choose. Check that your compiler supports full, modern C++ In this book, we follow the traditional C and C++ style pioneered by Bell Laboratories programmers, such as Brian Kernighan, Dennis Ritchie, and Bjarne Stroustrup. Several elements of this style can be seen in our programs. Beginning and ending braces for function definitions line up under each other and under the first character of the func- tion definition. Beginning braces after keywords, such as do and while, follow the key- word with the ending brace under the first character of that line. This style is in widespread use and makes it easy for others to read your code. The style allows us to distinguish key elements of the program visually, enhancing readability. Style should aim for clarity for both ourselves and others who need to read our code. Cleverness by its nature is usually obscure, and is the enemy of clarity. Hence, Kernighan and Plauger’s maxim Write clearly—don’t be too clever. Also, inconsistent style tends to obscure. C++ compilers for ANSI C++, as described here, may still be incomplete. Make sure you know what the vendors support, especially when it comes to recent changes in the use of namespaces, exception handling, templates, and libraries.Ira Pohl’s C++ by Dissection 1.8 C++ Compared with Java 17 1.8 1.8 C++ Compared with Java Increasingly, beginning programmers start by studying Java. The roots of C++ and Java both are found in C. Most serious programmers will end up learning all three languages. This book is coordinated in its treatment with the book Java by Dissection, by Pohl and McDowell, (Addison-Wesley, 1999) and with the book C by Dissection, Fourth Edition, by Kelley and Pohl (Addison Wesley, 2000). These comparison sections are an enrichment for those readers who already know or wish to know Java. If they are a distraction to others, they can be skipped. In this section, we implement our change-making algorithm from Section 1.2.1, Algo- rithms—Being Precise, on page 9, in the Java programming language. This is taken from Java by Dissection, pages 5–7. In file MakeChange.java // Change in dimes and pennies import tio.; // use the package tio class MakeChange public static void main (String args) int price, change, dimes, pennies; System.out.println("type price (0:100):"); price = Console.in.readInt(); change = 100 - price; //how much change dimes = change / 10; //number of dimes pennies = change % 10; //number of pennies System.out.print("The change is :"); System.out.print(dimes); System.out.print(" dimes "); System.out.print(pennies); System.out.print(" pennies.\n"); Ira Pohl’s C++ by Dissection 1.8 C++ Compared with Java 18 Dissection of the MakeChange Program import tio.; // use the package tio A package is a library or collection of previously written program parts that you can use. This line tells the Java compiler that the pro- gram MakeChange uses information from the package tio. We devel- oped this package especially for Java by Dissection to simplify keyboard input for you. It allows you to write Console.in.read- Int(), which we explain shortly. The source code is presented in Appendix D, The tio Library, and is available for download on the Web at ftp://ftp.awl.com/cseng/authors/pohl-mcdowell/. You can also view it at http://www.cse.ucsc.edu/charlie/java/tio/. int price, change, dimes, pennies; This program declares four integer variables. These hold the values to be manipulated. System.out.println("type price(0 to 100):"); This line is used to prompt you to type the price. Whenever a pro- gram is expecting a user to do something, it should print out a prompt telling the user what to do. The part in quotes appears on the user’s screen when the program is run. price = Console.in.readInt(); The Console.in.readInt() is used to obtain the input from the keyboard. The value read is stored in the variable price. The symbol = is called the assignment operator. Read the first line as the variable price is assigned the value obtained from the input command Con- sole.in.readInt(). At this point, you must type in an integer price. For example, you would type 77 and then hit Enter. change = 100 - price; // how much change This line computes the amount of change. dimes = change / 10; // number of dimes pennies = change % 10; // number of pennies The number of dimes is the integer or whole part of the result of dividing change by 10. The symbol /, when used with two integers, computes the whole (nonfraction) part of the division. The number of pennies is the integer remainder of change divided by 10. The symbol % is the integer remainder, or modulo, operator in Java. So if change is 23, the integer divide of 23/10 is 2 and the integer remain- der, or modulo, of 23 % 10 is 3.Ira Pohl’s C++ by Dissection 1.8 C++ Compared with Java 19 System.out.print("The change is : "); System.out.print(dimes); System.out.print(" dimes "); System.out.print(pennies); System.out.print(" pennies.\n"); In this example, the System.out.print() statements cause the val- ues between the parentheses to be printed on the computer console. The first one just prints out the characters between the quotation marks. The second one converts the value in dimes to the sequence of digits and prints those digits. The other print statements are similar. For an input value of 77, the output would be The change is : 2 dimes 3 pennies The \n in the last print statement indicates that a newline should be sent to the console, ending the line of output. Throughout this book we use the tio package in order to simplify the input and output required for Java. The source code is presented in Appendix D, The tio Library, and is available for download on the Web at ftp://ftp.awl.com/cseng/authors/pohl-mcdowell/. You can also view it at http://www.cse.ucsc.edu/charlie/java/tio/.Ira Pohl’s C++ by Dissection Summary 20 Summary An algorithm is a computational procedure consisting of elementary steps. Program- ming is the art of communicating algorithms to computers. When we compile a simple program, three separate actions occur: First the prepro- cessor is invoked, then the compiler, and finally the linker. A simple program consists of optional preprocessing directives and the function main(). The body of the function is made up of declarations and statements written between the braces and . All variables must be declared. The declarations must occur before the statements that use the variables. The statement cout "Hello, world" endl; prints output to the terminal. The endl places the cursor on a new line. It also flushes the output buffer, printing everything to that point. Following a set of instructions by writing out the results is called hand simulation or bench testing. It is a good way to find errors in an algorithm or program. Errors are called bugs, and finding and removing them is called debugging. An algorithm is a sequence of instructions that will terminate. The instructions are precise. Each instruction is unambiguous. The instructions are simple. Each instruc- tion is within the capabilities of the executing agent and can be carried out exactly in a finite amount of time. There are inputs and outputs. An algorithm has one or more outputs that depend on the particular input data. Informal notations for algorithms are called pseudocode, whereas real code is some- thing suitable for a computer. Before coding in C++, it is useful to write pseudocode and simulate its execution.

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.