CODE JOURNAL: Your Guide to Programming January 22, 2002 In This Edition: - Welcome to the Code Journal - Standardized Article - The Tower of Babel - Questions and Answers - Programming Challenge - Errata Welcome to Code Journal, a joint venture between Cprogramming.com (http://www.cprogramming.com) and AI Horizon (http://www.aihorizon.com) that aims to provide insightful articles on both C++ and algorithmic programming. Code Journal is helpware: in return for reading it, you are asked to help someone else out with their own programming problems. Good luck, and quick compiling. --------------------------------------------------------- C/C++ Programming by Alex Allain --------------------------------------------------------- Templates in C++ What's better than having several classes that do the same thing to different datatypes? One class that lets you choose which datatype it acts on. Templates are a way of making your classes more abstract by letting you define the behavior of the class without actually knowing what datatype will be handled by the operations of the class. In essence, this is what is known as generic programming; this term is a useful way to think about templates because it helps remind the programmer that a templated class does not depend on the datatype (or types) it deals with. To a large degree, a templated class is more focused on the algorithmic thought rather than the specfic nuances of a single datatype. Templates can be used in conjunction with abstract datatypes in order to allow them to handle any type of data. For example, you could make a templated stack class that can handle a stack of any datatype, rather than having to create a stack class for every different datatype for which you want the stack to function. The ability to have a single class that can handle several different datatypes means the code is easier to maintain, and it makes classes more reusable. The basic syntax for declaring a templated class is as follows: template class a_class { ... }; The keyword class above simply means that the identifier 'a_type' will stand for a datatype. Note: 'a_type' is not a keyword; it is an identifier that during the execution of the program will represent a single datatype. For example, you could, when defining variables in the class, use the following line: a_type a_var; When the programmer defines which datatype 'a_type' is to be when the program instantiates a particular instance of 'a_class', 'a_var' will be of that type. When defining a function as a member of a templated class, it is necessary to define it as a templated function: template void a_class::a_function(...) { ... } When declaring an instance of a templated class, the syntax is as follows: a_class an_example_class; An instantiated object of a templated class is called a specialization; the term specialization is useful to remember because it reminds us that the original class is a generic class, whereas a specific instantiation of a class is specialized for a single datatype (although it is possible to template multiple types). Usually when writing code it is easiest to precede from concrete to abstract; therefore, it is easier to write a class for a specific datatype and then procede to a templated - generic - class. For that brevity is the soul of wit, this example will be brief and therefore of little practical application. We will define the first class to act only on integers. class calc { public: int multiply(int x, int y); int add(int x, int y); }; int calc::multiply(int x, int y) { return x*y; } int calc::add(int x, int y) { return x+y; } We now have a perfectly harmless little class that functions perfectly well for integers; but what if we decided we wanted a generic class that would work equally well for floating point numbers? We would use a template: template class calc { public: A_Type multiply(A_Type x, A_Type y); A_Type add(A_Type x, A_Type y); }; template A_Type calc::multiply(A_Type x, A_Type y) { return x*y; } template A_Type calc::add(A_Type x, A_Type y) { return x+y; } To understand the templated class, just think about replacing the identifier 'A_Type' everywhere it appears, except as part of the template or class definition, with the keyword 'int'. It would be the same as the above class; now when you instantiate an object of class calc you can choose which datatype the class will handle. calc a_calc_class; Templates are handy for making your programs more generic and allowing your code to be reused later. ************************************ Alexander Allain is the webmaster of http://www.cprogramming.com. Contact him at webmaster@cprogramming.com --------------------------------------------------------- Algorithms and Programming by Eric Suh --------------------------------------------------------- The Tower of Babel The programming community has tons and tons of languages to choose from, but what's the difference? Why have tons of languages? Why can't we all settle down and choose just one? These days, programming languages are becomming more and more general and all-purpose, but they still have their specializations, and each language has its disadvantages and advantages. C++ is well-suited for large projects because it has an object-oriented structure. People can collaborate on one program by breaking it up into parts and having a small group or even one individual work on each part. The object-oriented structure also allows code to be reused a lot, which cuts down development time by a significant amount. C++ is also a fairly efficient language - although many C programmers will disagree. C is used a lot, especially in game programming, because it doesn't have the extra packaging of the object-oriented C++. Programmers use C because it makes programs slightly faster and smaller than programs written in C++. You have to wonder, however, whether it's really worth giving up the ease and reuseability of C++ to get the small increase in performance with C. Pascal is still mostly a teaching language, and not many industrial programs are written in Pascal. Pascal uses keywords a lot instead of C-style braces and symbols, so it is a bit easier for beginners to understand than languages like C++. Still, not all people think Pascal is just for the schools. Borland, the huge compiler software company, has been pushing Delphi as an industrial strength programming language. Delphi is an object-oriented version of Pascal, and currently, only Borland compilers use it. Fortran is a number-crunching program, and it is still used a lot by scientists because the language allows variables of any size up to the memory limit of the machine. Fortran is especially convenient for engineers, who have to mathematically model and compute many different variables to large precisions. Fortran, however, isn't nearly the flexible language that C++ or C is. Programming in Fortran is rigid, with strict rules on whitespace and formatting, which sometimes makes reading Fortran programs difficult. Java is a multi-platform language that is especially useful in networking. Of course, the most famous usage of Java is on the Web, with Java applets, but Java is also used to build cross-platform programs that stand alone. Since it resembles C++ in syntax and structure, learning Java is usually quite easy for most programmers. Perl was originally a file management language for Unix, but it has become famous as a CGI language. CGI (Common Gateway Interface) is a term for programs that web servers can execute to allow web pages additional capabilities. Perl is great with Regular Expression Pattern Matching, which is a method (or tool) for searching text. So, Perl can be used for databases and other useful server functions, and because it is a scripting language, it is pretty easy to learn. Web Hosting Services prefer Perl over C++ as a CGI language because the Web Hosts can inspect Perl script files, since they're just text files, while C++ is compiled, so it can't be inspected for potentially dangerous code. LISP is used mostly in Computer Science research. LISP is especially handy in programming abstract ideas because LISP is able to process a data structure called lists. Lists are like arrays, except lists have no index numbers. The syntax for lists is very simple, and so LISP programmers can manipulate these lists easily to implement complex structures easily. Of course, there are still many, many languages I still haven't covered, (Prolog, Scheme, Tcl, Python, COBOL, Smalltalk, C#, etc.) but those are generally related or similar to the programming languages I have described above. You get the idea, however. Programming languages still have their advantages and disadvantages, so picking the appropriate language for the task is often an important step in the process of developing an application or program. Now, if only I had enough time to learn them all... ************************************ Eric Suh is the webmaster of AI Horizon ( http://www.aihorizon.com/ ), a site devoted to Artificial Intelligence and Computer Science programming. Contact him at webmaster@aihorizon.com. --------------------------------------------------------- Questions and Answers on Programming --------------------------------------------------------- In response to the numerous emails Cprogramming.com receives, I have written an article on common programming mistakes. Due to its length, it is available only online. Read it at http://www.cprogramming.com/tutorial/common.html If you have a question on programming, send it in to either Cprogramming.com or AI Horizon and your question may be answered here. --------------------------------------------------------- Code Challenge --------------------------------------------------------- Every issue, we will issue a programming challenge and ask people to submit their solutions within two weeks. A few of the best solutions will be published the next issue, along with a new challenge. The Previous Issue's Challenge ------------------------------------ Write an Exclusive-OR encryption program. The program should take as input a filename that is then encrypted by the program. The program should ask the user to input an encryption key, which should be used to encrypt the file. The output of the program should go into a file with the same filename but a .ENC extension (for simplicity sake). All programs should run under DOS. Solutions ------------------------------------ We only received three responses to the challenge last week: congratulations to Niels Voigt, James Turk, and Matthew Costuros for their quick responses. The solutions are available at: http://www.cprogramming.com/source/nvxor.c http://www.cprogramming.com/source/jtxor.cpp http://www.cprogramming.com/source/mcxor.cpp This Week's Challenge ------------------------------------ As towers seem to be a theme this week, write a program to solve the Towers of Hanoi problem. The Towers of Hanoi is a very old problem, and its solution is a relatively simple algorithm to work out and program. In the game, there is a pyramidally shaped stack of disks placed onto an upright peg. There are two other pegs, each empty. The challenge is to move all of the disks from the first peg to the third peg. There is a catch, however. Each disk is a different size, and each disk can only be placed on top of a larger disk. You are free to place any disk on an unoccupied peg, but after the first disk has been placed, only smaller disks can be placed on it. Also, you can only move one disk at a time (they're made of ultra-dense, ultra-heavy material!) -|- | | --|-- | | ---|--- | | ----|---- | | Move these to here. The program must be able to handle any height of disks up to and including eight; the program should be able to output the intermediate steps as the solution is worked out; the program should use some form of ASCII output for the representation. Send your solutions to solutions@cprogramming.com as source code files, and you may find it published. Please include either your name or an identifying username so that we may attribute the solution to you in the next newsletter. If you wish, you may ask us to withhold your name. --------------------------------------------------------- Errata --------------------------------------------------------- In the previous issue, there were two mistakes: In the article "Hashed Browns and Smiths," Eric stated that the fiftieth element of an array is accessed by typing employees[50]; He should have written employees[49]; As well, Al stated in "XOR Encryption" that C++ has no Exclusive-OR operator. It does, however. ^ is the symbol for Bitwise Exclusive-OR, used like this: first_operand ^ second_operand; We apologize for these mistakes, and if we have made any errors in this issue, please inform us. --------------------------------------------------------- Suggestions and comments on this newsletter should be sent to codejournal@cprogramming.com or codejournal@aihorizon.com. Editors: Eric Suh, webmaster@aihorizon.com Alexander Allain, webmaster@cprogramming.com To unsubscribe from this journal, send a blank email to codejournal-unsubscribe@mlm.cprogramming.com.