Introduction to Binary

Document Sample
Introduction to Binary Powered By Docstoc
					                                                                    Chapter 1 – Computer Science         1



                           Chapter 1 – Computer Science
1.1 Preface

C++ for Geniuses -- (pronounced C plus plus for Geniuses minus minus) covers various aspects of the
C++ programming language including input and output, variables and constants, if...else statements,
loops, functions, strings, and recursion. Graphical programming is not covered – all programs in this
book are command line or console programs.

This book was written by a computer science college instructor who watched beginning students struggle
through various C++ books. The goal of this book is to provide a clear and understandable C++ textbook
that will be tested and refined in the classroom by observing students using the book. The style of the
book is to explain concepts as simply as possible using a top – down approach before covering the details.
In addition, since most people learn by doing, many examples and exercises have been provided. All
program listings in this book are complete and have been tested using the Linux GNU (g++) compiler.

1.2 Programming Languages

A programming language is used to create computer programs. The native language of the computer
(CPU) is machine language. Since this is a tedious language to code, high-level programming languages
have been created. These languages will either be compiled or interpreted into machine language to
execute.

A compiler translates an entire program (source code) into machine language before executing it. Each
programming language has its own compiler. A program must be compiled for each CPU or operating
system it is executed on. For example, to run a C++ program on both a PC and Mac computer, you will
need to obtain a compiler for both operating systems. An exception is Java.

An interpreter translates a program into machine language one line at a time while the program is
running. An executable program is not created as with compiled languages. One advantage of an
interpreter is that the program will usually halt execution where an error is encountered, helping the
programmer discover errors easily. A disadvantage of an interpreter is that the program runs less
efficiently than a compiled program. BASIC is a popular interpreted programming language.

When a new CPU is developed (e.g. Intel Pentium), the first programming is done using machine
language – the CPU's native tongue. Machine language is considered a low-level programming
language. Low-level languages are usually hardware (CPU) dependent. Because of the tedious
programming of a low-level language, high-level programming languages have been developed. These
languages allow the programmer to write code using a simpler format (in English) and then compile it
into the CPU's native machine language for execution. High-level languages are generally not hardware
dependent. The following table lists a few programming languages.
2    Chapter 1 – Computer Science



                                      Programming Languages
Language             Description
Machine Language     The native programming language of the computer's CPU. This low-level
                     language is tedious – CPUs come with a specified set of very basic instructions and
                     operations. For example, a load instruction will move each piece of data from
                     memory to a register on the CPU for processing. Machine language is written in
                     binary – all 1's and 0's.
Assembly             A fancier way to write machine language. This low-level language allows
Language             instructions to be written in a more understandable format (instead of binary), then
                     converted to machine language.
C                    A high-level structured, procedural programming language that is widely used for
                     programming applications as well as operating systems. It was developed on a
                     UNIX system and later used to reprogram UNIX.
C++                  A high-level object oriented programming language that is a superset of C.
                     Originally designed by Bjarne Stroustrup of AT&T's Bell Labs in 1979. It adds
                     better type checking, data abstraction, and object oriented programming to C.
C#                   Pronounced C-Sharp, this programming language was developed by Microsoft as
                     part of the .NET Framework. In some ways, it is an upgrade to C++ and was
                     designed to compete with the Java language.
BASIC                An early high-level programming language that is simple to use and widely
                     popular. Many of the first home computers in the 1970's and 1980's included this
                     programming language.
COBOL                COBOL (Common Business Oriented Language) was the first widely used high-
                     level language for business applications such as payroll and accounting. This older
                     programming language has been updated and is still used today, mostly on
                     mainframe computers.
FORTRAN              FORTRAN (Formula Translation) is an older high-level language that was
                     designed for scientific applications.
Pascal               Pascal is an older high-level language that was also designed for math and science
                     applications. It was popular as a teaching tool for structured programming before
                     C became popular.
Visual Basic (VB)    Microsoft's Visual Basic adds object-oriented features and a graphical user
                     interface to the standard BASIC language.
Java                 A high-level object-oriented programming language developed by Sun
                     Microsystems for creating applets that are platform independent. A Java applet
                     (.class file) will execute on any operating system that has the Java run-time console
                     installed. Java applets first became popular as programs that execute within a web
                     browser.
JavaScript           A scripting language used in web pages that enhances the limited capabilities of
                     HTML. JavaScript adds many functions to HTML including as cookies and pop-
                     up windows.

For most languages, programming language standards have been written. It is important to standardize
a programming language for the sake of portability. Portability means that a C++ program (source code)
can be placed on a different system using a different compiler. For example, a program created and
compiled using the Linux g++ compiler should be able to be compiled using Microsoft Visual C++
without making changes.
                                                                  Chapter 1 – Computer Science       3


C++ has been standardized by two organizations working together: American National Standards Institute
(ANSI) and The International Standardization Organization (ISO). The C++ standard which was adopted
in 1998 is referred to as ISO/IEC 14882:1998.


1.3 Software Development Life Cycle
Creating a program or application is often referred to as software development. Developing larger
applications might be called systems development. Larger projects require extensive planning,
organizing, and management. Example large systems include the Windows XP operating system, the
UPS package delivery system, and the American Airlines reservation system. Different organizations
may have different software development methodologies. Government agencies usually have
documented formal guidelines. The following table lists the general steps involved with software
development.

                                 Software Development Life Cycle
Step                 Description
Problem Analysis     Create the specifications for the software. Analyze end-user needs. Create a
                     requirements definition. Refine the project's goals into defined operation and
                     functions. Analyze end-user information needs and develop a requirements
                     definition.
Software Design      Create a program design from the specifications. Decide on a programming
                     language and algorithm for the program. Describe desired features and operations
                     in detail using screen layouts, business rules, process diagrams, pseudo code and
                     other documentation.
Programming          The system design is implemented as code by the programmers.
Testing              Create a test version of the software (beta version) and implement in a special
                     testing environment. Check for errors, bugs, and interoperability.
Deployment           Put the software into production: install the software and train the users.
Maintenance          After deployment, the software will occasionally need modification due to bugs,
                     desired new features, or if the software is ported to a new platform (e.g. moved to a
                     different operating system). The maintenance step will continue as long as the
                     software is in use.

• Pseudo Code

For small programs such as the ones listed in this book, pseudo code can help layout a problem before
you write the actual code. Pseudo code shows a detailed description with how a program should work,
but expressed in natural language rather than the programming language. It allows the designer to show
the steps needed for a program without actually coding it. The following is example pseudocode for a
program that calculates the volume of a pyramid.

                           1. Declare variables for base, height and width
                           2. Prompt the user to enter the pyramid's height.
                           3. Prompt the user to enter the pyramid's base.
                           4. Prompt the user to enter the pyramid's width.
                           5. Calculate Volume = (base * width * height) / 3
                           6. Display the volume of the pyramid.
4   Chapter 1 – Computer Science


• Flowcharts

Another tool used by some programmers are
flowcharts. A flowchart provides a graphic
representation of a program's logical sequence.
They describe each processing path in a program.
With the advent of object-oriented programming,
flowcharts have become less common. Since C++
adds objects (i.e. classes) to the C language,
flowcharts are less frequently used in C++.

The diagram on the right shows a simple flowchart
for a software installation program. Processes are
shown as squares. Decisions (e.g. if statements) are
shown as diamonds.




• Application Generators

Many programming environments contain software tools for generating parts of a program automatically.
For example, a report generator is a popular tool found in database programming languages that enable
you to create a report visually by specifying the needed data fields and layout. A form generator is used
by database languages to create data entry forms. Programming languages like Visual Basic allow you to
create screens visually and have the code generated automatically.
                                                     Chapter 2 – Introduction to Numbering Systems        5



           Chapter 2 – Introduction to Numbering Systems

2.1 Decimal (base-10)
The numbering system we use is called the decimal system. It consists of 10 numbers: 0123456789.
Some ancient civilizations used other numbering systems. For example, the Babylonians used the
sexagesimal system, based on the number 60. The Babylonians divided the circle into 360 degrees (a
multiple of 60). The Mayas used the vigesimal system, based on the number 20.

2.2 Unary (base-1)
A base-1 numbering system was used by some people in ancient times before more advanced systems
were developed. In a base-1 system, you simply put a mark (or a 1) for each item you are counting. For
example, bones have been found with 29 and 30 notches, possibly corresponding to the cycle of the
moon:




Placing a mark for every item you are counting would be quite cumbersome if you need to count larger
quantities. Slightly more advanced are numbering systems that have special symbols to represent larger
numbers. For example, Roman numerals use I, V, X, etc. The ancient Egyptians also used symbols to
represent larger quantities. The number below is 2,382,358.




                 1,000,000    100,000     10,000    1,000    100        10        1




2.3 Binary (base-2)
The electronic circuitry within computers is composed of millions of transistors. Each of these circuits
has two states – on and off. On and off is viewed as representing 1 and 0, respectively. Because of this, a
base-2 numbering system was devised for computers. Counting in binary is often a tricky concept to
understand for newcomers.
6    Chapter 2 – Introduction to Numbering Systems


In binary, each digit has only two numbers – 0 and 1. With a two-digit decimal number, you can count
from 0 to 99. With a two-digit binary number, you can only count to 3. The following table shows all
the combinations of two binary digits with their decimal equivalent.

                                       2-Digit Binary          Decimal
                                          number              Equivalent
                                               00                   0
                                               01                   1
                                               10                   2
                                               11                   3

One method that might help you understand counting in binary would be to use the decimal system, but
only keep the numbers that contain 0's and 1's. The following table shows these numbers in bold:

    0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

    30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

    60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89

    90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119


With a four-digit binary number, you can count from 0 to 15. The following table shows all the
combinations of four binary digits with their decimal equivalent.

                                       Binary Decimal Binary Decimal
                                          0000      0        1000        8
                                          0001      1        1001        9
                                          0010      2        1010       10
                                          0011      3        1011       11
                                          0100      4        1100       12
                                          0101      5        1101       13
                                          0110      6        1110       14
                                          0111      7        1111       15

There are different methods used to convert between binary and decimal numbers. One way to convert a
binary number to decimal is to calculate the value of each digit and add these up. Since binary is based
on multiples of 2, each successive digit is two times the previous. The following example illustrates this.

Value of each digit:       8 4 2 1                      Add 2 + 8
                           ↓ ↓ ↓ ↓
Binary number:             1 0 1 0                      Decimal number: 10

In a binary number, the first digit (farthest to the right) has a value of 1. The next digit (to the left) has a
value of 2. The third digit has a value of 4. The fourth digit has a value of 8, etc. In the binary number
1010, since the second and fourth digits are 1, you would add 2 + 8 which is equal to 10. Look at another
example.
                                                      Chapter 2 – Introduction to Numbering Systems            7


Value of each digit:     16 8 4 2 1               Add 1 + 2 + 4 + 16
                         ↓ ↓ ↓ ↓ ↓
Binary number:           1 0 1 1 1                Decimal number: 23


A bit is a single binary digit, which can be 0 or 1. A byte is 8 binary digits (8 bits), which allows you to
count from 0 to 255. Data in most computers is organized in bytes. The following table shows how the
metric system applies to bits and bytes.

Unit                Size                              What it Can Store
Bit                 0 or 1                            One bit of information can store answers to yes/no
                                                      questions: "Do you have a driver‟s license?"
Byte                8 bits                            Each character in a document on your computer uses
                                                      one byte of storage.
Kilobyte (KB)       1,000 bytes                       2 Kilobytes could store one page of a document. 50
                                                      Kilobytes can store a low resolution photograph.
Megabyte (MB)       1,000,000 bytes                   1 Megabyte can store a novel. 5 Megabytes can store
                                                      the complete works of Shakespeare or 30 seconds of
                                                      TV-quality video. 640 Megabytes can store a music
                                                      CD.
Gigabyte (GB)       1,000,000,000 bytes               1 Gigabyte can store a movie at TV quality. 4
                                                      Gigabytes can store a DVD movie.
Terabyte (TB)       1,000,000,000,000 bytes           10 Terabytes can store the printed section of the
                                                      Library of Congress.
Petabyte            1,000,000,000,000,000 bytes       250 Petabytes can store everything ever printed on
                                                      Earth.
Exabyte             1,000,000,000,000,000,000         5 Exabytes can store everything ever spoken by
                    bytes                             people


2.4 Hexadecimal (base-16)
Hexadecimal was developed as an easier way to deal with binary. With four binary digits, you can count
from 0 to 15 in decimal (as shown in the table in the previous section). One hexadecimal digit can be
used to replace four binary digits. Hexadecimal uses the numbers 0 – 9, then A – F to give a total of 16
numbers.

 Decimal     0    1    2    3    4    5    6    7    8    9    10 11 12 13 14 15
 Binary      0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
 Hexadecimal 0    1    2    3    4    5    6    7    8    9    A    B    C    D    E    F

As can be seen in the previous table, the 16 different hexadecimal digits are 0123456789ABCDEF.
When counting in hex, you combine the numbers similar as to counting in decimal. The next numbers
after F are 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C, 1D, 1E, 1F, 20, 21, etc. Often, a
hexadecimal number is written with a 0x in front of it: 0xB means B hex, or 11 in decimal.
8   Chapter 2 – Introduction to Numbering Systems


2.5 ASCII
In most computers, each character of data is stored using one byte (8 bits) of memory. Each space and
punctuation mark also uses one byte. Therefore, this sentence takes 40 bytes. Since each byte represents
a number between 0 and 255, ASCII is way of coding data so that each character has a corresponding
number. For example, "a" is 97; "b" is 98, "c" is 99, etc. The following ASCII chart shows each
character and the corresponding number used to represent it.

                                           ASCII Chart
ASCII#       Char     ASCII#   Char   ASCII#   Char   ASCII#   Char   ASCII#   Char   ASCII#   Char
 0–8       unused       53      5       78      N      103      g      128      Ç      153      Ö
   9          tab       54      6       79      O      104      h      129      ü      154      Ü
  10      line feed     55      7       80      P      105      i      130      é      155      ¢
11 - 31    unused       56      8       81      Q      106      j      131      â      156      £
  32        space       57      9       82      R      107      k      132      ä      157      ¥
  33           !        58      :       83      S      108      l      133      à      158      ₧
  34           "        59      ;       84      T      109      m      134      å      159      ƒ
  35           #        60      <       85      U      110      n      135      ç      160      á
  36           $        61      =       86      V      111      o      136      ê      161      í
  37           %        62      >       87      W      112      p      137      ë      162      ó
  38           &        63      ?       88      X      113      q      138      è      163      ú
  39            '       64      @       89      Y      114      r      139      ï      164      ñ
  40           (        65      A       90      Z      115      s      140      î      165      Ñ
  41           )        66      B       91      [      116      t      141      ì      166      ª
  42           *        67      C       92      \      117      u      142      Ä      167      º
  43           +        68      D       93      ]      118      v      143      Å      168      ¿
  44           ,        69      E       94      ^      119      w      144      É      169      ⌐
  45           -        70      F       95      _      120      x      145      æ      170      ¬
  46           .        71      G       96      `      121      y      146      Æ      171      ½
  47           /        72      H       97      a      122      z      147      ô      172      ¼
  48           0        73      I       98      b      123      {      148      ö      173      ¡
  49           1        74      J       99      c      124      |      149      ò      174      «
  50           2        75      K      100      d      125      }      150      û      175      »
  51           3        76      L      101      e      126      ~      151      ù
  52           4        77      M      102      f      127      ⌂      152      ÿ

You will notice in this ASCII chart that there are many characters (e.g. Æ ) that do not have a key on the
keyboard. These characters can be typed by holding down the Alt key and typing the ASCII number on
the keypad. For example, open up the Windows notepad program. Hold the Alt key and type "171" on
the keypad. When you release the Alt key, the character "½" will appear.
                                                          Chapter 2 – Introduction to Numbering Systems   9


2.6 Storing Text on a Computer
The table below illustrates how the letter „Z‟ is stored on a computer electronically.

The letter „Z‟ is typed on the computer using a word                             Z
processor.
The letter „Z‟ is converted to a number using the ASCII
                                                                                90
table. Decimal 90 corresponds to the letter „Z‟.
The decimal number 90 is converted to binary                                01011010
(01011010).
In the computer‟s memory, there are electronic circuits
that are either on or off. One circuit is used to represent
one binary digit – 1 if the circuit is on, 0 if the circuit is
off. Eight of these circuits form one byte.

                                                                 Off-On-Off-On-On-Off-On-Off




Exercises – Chapter 2
1.     Convert the following binary numbers to decimal:
       (a) 11   (b) 0101 (c) 1111    (d) 10101   (e) 11111111                            (f) 11111110

2.     Convert the following decimal numbers to binary:
       (a) 5   (b) 2   (c) 7   (d) 8   (e) 15   (f) 24

3.     Convert the following hexadecimal numbers to binary:
       (a) 1   (b) 9   (c) B   (d) DC   (e) F1   (f) FF

4.     List the ASCII numbers for the following words:

       (a) Hi              ___ ___
       (b) apple           ___ ___ ___ ___ ___
       (c) kiwi            ___ ___ ___ ___
       (d) Excite!         ___ ___ ___ ___ ___ ___ ___

5.     What do the following ASCII Numbers translate to?

       73 32 97 109 32 104 117 110 103 114 121 46

6.     If a photograph is 700KB in size, how many could you store on a
       2 gigabyte flash drive?
10   Chapter 3 – Using Linux


                                Chapter 3 – Using Linux
3.1 C++ Compilers

When programming in C++, you must decide what compiler or development environment you will be
using. The following table lists some of the compiler choices.

Compiler                    Comments
Linux g++                   To use the g++ compiler, you must have access to a Linux computer. The C
                            programming language was developed on the UNIX operating system and
                            later used to rewrite the operating system. It provides a nice environment for
                            non-graphical C++ programs.
Microsoft Visual C++        Microsoft's Visual C++ provides a nice graphical environment for creating
                            and running your programs. It is geared towards creating large Windows
                            applications.
Borland C++                 Borland offers a free C++ compiler. It runs from a DOS/Windows command
                            prompt (non-graphical). It may be downloaded from the Borland web site.

This book covers using Linux with the g++ compiler, although the concepts and programs should work
with any C++ compiler. This chapter covers basic UNIX background and basic commands if you will be
using the Linux compiler.

3.1 UNIX/Linux Background

The UNIX operating system (OS) was developed at Bell Laboratories in 1969. Other companies and
organizations developed their own versions of UNIX. Popular versions (flavors) of UNIX include Sun
Solaris, HP UX, IBM AIX, BSD (Berkley Systems Development), and Linux. UNIX is known as being a
very stable OS which makes efficient use of the computer‟s resources. In addition, UNIX is a multi-user
OS allowing many users to log in and run programs simultaneously.

UNIX (and all the other flavors of) has become more popular recently and is being used as firewalls,
routers, network servers, web servers, and e-mail servers. The original Internet protocols were all
developed on UNIX. The telecom industry uses UNIX systems extensively. Nevertheless, UNIX has
become popular for students to learn because of its demand in industry.

Linux was developed by Linus Torvald as a UNIX-like OS to run on an Intel 386 computer that would be
more efficient than Windows. Linux is open source software – it is free to load on as many computers as
you wish and the source code is readily available if you choose to modify it. Linus Torvald developed the
core of the OS, or the kernel. For the user interface, or shell, he made use of software developed by the
Free Software Foundation and GNU (GNU's Not UNIX). Different companies now have their own
distributions of Linux, with the most popular being Red Hat. Since Linux is free, these companies make
money by providing technical support, books, application software, etc.

Linux (as well as other flavors of UNIX) have different shells that can be used as the user interface. The
default command-line interface shell is called BASH (Bourne Again Shell) which is an update of the
original UNIX Bourne shell. There is a graphical shell similar to Windows called XWindows, or just X.
The examples in this book assume you are logged into a Linux computer using the BASH shell.
                                                                           Chapter 3 – Using Linux       11


3.2 Logging Into Linux

To log into a Linux computer you will need an account on that system. You will need to see your system
administrator for an account and how to log in. Typically, the telnet program (included with Windows) is
used for connecting to Linux systems. For secure connections, Secure Shell (ssh) is often used. Since
there are a variety of methods for logging on, this book does not attempt to describe them all. Your
system administration or instructor should have specific instructions for connecting to the system.

3.3 Linux File System

Linux computers have a file system with some similarities to DOS/Windows. There are no logical drive
letters like C: or D: Instead, the top level directory is denoted with a slash - /. You may notice that
UNIX/Linux uses forward slashes for specifying directories whereas DOS/Windows uses back slashes.
When you first log in, you are placed in your home directory: /home/UserName. This directory is your
personal space for storing files you create (e.g. C++ programs). The following table lists some of the
common directories found on a Linux system.

                              Common Linux File System Directories
                  Directory        Contents
                  /etc             Configuration files for the Linux system.
                  /home            User home directories.
                  /var and /tmp    Linux system log files or temporary files.
                  /bin             Linux system user programs: login, shells,
                                   editors, system utilities.
                  /sbin            System administrator programs.
                  /mnt             Contains mount points (access) to CD-ROM's,
                                   floppy drives, etc.
                  /usr             User applications.


3.4 Linux File Commands

This section explains some basic Linux commands that you can use for working with files. After you log
on to the Linux system, you will be at a $ prompt. From this prompt you will execute all Linux
commands. A common mistake for people new to Linux is to attempt to run commands from a sub-
prompt or from the editor. Remember to look for the $ prompt for typing commands. Linux is case
sensitive and most commands are in lowercase.

$ ls                                   The ls command shows all the files in the current directory. If
a.out    hello.cpp        prog2        you have not changed directories, this should list the files in your
test.cpp                               home directory.

$ ls –l                                                         Using the ls -l command, you will get a
total 3                                                         long directory listing. For each file, you
-rwx—-x—-x      kirk    960   Jun   5 10:50 a.out               also see the permissions, the owner, the
-rw-r--r--      kirk    512   Jun   4 9:20 hello.cpp
                                                                size, and the date and time it was last
-rw-r--r--      kirk    386   Jun   6 12:01 prog2
-rw-r--r--      kirk    768   Jun   4 8:34 test.cpp             modified.
12   Chapter 3 – Using Linux


$ mv prog2 prog2.cpp                    The mv command allows you to move, or change the name of a
                                        file. In this example, you are changing the file named prog2 to
                                        prog2.cpp. A common mistake is to forget to put the .cpp
                                        extension on a C++ program file. You can use this command to
                                        change the filename to add the extension.

$ cp test.cpp test2.cpp                 The cp command is used to make a copy of a file, leaving the
                                        original file in tact. In this example, you are making a copy of
                                        test.cpp and naming it test2.cpp.

$ rm hello.cpp                          The rm command is used to remove, or delete a file. In this
                                        example, you are deleting the file named hello.cpp.

$ pwd                                   The pwd command shows you your current directory. If you
/home/kirk                              have not changed directories, this should print your home
                                        directory.

$ mkdir test                            Creates a directory named test. You might do this to organize
                                        files under your home directory.

$ rmdir test                            Removes the directory named test. The directory must be empty
                                        (contain no files).

$ cat test.cpp                          Displays the contents of the file test.cpp. Use this to see a file
                                        without having to open it using an editor.

$ cd test                               Move into the subdirectory named test.

$ cd ..                                 Move up one directory. If you had created a subdirectory named
                                        test and moved into it, then this will put you back in your home
                                        directory.

$ cd ~                                  Move to your home directory (the one you are in when you log
                                        in).

3.5 The Pico Editor
There are many text editors available on a Linux system. Text editors are used to create your C++
programs (source files), as well as any other text files. This section covers using one of the simplest
editors – pico. The most powerful and popular UNIX text editor, as well as the most complicated, is vi.
Another popular editor is emacs. One simple text editor is pico (part of pine mail). There is a newer
version of pico you might find on some Linux servers called nano. To create a new file using pico, or to
edit an existing file, type the following from the command prompt:

$ pico helloworld.cpp

In this example, we are editing a file named helloworld.cpp. You may name the program anything you
want (not just helloworld), but you should always use the .cpp or .c++ extension. The pico text editor will
open up. At the top, you may enter your code. At the bottom of the screen you will see a command
menu.
                                                                            Chapter 3 – Using Linux      13


#include <iostream>
using namespace std;

main()
{
   cout << "Hello World!\n";
}




^G Get Help ^O WriteOut ^R Read File ^Y Prev Pg ^K Cut Text
^X Exit     ^J Justify ^W Where is ^V Next Pg ^U UnCut Text


All pico editor commands are typed by holding the Ctrl key and typing a letter. For example, to exit from
the editor, type Ctrl-X. The following table describes the pico commands.

                                         Pico Editor Commands
Command        Description
^G             Access help for the editor. Use Ctrl-X to exit from the help screen.
^X             Exit from the editor. If you have not already saved your changes, it will ask you if you
               want to save modified buffer – type "y". It will then ask you for a filename to save to. If
               your filename is already listed here, just press Enter.
^O             Save changes without exiting from the editor. You will be asked for a filename. If you
               have already named the file, just press Enter.
^R             Import a file into the editor. This would be useful if you have a C++ function in a
               different file that you need to put into the program you are working on.
^W             Search for a word. You will be prompted to enter the text you are looking for.
^Y             Scroll up to the previous page.
^V             Scroll down to the next page.
^K             Delete the line where the cursor is located. This text is saved if you decide to undelete.
^U             Undelete, or paste the last line that was deleted.
^T             Spell check. The program will display each misspelled word and ask you for a
               replacement. This may not be useful for a C++ file since programming keywords are not
               in the dictionary.

When you are compiling C++ programs, you will often get error messages (unless you never make a
misstake like me). For example, suppose that after you compile a program named hangman.cpp, it tells
you there is a syntax error on line 87. To edit this program and place you at line 87 (so you can look for
the error), type the following command:

$ pico +87 hangman.cpp

A common mistake for new people using the pico text editor is the tendency to reach for the mouse. You
will need to move the cursor using your arrow keys. Do not use your mouse to scroll up or down – this
can mess up the screen.
14    Chapter 3 – Using Linux


3.6 Other Linux Commands

This section lists some other UNIX/Linux commands, although they probably will not be necessary for
basic programming. A real time saver is using the up arrow key at the $ prompt. Pressing this key will
take through the previous commands you have already used. This is especially useful when you are
alternating between the editor and compiling your program.


$ exit                            When you type exit at the $ prompt, you will be logged off the Linux
                                  computer.

$ clear                           Clears the screen.

$ w                               The w command (short for who) lists the users currently logged into
                                  the Linux computer. It also provides other information such as when
                                  each user logged in and the last command they typed. The example
                                  output only shows a portion of information this command provides.

$ cal                             The cal command shows a calendar of the current month. Try typing
                                  cal 2002 to see a complete calendar for the year 2002.

$ date                            The date command shows today's time and date.

$ mail someone@xyz.com            The UNIX mail command is the original Internet e-mail program. The
                                  recipient may be the username of another Linux user or an Internet e-
                                  mail address. After you press enter, you then type the message. When
                                  you are finished, type Ctrl-D to finish.

$ grep cout myprog.cpp            The grep command is used to located text within a file. In this
                                  example, the file myprog.cpp is search for any occurrence of "cout".
                                  The command will print every line of the file containing "cout".

$ w | awk '{print $1}'            The awk command is a more advanced command that allows you to
                                  work with fields (columns). Details of this command are not covered
                                  here. In this example, the output of the w command is piped or sent to
                                  the awk command which prints the first field. Compare this output to
                                  that of the w command.

$ whoami                          Prints your user id.

$ head myprogram.cpp              Prints the first 10 lines of the file myprogram.cpp.

$ tail myprogram.cpp              Prints the last 10 lines of the file myprogram.cpp.

$ wc myprogram.cpp                Counts the number of lines, words, and characters in the file named
                                  myprogram.cpp.
                                                             Chapter 3 – Using Linux     15


$ finger username    Prints information about the user username. Users often create a file
                     in their home directory named .plan with information for others to see
                     when fingered.

$ write username     Sends a message to the screen of the user username. When you are
                     finished typing the message, press Ctrl-D.

$ mesg n             Turns off messages. Use this if you do not want to be disturbed by
                     users sending you messages. Turn back on messaging by typing mesg
                     y.

$ du –h             Displays the amount of disk usage in the current directory, and
                    subdirectories.
16   Chapter 4 – Hello World!



                                Chapter 4 – Hello World!

4.1 Getting Started

Writing your first program in any new programming language can be challenging. Often, the first
program many people write simply prints the following words to the screen: "Hello World!". The Hello
World program may not be complicated, but the challenge is often not in the writing of the program
(since the source code is provided here), but in learning how to use your editor and compiler. Section 1.3
discusses the C++ development cycle and compiler choices. This chapter will cover editing, compiling,
and running your program using Linux.

4.2 Your First Program Using Linux

This section will give the steps needed to create the Hello World program using the Linux g++ compiler.
Note: Linux computers may be configured differently or be different versions so there is no guarantee that
these instructions will be exact for every implementation – you may need to get help from the system
administrator or your instructor.

Step 1 – Logging On

If you not physically sitting in front of the Linux computer, then you will need to log on to it remotely
over the network or Internet. Typically, the telnet program is used to access it. Alternatively, ssh (secure
shell) might be used for your server which provides a secure connection. A popular freeware version of
ssh is Putty.

This section will show how to log on using
telnet. Telnet is included with all versions of
Windows (since Windows 95), but there is no
shortcut on the Start Menu for the program.
Therefore, you will need to click on the Start
Menu and select Run.

Type "telnet ServerName". For ServerName,
you should type the name of the Linux
computer. Press Enter. If you are connected to
the Linux server, you will see the logon screen. Enter your username and password to log on.

Red Hat Linux release 7.0 (Guinness)
Kernel 2.2.16-22 on an i686
login: username
Password: ******

Once you are successfully logged on, you should be at the $ prompt. Logging on to the Linux computer
using telnet will place you into the BASH shell which is a command line interface. Therefore, you will
need to press Enter after typing each command.
                                                                           Chapter 4 – Hello World!      17


Step 2 – Editing Your First Program

To create the source code for the Hello World program, you may use any of the Linux text editors. This
section gives the steps using the pico editor. From the $ prompt, type "pico" followed by a filename for
the program. Note: You may name the program anything you want (not just helloworld), but you should
always use the .cpp or .c++ file extension.

$ pico helloworld.cpp

The pico text editor will open to a screen similar to one shown below. At the top, you may enter your
code. At the bottom of the screen you will see some commands.




^G Get Help ^O WriteOut ^R Read File ^Y Prev Pg ^K Cut Text
^X Exit     ^J Justify ^W Where is ^V Next Pg ^U UnCut Text


Type the following program exactly as shown below written. Notice that following main, are open and
close parentheses ( ). Before and after the cout statement are open and close braces { }.

#include <iostream>
using namespace std;

main()
{
   cout << "Hello World!\n";
}




^G Get Help ^O WriteOut ^R Read File ^Y Prev Pg ^K Cut Text
^X Exit     ^J Justify ^W Where is ^V Next Pg ^U UnCut Text


After typing the above program, you will need to save your program and exit the pico editor. Press Ctrl-
X to exit. Pico will prompt you if you want to save changes (Save modified buffer?). Type "y". Pico
will then ask you for the filename. Your file, helloworld.cpp, should already be listed here so just press
Enter.
18   Chapter 4 – Hello World!


Step 3 – Compiling the Program

Once you have exited pico and returned to the $ prompt, you can compile your program using the g++
compiler:

$ g++ helloworld.cpp

If you did not have any errors, you should return back the $ prompt without any error messages. If you
received error message(s), then go back to step 2 and verify that your program looks exactly like the one
shown in this step.

Step 4 – Running the Program

If your program compiled without any errors, then an executable program was created in your home
directory named a.out. To run the program, just enter:

$ a.out

You should now see the output of your program:

Hello World!

Note: If your a.out program was created but you are unable to execute it by typing a.out after the $
prompt, your directory may not be in your Linux path. In this case, try typing $ ./a.out

4.3 Hello World Program Examined
This section will explain each line of the Hello World program. If you are new to programming or C++,
do not panic if this program looks complicated and foreign. The following program listing shows the
basic Hello World program again.

Program 4.3a – Basic Hello World Program

#include <iostream>
using namespace std;

main()
{
  cout << "Hello World!\n";
}

Output
Hello World!
                                                                            Chapter 4 – Hello World!      19


The following table explains each line of this program. Do not panic if it is not all clear – for most people
understanding will come later after lots of practice.

                          Hello World Program Examined
C++ Statement               Explanation
#include <iostream>         At the top of C++ programs, you will usually find include
                            statements. The C++ programming language is limited, so it is
                            common to include libraries to add additional capabilities. In this
                            example, we have included the iostream library which provides us
                            with various input/output commands including the cout statement
                            that allows us to output text to the screen.
using namespace std;        The standard library is a collection of functions, constants, and
                            classes that extends the C++ language providing additional
                            functionality. This line says to treat the identifiers (function,
                            constant, class names) in the standard library as though they are part
                            of the main program. This line should be used in almost every
                            program after your include statements.
main ( )                    All C++ code is located in containers called functions. All
                            programs will have a function named main which executes first
                            when you run the program. Functions will be explained in detail
                            later when you get to the chapter on writing functions.
{                           The open brace begins the function (container) which holds the
                            program. It will always be located immediately after a function
                            header – i.e. main().
  cout << "Hello World!";   This is really the first and only line of code in our program. The
                            cout (console out) statement tells the program to output text to the
                            screen. The text to be output is contained within double quotes.
                            Most C++ statements are terminated with a semicolon.
}                           The close brace terminates the function containing the code.

Although the previous "Hello World" program should compile without any errors, C++ standards say that
the main() function should have an int return type and return 0 at the end of the program. The corrected
program is shown below.

Program 4.3b – Corrected Hello World Program to Conform to C++ Standards

#include <iostream>
using namespace std;

int main()
{
  cout << "Hello World!\n";
  return 0;
}

Output
Hello World!


Note: To keep program listings compact, this book may often omit the int before main() and the return 0
at the end of the program.
20   Chapter 5 – Cout Statement


                             Chapter 5 – Cout Statement
5.1 Basic Cout Statement
One of the first things to learn in C++ is how to print text to the screen. This may be done using the cout
(console out) statement, which is used to output text, variables, and mathematical expressions to the
screen. This statement is located in the iostream.h library which must be included at the top of your
program. The cout statement is followed by << then the text to output. All cout statements should be
terminated with a semi-colon.

Program 5.1 - Basic Cout Statement

#include <iostream>
using namespace std;
main()
{
  cout << "Hello World! ";
  cout << "This is one my first programs.";
}

Output
Hello World! This is one of my first programs.


5.2 Printing a Newline
You may have noticed that the two sentences in the previous program printed on the same line. Just
because you put a second cout statement on the next line does not cause your output to skip to the next
line. The following programs show the two ways to print a newline after the first sentence. Both
programs output the same thing.

Program 5.2 – Two Ways to Print a Newline

#include <iostream>
using namespace std;
main()
{
  cout << "Hello World!\n";
  cout << "This is one my first programs.";
}

#include <iostream.h>
using namespace std;
main()
{
  cout << "Hello World!";
  cout << endl;
  cout << "This is one my first programs.";
}

Output
Hello World!
This is one of my first programs.
                                                                        Chapter 5 – Cout Statement        21


The first program used a "\n" to skip to a new line. The second program uses an endl (endline) to skip
to the next line. The cout statement below shows how to combine both lines using a \n in between.

cout << "Hello World!\nThis is one of my first programs";

Important to Remember: The \n must be within double quotes whereas the endl does not.

5.3 Printing Variables
In addition to printing text, you may use cout statements to output variables. Variables are covered in
more detail in chapter 6. In the following program, two integer variables (A and B) are declared and
assigned values of 2 and 3, respectively.

Program 5.3 - Printing Variables

#include <iostream>
using namespace std;
main()
{
  int A = 2;
  int B = 3;
  cout << "I will now print the values of A and B.\n";
  cout << A;
  cout << endl;
  cout << B;
  cout << endl;
}

Output
I will now print the values of A and B.
2
3



5.4 Printing Mathematical Expressions

The cout statement is also used for printing mathematical expressions. Numbers and/or variable values
may be added, subtracted, multiplied, and divided as shown in the next program.

Program 5.4a – Printing Mathematical Expressions

#include <iostream>
using namespace std;
main()
{
  cout << 5 + 4 << endl;
  cout << 5 * 4 << endl;
  cout << 9 / 3 << endl;
  cout << 9 – 3 << endl;
  cout << 8 % 5 << endl;
}
22   Chapter 5 – Cout Statement


Output
9
20
3
6
3


There are 5 mathematical operators in C++: addition (+), subtraction (-), multiplication (*), division (/),
and modulus (%). The modulus operator (%) calculates the remainder in a division. If you divide 20 by
3, you will get 6, with a remainder of 2. The following cout statement will print 2:

cout << 20%3;

The next program listing uses variables in the mathematical expressions.

Program 5.4b - Printing Mathematical Expressions

#include <iostream>
using namespace std;

main()
{
  int A =    2;
  int B =    3;
  cout <<    "The product of A and B is ";
  cout <<    A * B;
  cout <<    endl;
  cout <<    "A + B * 4 / 2 is equal to ";
  cout <<    A + B * 4 / 2;
  cout <<    endl;
}

Output
The product of A and B is 6
A + B * 4 / 2 is equal to 8


Order of Operations - In the last mathematical expression in the above program, you do the multiplication
and division before you do the addition. Therefore, A + B * 4 / 2 is equal to 8. Multiplication and
division are calculated (from left to right) before addition and subtraction. Items in parenthesis are
calculated first, however. Therefore, 8 / 4 + 2 * 3 * (1 + 3) is equal to 26.
                                                                       Chapter 5 – Cout Statement         23


5.5 Extending the Cout Statement
Every time you switch between printing variables, text (within quotes), mathematical expressions, or an
endl, you either need to use another cout statement, or extend the cout statement by adding another
<<. The following program is the same as Program 5.3, but with the last cout statement extended.


Program 5.5a – Extending Cout Statements

#include <iostream>
using namespace std;
main()
{
  int A = 2;
  int B = 3;
  cout << "I will now print the values of A and and B.\n";
  cout << A << endl << B << endl;
}

Output
I will now print the values of A and B.
2
3


The final program in this section declares two variables, prints text, mathematical expressions, and uses
one cout statement extended and on multiple lines. When you extend a cout statement to multiple lines,
there is only one semicolon placed at the very end.

Program 5.5b – Extending Cout to Multiple Lines

#include <iostream>
using namespace std;
main()
{
  int X = 4;
  int Y = 5;
  cout << "X * Y = " << X * Y << endl
       << "X + Y = " << X + Y << endl
       << "X - 2 * 3 = " << X - 2 * 3 << endl;
}

Output
X * Y = 20
X + Y = 9
X – 2 * 3 = -2
24     Chapter 5 – Cout Statement



5.6 Comments and Documentation

Whenever you place two backslashes // on a line, any text that follows is ignored by the compiler – it
has no effect on the execution of the program. Comments allow programmers to place information in a
program to explain what is happening. At the top of a program, you could add information on who the
programmer is, what version the program is, etc. It is good practice to add documentation to your
program so that someone else looking at it will understand it. Even if nobody else will ever look at your
program, it is good to document the program for yourself – it is easy to forget what a program does and
how it works when you have not looked at it in a while.

Program 5.6 – Comments

// This program multiplies two numbers.
// Author: David Kirk

#include <iostream>
using namespace std;
main()
{
  int A = 18;    // This is the first number
  int B = 3;     // This is the second number

     cout << "The product of " << A << " and " << B << " is " << A * B << endl;
}

Output
The product of 18 and 3 is 54


Using two backslashes // is the newew C++ style of comments. The older C method of comments uses a
/* to begin the comment, and a */ to end the comment. This allows you to comment out a section of
code, which is useful for debugging. The following program demonstrates this.

Program 5.7 – Alternative method for Comments

#include <iostream>
using namespace std;
main()
{
  cout << "Welcome!\n";

/*
     int A = 18;
     int B = 3;
     cout << "The product of " << A << " and " << B << " is " << A * B << endl;
*/

}

Output
Welcome!
                                                                         Chapter 5 – Cout Statement       25



5.7 Backslash Special Characters

Within the double quotes " " of a cout statement, A backslash \ has a special function. It is always
followed by another character that tells what function it is. You have already learned about printing a
newline using "\n". The following table lists other backslash functions.

                                           Backslash Functions
Code Explanation                             Example Cout Statement                  Output
\n   Used to print a newline which          cout << "A\nB\nC";                       A
     skips to the next line.                                                         B
                                                                                     C
\t      Used to print a tab.                cout << "A\tB\tC";                       A     B          C
\\      Used to print a backslash. This     cout << "c:\\Windows";                   c:\Windows
        must be used since the backslash
        is always followed by another
        character
\"      Used to print a double-quote.       cout << "She said \"hi\".";              She said "hi".
        This must be used since double-
        quotes are used as the container
        for all output.
\e      Sends an escape character –         cout << "\e[2J";                         <clears screen>
        ASCII 27. Often used in escape
        sequences in a telnet window to
        change text colors, cursor
        position, etc. This is discussed
        further in the chapter titled
        "More Input/Output".
26    Chapter 5 – Cout Statement



Exercises – Chapter 5

What will each of the following output?

1.     cout << "Hello" << "World";

2.     int A = 1;
       int B = 3;
       cout << A << " is less than " << B;

3.     int X = 4;
       int Y = 2;
       cout << "X * Y = " << X * Y << endl << "The End";

4.     int Z = 1;
       cout << "Z";

5.     cout << "A" << "B" << endl << "C" << "D";

6.     cout << 5 + 6 * 3 – 2;

7.     cout << (17 + 3) / 4;

8.     int A = 15;
       cout << A % 4;

9.     int B = 50;
       cout << B * (3 – 1) + 20;

10.    cout << "3\t2\t1\tGO!";

11.    cout << "\"apples\"\nare good";

12.    cout << "/---\\\n| \" |\n\\ - /";
                                                                              Chapter 6 – Variables      27



                                   Chapter 6 – Variables
6.1 Variables Defined

Variables are used by programs to store data. Their values can be set, and changed as often as needed.
Before you can use a variable, it must be declared. When you declare a variable, you reserve a memory
location on the computer and assign a name to it. This memory location holds the variable's value. The
following line declares an integer variable named Age.

int Age;

Declaring an integer variable such as this reserves four bytes of memory for storing its value. An integer
is a number without a decimal point – e.g. 3, 1492, -200, 0, or -1. Once the variable is declared, you may
assign it a value. The following line is an example assignment statement.

Age = 25;

The previous line assigns the value of 25 to the variable Age. The next assignment statement adds 5 to
the existing value of Age, thus making it equal to 30.

Age = Age + 5;

Below is a completed program using the integer variable Age.

Program 6.1 – Using Variables

#include <iostream>
using namespace std;
main()
{
  int Age;
  Age = 25;
  Age = Age + 5;
  cout << Age << endl;
}

Output
30

Summary
    Variables are used to store data used in a program.
    Before a variable can be used, it must be declared – you put the variable type followed by the
      variable name. The following example declares an integer variable named Age:
         int Age;
        An assignment statement is used to assign a value to a variable. An assignment statement
         consists of the variable name, an equal sign, and then the new value.
         Age = 25;
        Assignment statements can contain mathematical expressions. They may also use the same
         variable in the expression. The assignment statement below assigns the value of 10 to Age
         (assuming Age was previously equal to 25).
         Age = Age / 5 + 5;
28     Chapter 6 – Variables


6.2 Variable Names

When declaring a variable, you assign it a name (e.g. Age). Legal variable names must begin with a letter
or an underscore, and can contain any combination of letters, numbers, and underscores. Variable names
cannot contain spaces or symbols. Variables cannot be named after C++ keywords – e.g. cout, cin, if,
else, for, while, int, float.

                           Legal Variable Name       Illegal Variable Name
                           X                         cout
                           Car1                      1Car
                           My_Age                    My Age
                           HelloWorld                HelloWorld!

When choosing a variable name, be descriptive. For example, if you are writing an accounting program,
use variable names like Assets and Liability instead of A and L. A good naming convention is to
capitalize each word in your variable names. For example: Height_Pyramid, Width_Pyramid,
Length_Pyramid. Remember, variable names are case sensitive – Age is a different variable than age.

6.3 Variable Types

In the first program, we used the int variable type. An integer is positive or negative whole number
(does not contain a decimal point). The following table lists the different C++ variable types.

                                         C++ Variable Types
Variable Type                  Size      Legal Values        Comments
int                            4 bytes   -2,147,483,648 to   For most compilers, int is the same as
                                         2,147,483,647       long int – a four byte integer.
short int                      2 bytes   -32,768 to 32,767   This is useful for smaller numbers and
                                                             uses half as much memory as a regular
                                                             integer.
unsigned int                   4 bytes   0 to 4,294,967,295 This is useful for larger numbers that are
                                                             not negative.
unsigned short int             2 bytes   0 to 65,535         This is useful for smaller numbers that
                                                             are not negative.
float                          4 bytes   -1.2e -38 to 3.4e38 A float variable has a floating point,
                                                             meaning there is a decimal point with a
                                                             variable number of digits past it – e.g.
                                                             3.34, -123.456, 2.0.
                                               -308      308
double                         8 bytes   -2.2e to 1.8e       Double precision variables are for very
                                                             large numbers, and usually written in
                                                             scientific notation.
bool                           1 byte    true or false       Boolean variables are used for things that
                                                             are either true or false, such as whether
                                                             or not someone is a citizen.
char                           1 byte    one alphanumeric    A char is one alphanumeric digit, as
                                         digit               shown in the ASCII chart.

How do you choose the right variable type? As a general rule, integers are used for numbers without a
decimal point. Floating points are used for numbers that have digits past the decimal point. Double
                                                                               Chapter 6 – Variables       29


precision variables are for very large and small numbers. Character variables are used for storing a single
alpha-numeric character. This includes letters of the alphabet, numbers, symbols, etc. Boolean variables
are used for storing information that is either true or false, such as whether or not you have traveled
abroad.

In choosing a variable type, you should use the type which requires the least amount of memory. As can
be seen in the previous table, an int variable requires twice as much memory as a short int. Should
you be concerned about saving two bytes of memory? For the programs in this book which only declare a
few variables at most, saving memory is not a concern. More advanced programs may declare hundreds,
thousands, or millions of variables – conserving memory is a concern. If there is any chance that the
value you assign to the variable will be larger than its type, use the larger variable type (e.g. use int
instead of short int).

6.4 Using Integer Variables

The next program demonstrates using the int variable.

Program 6.4a – Integer Variable

#include <iostream>
using namespace std;
main()
{
  short int Apple;
  short int Pear;
  Apple = 5;
  Pear = 6;
  cout << Apple * Pear << endl;
}

Output
30


The next program is similar to the previous. Both variables (Apple and Pear) are declared in one line by
separating the variable names with commas. Also, values may be assigned to the variables in the
declaration line.

Program 6.4b – Declaring Multiple Variables and Assigning Values

#include <iostream>
using namespace std;
main()
{
  short int Apple = 5, Pear = 6;
  cout << Apple * Pear << endl;
}

Output
30


Be careful when using integers that you do not assign a value above the largest legal value or below the
smallest legal value. If you do, the value will "wrap around". In the next program, we declare a short
30    Chapter 6 – Variables


int and make it equal to its maximum legal value. Incrementing (adding 1) the variable causes the value
to wrap around and become its smallest legal value.

Program 6.4c – Wrapping Around an Integer

//   A short int variable has a range of -32,768 to 32,767.
//   This program declares a short int variable and makes it
//   equal to the largest value it can be. The program then
//   adds one to the variable to demonstrate what happens
//   when it goes past the upper limit.

#include <iostream>
using namespace std;

main()
{
  short int Test = 32767;
  Test = Test + 1;
  cout << Test << endl;
}

Output
-32768


When you add 1 to the value of a variable, it is called incrementing the variable. When you subtract 1
from the value, it is called decrementing the variable. In the previous program, we increment the variable
Test:

Test = Test + 1;

An easier way to increment Test is to do the following:

Test++;

You can also decrement (subtract 1) a variable by following its name with two minus sings:

Test--;

This is where the C++ programming language gets its name. The C programming language was the
predecessor to C++. Therefore, the next version of C is C + 1, or C++. The title of this book, C++ for
Geniuses-- uses a decrement (minus-minus) on the word "Geniuses", meaning for the not-so-genius. If
you are in fact a genius, then you might want to return the book. If you were a genius, however, then you
would have known this and not purchased the book in the first place. Therefore...
                                                                                 Chapter 6 – Variables     31



6.5 Using Float Variables

For numbers that have a decimal point, the float variable type is used, as shown in the next program.

Program 6.5a – Float Variable

#include <iostream>
using namespace std;
main()
{
  float A = 1.5, B = 2.44, C;
  C = A + B;
  cout << C << endl;
}

Output
3.94


It is good practice to always type the decimal point when using float variables. The next program
demonstrates how failing to type the decimal point may give you unexpected results. When the compiler
divides 1 / 4, it assumes the result is an integer since both variables are integers. To correct the program,
change the assignment statement to: A = 1.0 / 4.0;

Program 6.5b – Remember to Type Decimal Point

#include <iostream>
using namespace std;
main()
{
  float A;
  A = 1 / 4;
  cout << A << endl;
}

Output
0
32    Chapter 6 – Variables



6.6 Using Char Variables

A char variable stores a single alphanumeric character. You must use single quotes when assigning a
char variable a value. The following program demonstrates this variable.


Program 6.6 – Char Variables

#include <iostream>
using namespace std;
main()
{
  char MyGrade = 'A';
  cout << "My Grade is an " << MyGrade << endl;
}

Output
My Grade is an A



Exercises – Chapter 6

What type of variable would be most appropriate for storing each of the
following, keeping in mind to conserve memory whenever possible?
1. Someone's age
2. The balance of your bank account
3. The yearly budget for the U.S.
4. A person's gender
5. A car's odometer reading
6. Whether or not someone has a driver's license
7. The distance in miles to other stars in the galaxy
8. The outdoor temperature

What will each of the following output?

9.     cout << 1 / 4;                                   12.   int Cow = 4, Chicken = 6;
                                                              Cow = (Cow * 4) % 2;
                                                              cout << Chicken * Cow;
10.    cout << 1.0 / 4.0;                               13.   char A = 'B', B = 'A';
                                                              cout << "A" << A << "B" << B;
11.    float Bear = 1.0, Alligator = 1.0;               14.   float A, B = -2.5;
       Alligator++;                                           A = B * 2;
       Bear--;                                                A++;
       cout << Alligator + Bear;                              cout << A;
                                                                              Chapter 7 – Constants       33



                                   Chapter 7 – Constants
7.1 Declared Constants

Declared constants allow you to create a variable that cannot be changed. This is good practice for
numbers that do not change – assigning them to a constant insures that nothing in the program will ever
change their value. The following program demonstrates the use of a declared constant.

Program 7.1 – Declared Constants

#include <iostream>
using namespace std;
main()
{
  const float Pi = 3.1415;
  cout << "Circumference of circle: " << 2 * Pi * 1.4 << endl;
}

Output
Circumference of circle: 8.7962


7.2 Defined Constants

The #define statement is a preprocessor directive to do a string substitution. At the top of your
program, you can type:

#define Pi 3.1415

Inside the program, you can use it as if it were a declared constant:

cout << 2 * Pi * 1.4;

Anywhere your code has a reference to Pi, it is replaced with 3.1415 before the program is compiled. The
following program demonstrates using a defined constant.

Program 7.2 – Defined Constants

#include <iostream>
using namespace std;
#define Pi 3.1415
main()
{
  cout << "Circumference of circle: " << 2 * Pi * 1.4 << endl;
}

Output
Circumference of circle: 8.7962


For most cases, using declared constants (const statement) is preferred over defined constants since the
former has a variable type to associate with.
34   Chapter 7 – Constants



7.3 Enumerated Types

The enumeration command (enum) allows you to define a new type with a defined set of values. The
following line declares a new type named CarTypes and defines its possible values:

enum CarTypes {Corvette, Mustang, Viper, Ferrari, Lamborghini};

You can use this new type (CarTypes) similarly to a variable type. The next program declares the
enumerated CarTypes, and then declares two variables of this type (Car1 and Car2). This program uses
an if statement which is covered in Chapter 9.

Program 7.3 – Enumerated Types

#include <iostream>
using namespace std;
main()
{
  enum CarTypes {Corvette, Mustang, Viper, Ferrari, Lamborghini};
  CarTypes Car1 = Corvette;
  CarTypes Car2 = Ferrari;
  if (Car1 == Corvette)
    cout << "Wise Choice.\n";
}

Output
Wise Choice.


Enumerated types have an integer value. In the previous program, Corvette = 0, Mustang = 1, Viper = 2,
Ferrari = 3, and Lamborghini = 4. Therefore, doing the following would assign the value of 7 to the
integer MyCars:

int MyCars = Ferrari + Lamborghini;

You can assign your own values to enumerated types by doing the following:

enum CarTypes {Corvette=1, Mustang=5, Viper=10, Ferrari=20, Lamborghini=50};
                                                                         Chapter 8 – Cin Statement       35



                              Chapter 8 – Cin Statement
The cin statement is used in programs to allow the user to enter a value for a variable while the program
is running. This statement, like cout, is located in the iostream.h library. The following is an example
cin statement:

cin >> Grapes;

When the program encounters this cin statement, the program pauses, waits for the user to enter a value
on the keyboard, then stores this value in the variable Grapes. You will need to declare the variable
Grapes before you do the cin statement. Notice that the cin statement is followed by two greater than
signs >> while the cout statement is followed by two less than signs <<.

It is good practice to precede a cin statement with a cout statement that lets the user know what they
should enter. Below is the same cin statement, but this time with the variable declaration and a
statement letting the user know what to enter.

cout << "Please enter the number of grapes you want to eat: ";
int Grapes;
cin >> Grapes;

Below is an example complete program using the cin statement. In the output of the program, we
assume the user enters the number 20 when prompted. It is good practice to precede a cin statement with
a cout statement so that you can prompt the user for what they should enter.

Program 8a – Basic Cin Statement

#include <iostream>
using namespace std;
main()
{
  int Grapes;
  cout << "How many grapes would you like to eat? ";
  cin >> Grapes;
  cout << "Why not eat this many: " << Grapes * 2 << endl;
}

Output
How many grapes would you like to eat? 20
Why not eat this many: 40
36    Chapter 8 – Cin Statement


The next program prompts the user for three variables then calculates the volume of a cube using these
values. We assume the user enters the values 1.5, 2.8, and 3.7 for the dimensions.

Program 8b – Multiple Cin Statements

#include <iostream>
using namespace std;
main()
{
  cout << "This program calculates the volume of a cube.\n";
  float Base, Width, Height;
  cout << "Enter the base: ";
  cin >> Base;
  cout << "Enter the width: ";
  cin >> Width;
  cout << "Enter the height: ";
  cin >> Height;
  cout << "The volume is: " << Base * Width * Height << endl;
}

Output
This program calculates the volume of a cube.
Enter the base: 1.5
Enter the width: 2.8
Enter the height: 3.7
The volume is: 15.54



Exercises – Chapter 8

1. Write a program that would have the following output:

     Enter a number to convert from inches to centimeters: 4
     This is equal to 10.16 centimeters.

2. Write a program that would have the following output:

     Enter your age: 21
     Enter your weight: 150
     You still have 79 years before you are 100.
     You can still gain 350 pounds before you weigh 500.
                                                                        Chapter 9 – If…Else Statement        37



                            Chapter 9 – If...Else Statement
9.1 Basic If Statement
The if statement is used to test a condition and offer a branch in the program depending on the result of
the test. The next program shows how to use a basic if statement. This program asks the user to enter a
number. If the number they enter is greater than 5, then the program outputs, "Your number is greater
than 5." Otherwise, the program will not output anything.

Program 9.1 - Basic If Statement

#include <iostream>
using namespace std;
main()
{
  int A;
  cout << "Enter an integer: ";
  cin >> A;
  if (A > 5)
    cout << "Your number is greater than 5.\n";
}

Output
Enter an integer: 9
Your number is greater than 5.


In preceding program, immediately following the if statement is the condition (A > 5). A condition
either evaluates to true or false. If the condition is true, then the line following the condition is executed.
If the condition is false, the program will skip this line. Notice there is no semicolon after the if
statement. The if statement technically ends after the cout statement.

9.2 If...Else Statement
Immediately following an if statement, we can add an else statement as shown in the next program.
For the output, we run the program twice. In the first output, we assume the user enters a 9 at the cin
statement. In the second output, we assume the user enters a 3.
38   Chapter 9 – If…Else Statement



Program 9.2a - If...Else Statement

#include <iostream>
using namespace std;
main()
{
  int A;
  cout << "Enter an integer: ";
  cin >> A;
  if (A > 5)
    cout << "Your number is greater than 5.\n";
  else
    cout << "Your number is less than or equal to 5.\n";
}

Output 1
Enter an integer: 9
Your number is greater than 5.

Output 2
Enter an integer: 3
Your number is less than or equal to 5.


With an if...else statement, only one of the two cout statements will execute - not both. The next
program shows how to use the "is equal to" comparison.

Program 9.2b – Equal To Comparison

#include <iostream>
using namespace std;
main()
{
  int Number, Option, Total;
  cout << "Enter an integer: ";
  cin >> Number;
  cout << "Choose an option, 1 = square number, 2 = cube number : ";
  cin >> Option;
  if (Option == 1)
    Total = Number * Number;
  else
    Total = Number * Number * Number;
  cout << "The answer is " << Total << endl;
}

Output
Enter an integer: 3
Choose an option, 1 = square number, 2 = cube number : 2
The answer is 27


In the previous program, we assume the user entered 3 for the integer, and chose option 2 to cube the
number. Therefore, the else statement executes since the variable Option is not equal to 1.
                                                                     Chapter 9 – If…Else Statement       39


9.3 Comparison Operators
The following table shows all the comparison operators that can be used with an if statement.

                                     Comparison Operators
                              Operator   Description
                              <          Less than
                              >          Greater than
                              <=         Less than or equal to
                              >=         Greater than or equal to
                              ==         Equal to
                              !=         Not equal to



Important: It is a common mistake to forget to use two equal signs == when testing for equality. If you
accidentally use only one equal sign, it will not cause a syntax error, but your program will probably not
work the way you were hoping. Using a single equal sign in a condition is an assignment statement. As
shown below, you will assign a value to the variable. If the value you are assigning is 0, then the
condition evaluates to false. Otherwise, it evaluates to true.

if (Option = 5)              // This assigns 5 to Option and evaluates to true

if (Option = 0)              // This assigns 0 to Option and evaluates to false

Again, always remember to use two equal signs == in you condition when testing for equality.

if (Option == 5)             // The proper condition tests to see of Option equals 5
40   Chapter 9 – If…Else Statement


The program below uses all of the comparison operators. In this program, we assume the user enters 75
for the value of A. The only condition that does not evaluate to true is: if (A <= 40).


Program 9.3 – All Comparison Operators

#include <iostream>
using namespace std;

main()
{
  int A;
  cout << "Enter a value for A: ";
  cin >> A;
  if (A > 5)
    cout << "A is greater than 5.\n";
  if (A < 100)
    cout << "A is less than 100.\n";
  if (A >= 50)
    cout << "A is greater than or equal to 50.\n";
  if (A <= 40)
    cout << "A is less than or equal to 40.\n";
  if (A == 75)
    cout << "A is equal to 75.\n";
  if (A != 20)
    cout << "A is not equal to 20.\n";
}

Output
Enter a value for A: 75
A is greater than 5.
A is less than 100.
A is greater than or equal to 50.
A is equal to 75.
A is not equal to 20.
                                                                     Chapter 9 – If…Else Statement      41



9.4 Using Braces with the If Statement
In the preceding programs, we only have one cout statement to execute after each if statement. If you
have multiple statements to execute on the condition of an if or an else, then you will need to use
braces after these statements. Many programmers will always use braces for clarity. The next program
shows how to use an if statement to ask the user what they want the program to do.

Program 9.4 – If...Else Statement with Braces

#include <iostream>
using namespace std;
main()
{
  int Choice;
  cout << "Select one of the following:\n";
  cout << " (1) Calculate the area of a circle.\n";
  cout << " (2) Calculate the area of a triangle.\n";
  cout << "Your choice: ";
  cin >> Choice;
  if (Choice == 1)
  {
    float R;
    cout << "Enter a radius: ";
    cin >> Radius;
    cout << "The area is " << 3.14 * R * R << endl;
  }
  else
  {
    float Base, Height;
    cout << "Enter the base: ";
    cin >> Base;
    cout << "Enter the height: ";
    cin >> Height;
    cout << "The area is " << 0.5 * Base * Height << endl;
  }
}

Output
Select one of the following:
(1) Calculate the area of a circle.
(2) Calculate the area of a triangle.
Your choice: 1
Enter a radius: 2
The area is 12.56


In the previous program, notice that after each opening brace, the lines following are indented.
Indentation after braces shows the different levels in your program – similar to indentation in a table of
contents. Indentation will not change the way your program executes – it is intended to make the source
code more readable. You may choose how many spaces to indent, or to insert a tab. Some editors like in
Visual C++ will indent your program automatically when you insert braces.
42   Chapter 9 – If…Else Statement



9.5 Logical Operators: AND, OR, and NOT
When you have multiple conditions that all must be true, then you will need to use the logical AND (&&)
operator within the condition. The next program demonstrates this.

Program 9.5a – Logical AND Operator

#include <iostream>
using namespace std;
main()
{
  int A;
  cout << "Enter a value for A: ";
  cin >> A;
  if (A >= 1 && A <= 10)
    cout << "A is between 1 and 10\n";
  else
    cout << "A is not between 1 and 10\n";
}

Output
Enter a value for A: 7
A is between 1 and 10


In the previous program, both conditions must be true to execute the first cout statement –
(A >=1) and (A <=10). If one or both of the conditions are false, then the second cout statement will
execute. Notice that each of the conditions is evaluated before the logical AND operator. Although it is
not necessary, you can use addition parentheses in your condition as shown below.

if ((A >= 1) && (A <= 10))

When testing multiple conditions in which only one needs to be true, then you will need to use the logical
OR (||) operator. This is typed using two vertical bars, or pipe symbols – above Enter on your
keyboard. With a logical OR, at least one of the conditions must be true for the condition to evaluate to
true. The next program demonstrates the logical OR.

Program 9.5b – Logical OR Operator

#include <iostream>
using namespace std;
main()
{
  int A;
  cout << "Enter a number between 1 and 10: ";
  cin >> A;
  if (A == 2 || A == 4 || A == 6 || A == 8 || A == 10)
    cout << "Your number is even.\n";
  else
    cout << "Your number is odd.\n";
}
                                                                       Chapter 9 – If…Else Statement          43


Output
Enter a number between 1 and 10: 7
Your number is odd.


A third operator is the logical NOT (!). This will negate any condition it is placed in front of – i.e. the
condition will evaluate to the opposite value. The example below demonstrates this.

if (!(A == 1))             // Evaluates to false if A is equal 1, and true otherwise

The words true and false may be used in a condition. This might be useful if you are testing a program
and need a condition to always evaluate to true or false – you can temporarily substitute the condition
with the word true or false. The following cout statement will always execute:

if (true)
  cout << "This will always print";

9.6 Ternary Conditional Operator

The conditonal or ternary operator allows you to put an if...else statement in an assignment
statement. The statement below uses this conditional operator to convert the variable Number to its
absolute value.

                                  Value if         Value if
               Condition        conditon true      condition false


Number = (Number > 0) ? Number : -1 * Number;

After the equal sign on the above assignment statement is a condition (Number > 0). If the condition is
true, then the expression after the question mark (Number) will be assigned to Number. If the condition is
false, then the expression after the colon (-1 * Number) will be assigned to Number.
The next program demonstrates use of the ternary conditional operator.

Program 9.6 – Ternary Conditional Operator

#include <iostream>
using namespace std;
main()
{
  char Choice;
  int Donuts;
  cout << "Please select an option\n";
  cout << "1 = eat a dozen donuts\n";
  cout << "2 = eat a half dozen donuts\n";
  cout << "Your choice: ";
  cin >> Choice;
  Donuts = (Choice == 1) ? 12 : 6;
  cout << "Have fun eating " << Donuts << " donuts.\n";
}
44   Chapter 9 – If…Else Statement


Output
Please select an option
1 = eat a dozen donuts
2 = eat a half dozen donuts
Your choice: 1
Have fun eating 12 donuts.
                                                                  Chapter 9 – If…Else Statement     45



Exercises – Chapter 9

What will each of the conditions evaluate to – true or false?
Assume the following: X = 5, Y = 8, Z = 20
1.    (X == 8)
2.    (Z != 20)
3.    (X == 3 || Z < 50)
4.    (Z == 20 && Y < 10)
5.    (!(Y >=6 && Y <=10))
6.    ((X != 5 || Y != 8) && Z == 20))
7.    ((X > 1 && Y > 10) || (Z <= 19 && Z >= 21))
8.    (X <= 5 && !(Z > 25))
9.    (!(Y > -5) || !(Z > -5))
10. (Z = 15 && Y = 10)


What will each of the following output?

11.       int A =    1;
          if (A >    0)
             cout    << "Yes";
          else
             cout    << "No";


12.       float B = 1.0, C = 2.0;
          if (C <= B)
             cout << "Apple";
          else
             cout << "Pear";


13.       bool X = false, Y = true, Z = true;
          if (Y && (X || Z))
             cout << "Yes";
          else
             cout << "No";


14.       int I =    4, J = -2, K = 0;
          if (!(J    < I) && !(K >= J))
             cout    << "red";
          else
             cout    << "blue";


15. Write a program that prompts the user to enter an integer. Let the user know whether their number
is evenly divisible by 2, 3, and 4.
46   Chapter 10 – Switch Statement



                          Chapter 10 – Switch Statement
The switch statement can used as an alternative to if...else statements when the value of a single
variable needs to provide multiple choices. The following code demonstrates the switch statement.

switch(Day)
{
   case 1:
      cout <<     "Sunday";
      break;
   case 2:
      cout <<     "Monday";
      break;
   case 3:
      cout <<     "Tuesday";
      break;
   case 4:
      cout <<     "Wednesday";
      break;
   case 5:
      cout <<     "Thursday";
      break;
   case 6:
      cout <<     "Friday";
      break;
   case 7:
      cout <<     "Saturday";
      break;
   default:
      cout <<     "Invalid Day";
}

As can be seen in the previous switch statement, the optional default statement can be included to
provide a branch if none of the other cases execute. In a switch statement, it is not necessary to use
braces for each case, even if you have multiple lines of code to execute. It is important to remember to
put a break after each case, otherwise all remaining cases will execute. The next program demonstrates
another switch statement.
                                                   Chapter 10 – Switch Statement   47



Program 10.1 – Switch Statement

#include <iostream>
using namespace std;

main()
{
  short int Year;
  cout << "Enter a year to see any famous events: ";
  cin >> Year;
  switch(Year)
  {
    case 1492:
       cout << "Columbus sailed the ocean blue.\n";
       break;
    case 1776:
       cout << "The United States comes into being.\n";
       break;
    case 1963:
       cout << "Kennedy assassinated.\n";
       break;
    case 1969:
       cout << "First person lands on the moon.\n";
       break;
    case 2002:
       cout << "Learning C++ for Geniuses-- is written.\n";
       break;
    default:
       cout << "No famous events this year.\n";
  }
}

Output
Enter a year to see any famous events: 1969
First person lands on the moon.
48   Chapter 11 – Using Libraries and Functions



               Chapter 11 – Using Libraries and Functions
11.1 Functions Defined

A function is a program or subroutine that may be used (or called) in any program you write. There are
many libraries that may be included in your programs, each containing many different functions. For
example, if you need to calculate the square root of a number, you do not need to write the code to make
this calculation since there is already a function developed to do this. Functions are a method of making
code reusable --- code that may be used in many different programs.

Some software companies have developed and sell libraries of functions for various purposes. For
example, suppose you need to have your C++ draw bar and pie charts. Instead of developing the
programs yourself for drawing these, you could find a library already developed for this purpose. In a
later chapter, you will learn how to create your own functions and libraries.

Below is an example function call. This is the square root function that is located in the <math.h> library.

cout << sqrt(25);

The above statement will output the number 5. When you use this function, you put the name of the
function (sqrt), and then in parenthesis you put what number to take the square root of (e.g. 25). The
function call returns the number 5.

11.2 Using Math.h Functions

The math.h library contains many arithmetic functions such as sine, cosine, square root, and natural
logarithm. The following program shows how to include the math.h library and use (or call) its square
root function.

Program 11.2a - Using the Square Root Function

#include <iostream>
#include <math.h>
using namespace std;

main()
{
  float A;
  A = sqrt(16);
  cout << A << endl;
}

Output
4


In the previous program, we must include the math.h library at the top to gain access to its functions. In
this program, we use (or call) the square root function. The function name is sqrt. We send this function
a number (16) to use for calculating the square root. The information you send the function is always
enclosed in parenthesis and is called the parameter(s) or argument(s). The square root function
                                                          Chapter 11 – Using Libraries and Functions          49


calculates the square root of 16 and returns the answer to your program. In this program, the A will be
assigned the value of 4.

Remember, functions are separate programs that you call from your main program. You send them
information (the parameters), and they return a result. The information they return is always of a
particular variable type such as int, string, float, etc. The next program uses the power function. It will
raise the first number (2) to power of the second (5). When using a function that takes two parameters,
separate the numbers by a comma.

Program 11.2b – Using the Power Function

#include <iostream>
#include <math.h>
using namespace std;

main()
{
  int A;
  A = pow(2,5);
  cout << A << endl;
}

Output
32


The following table lists some of the functions found in the math.h library.

                       Common Math.h Functions
Function        Comments
sqrt(n)         Calculates the square root of n.
pow(n, p)       Raises n to the power of p.
exp(n)          Calculates the exponential function – en.
log(n)          Calculates the natural logarithm using n.
sin(n)          Calculates the sine of n (in radians).
cos(n)          Calculates the cosine of n (in radians).
tan(n)          Calculates the tangent of n (in radians).
floor(n)        Rounds n down to the nearest integer – floor(1.6) is 1.
ceil(n)         Rounds n up to the nearest integer – ceil(2.45) is 3.
50   Chapter 11 – Using Libraries and Functions



11.3 Using Stdlib.h Functions
This section lists some of the functions in the stdlib.h library. One useful function contained in stdlib.h is
system( ). This function allows you to execute an operating system command. How you use it depends
on what operating system your compiler is located. This function does not return a value and should be
placed on a line by itself. The following program assumes you are running your program on a Linux
system and shows how to execute the date command.

Program 11.2 – Using the System Function

#include <iostream>
#include <stdlib.h>
using namespace std;

main()
{
  cout << "The date and time is:\n";
  system("date");
}

Output
The date and time is:
Sun Aug 4 14:18:43 CDT 2002


The following table lists some of the functions found in the stdlib.h library.

                               Common Stdlib.h Functions
Function          Comments
system(s)         Execute operating system command s.
itoa(n)           Convert integer n to a string.
atoi(s)           Convert string s to an integer.
atof(s)           Convert string s to a double.
rand()            Generate a random number (discussed in Random Numbers chapter).
srand()           Seed random number generator (discussed in Random Numbers chapter).
min(n1, n2)       Returns smallest of n1 and n2.
max(n1, n2)       Returns largest of n1 and n2.
abs(n)            Calculates absolute value of integer n.
                                                         Chapter 11 – Using Libraries and Functions      51



Exercises – Chapter 11

1. Write a program that prompts the user to enter two integers, and then outputs the first number raised to
the power of the second.

2. Write a program that would have the following output:

  a = Calculate       sine
  b = Calculate       cosine
  c = Calculate       tangent
  Please select       an option: b

  Enter a value: 2

  The cosine of 2 is -0.416147

3. What is wrong with the following statement?

  char A = sqrt(9);
52       Chapter 12 – While Loop



                                   Chapter 12 – While Loop
12.1 Basic While Loop

Loops allow one or more lines of code within your program to execute multiple times. Below are a few
examples of how a loop could be used in a program.

          Have a program execute over and over again, after prompting the user if they want to run it again.
          Have a program print the numbers 1 through 1000.
          Have a program calculate the factorial of a number (e.g. 10! = 10*9*8*7*6*5*4*3*2*1).

This chapter will examine the while loop and the next chapter looks at the for loop.

The while statement is followed by a condition (like the if statement). The code that will be executed
multiple times (looped) is contained within braces. This code will execute as long as the condition
evaluates to true. The following code demonstrates a simple while loop that prints the word "Hello"
five times: HelloHelloHelloHelloHello.

int A = 1;
while (A <= 5)
{
  cout << "Hello";
  A++;
}

In the previous code, we declared a variable A and assigned it a value of 1. The condition tells the while
loop to execute the code within the braces as long as A is less than or equal to 5. Within the braces, the
cout statement prints "Hello" and the A++ statement increments A. The next complete program shows
another while loop. On the right side is the same program without using a loop.

Program 12.1 – While Loop

#include <iostream>                       // The same program without using a loop
using namespace std;                      #include <iostream>
main()                                    using namespace std;
{                                         main()
  int B = 1;                              {
  while (B < 5)                             cout << "Hello\n";
  {                                         cout << "Hello\n";
    cout << "Hello\n";                      cout << "Hello\n";
    B++;                                    cout << "Hello\n";
  }                                         cout << endl;
  cout << endl;                           }
}

Output
Hello
Hello
Hello
Hello
                                                                          Chapter 12 – While Loop      53



In the previous program, we declared a variable B and assigned a value of 1. The condition on the while
loop says to execute the code within braces as long as B is less than 5.

12.2 Infinite Loops

Be careful when programming with loops that you do not create a program with an infinite loop. An
infinite loop is one in which the condition will always be equal to true. The following program
demonstrates an infinite loop.

Program 12.2 – Infinite Loop

// If you run this, you will have to manually stop the program
#include <iostream>
using namespace std;

main()
{
  int Z = 5;
  while (Z > 1)
  {
    cout << Z;
    Z++;
  }
}

Output
5678910111213141516171819202122232425262728293031323334353637383940
4142434445464748495051525354555657585960616263646566676869707172737
475767778798081828384858687888990919293949596979899100101102103...


In the preceding program, we declared a variable Z and made it equal to 5. The condition in the while
loop says to execute as long as Z is greater than one. Since we increment Z during each iteration (Z++), Z
will always be greater than 1. If you ran this program, then you may be wondering how to stop it – this is
covered in the sequel C++ for Geniuses++. Just kidding!! Terminating a program that is in an infinite
loop will depend on the compiler you are using. You can try pressing Ctrl-C. If this does not work, then
you may need to close the window that is running the program. If this does not work, then it may be time
to buy a new computer.
54   Chapter 12 – While Loop



12.3 Using While Loops for Menus

A while loop can be used for writing a program that contains a menu of options for the user. The loop
will allow you to create a program that will keep running until the user selects the option to exit. In the
next program, the while loop will keep looping until the user enters 5 to exit.

Program 12.3 – While Loop for Menus

#include <iostream>
using namespace std;

main()
{
  short int Choice = 0;
  while (Choice != 5)
  {
    cout << "1 = See the highest mountain\n";
    cout << "2 = See the second highest mountain\n";
    cout << "3 = See the third highest mountain\n";
    cout << "4 = See the fourth highest mountain\n";
    cout << "5 = Exit\n";
    cout << "Enter your choice: ";
    cin >> Choice;
    if (Choice == 1)
       cout << "Everest\n";
    if (Choice == 2)
       cout << "K2\n";
    if (Choice == 3)
       cout << "Kangchenjunga\n";
    if (Choice == 4)
       cout << "Lhotse\n";
    cout << "-----------------------------------\n";
  }
  cout << "Hope you enjoyed this mountain trivia!\n";
}

Output
1 = See the highest mountain
2 = See the second highest mountain
3 = See the third highest mountain
4 = See the fourth highest mountain
5 = Exit
Enter your choice: 2
K2
-----------------------------------
1 = See the highest mountain
2 = See the second highest mountain
3 = See the third highest mountain
4 = See the fourth highest mountain
5 = Exit
Enter your choice: 5
-----------------------------------
Hope you enjoyed this mountain trivia!
                                                      Chapter 12 – While Loop   55



Exercises – Chapter 12

What will each of the following while loops output?

1.   int A = 1;
     while (A < 5)
     {
        cout << A;
        A++;
     }

2.   int B = 5;
     while (B >= 0)
     {
        cout << B;
        B--;
     }

3.   int A = 1, B = 6;
     while (A <= 7)
     {
        cout << A + B << " ";
        A++;
        B--;
     }

4.   int X = 2;
     while (X <= 128)
     {
        cout << X << " ";
        X = X * 2;
     }

5.   int X = 1;
     char Y = '*';
     while (X <= 12)
     {
        cout << Y;
        X = X + 2;
     }

6.   int J = 10;
     while (J >= 0)
     {
        if ((J % 2) == 0)
           cout << "yes ";
        else
           cout << "no ";
        J--;
     }
56   Chapter 13 – For Loop



                                   Chapter 13 – For Loop
13.1 Basic For Loop

The for loop can be used similarly to the while loop. Along with the condition, the for loop allows
you to put a variable declaration and an increment. Using a for loop can save you a few lines of code.
You may use either loop for most situations. The following is an example for loop:

       Variable
      Declaration     Condition    Increment


for (int X = 1; X <= 10; X++)
{
  cout << X;
}

The previous for loop will print: 12345678910. After the for statement, there are three items within
the parentheses: (1) The variable declaration - you may declare a variable and assign it a value, (2) The
condition – it will loop as long as this condition is true, (3) The increment – this is actually an assignment
statement. Example increments are: X++, X--, X=X+2, X=X*2. The next program demonstrates a
basic for loop.

Program 13.1 – Basic For Loop

// Using a For Loop to count from 10 to 1                     // Same program with a While Loop
#include <iostream>                                           #include <iostream>
using namespace std;                                          using namespace std;

main()                                                        main()
{                                                             {
   for (int Count=10; Count >= 1; Count--)                      int Count = 10;
   {                                                            while (Count >= 1)
     cout << Count;                                             {
   }                                                              cout << Count;
   cout << endl;                                                  Count --;
}                                                               }
                                                                cout << endl;
                                                              }

Output
10987654321
                                                                                Chapter 13 – For Loop      57



13.2 Using For Loops with Mathematics

Using a for loop may be helpful in certain mathematical calculations. One example is to write a program
that calculates the factorial of a number. As you recall, 6! means to multiply 6*5*4*3*2*1. The next
program prompts the user for a number, and then calculates the factorial of that number.

Program 13.2 – For Loop for Calculating Factorials

#include <iostream>
using namespace std;

main()
{
   int Num, Answer;
   cout << "This program calculates factorials\n";
   cout << "Please enter an integer: ";
   cin >> Num;
   Answer = 1;
   for (int X = 1; X <= Num; X++)
   {
       Answer = Answer * X;
   }
   cout << Num << "! is equal to " << Answer << endl;
}

Output
This program calculates factorials
Please enter an integer: 6
6! is equal to 720


In the preceding program, we first declare two integers – Num to store the number the user inputs, and
Answer to store the store the answer (factorial of Num). We then prompt the user to enter an integer for
calculating a factorial. In the for loop, the variable X goes from 1 to 6 (the value of Num). Therefore,
the loop does the following:

Answer   =   Answer   *   1;
Answer   =   Answer   *   2;
Answer   =   Answer   *   3;
Answer   =   Answer   *   4;
Answer   =   Answer   *   5;
Answer   =   Answer   *   6;       // This gives us Answer = 1 * 2 * 3 * 4 * 5 * 6


13.3 Additional Information About Loops and Program Flow

There is a third loop not covered in this book – the do...while loop. It is very similar to the while
loop except that the condition is located at the end of the loop. The condition is not tested until the loop
executes once.

Remember the order in which a for and while loop executes: The condition is tested first. If it is false,
then the program will bypass the loop and go to the next line of code after the loop (after the braces).
58   Chapter 13 – For Loop


Otherwise, all statements within the braces are executed. After each loop iteration, the condition is tested
again to determine if the loop should continue executing.

Take note of the ending value of variables used as increments in loops. Look at program 12.1. What is
the value of the variable Count at the end of the program? There may be a tendency to say 1, but the
correct answer is 0. Remember that Count must be decremented (Count--) down to 0 before the condition
(Count >=1) evaluates to false.

There are two statements that may be used in loops: break and continue. Many instructors will advise
against using these because they can cause a program to be more difficult to understand. The break
statement will cause the loop to terminate immediately. The following code will print: 123456.

for (int Counter=1; Counter<10; Counter++)
{
  cout << Counter;
  if (Counter > 5)
    break;
}

The continue statement will cause a loop to immediately begin again (next iteration). The following
code will print: 5566778910.

for (int A=5; A<=10; A++)
{
  cout << A;
  if (A > 7)
    continue;
  cout << A;
}

The goto statement is also often advised against using since it causes such a dramatic change in the flow
of your program. It can be a useful debugging tool, however. The goto statement will cause the
program to skip immediately to the specified label. The following code will print: 1 4.

cout << "1     ";
goto Here;
cout << "2     ";
cout << "3     ";
Here:
cout << "4     ";



Exercises – Chapter 13

What will each of the following for loops output?

1.   for (int A=1; A<=5; A++)
     {
        cout << A << " ";
     }


2.   for (int A=10; A>0; A--)
                        Chapter 13 – For Loop   59


{
    cout << A << " ";
}
60   Chapter 13 – For Loop


3.   for (int Z=2; Z<=20; Z=Z+2)
     {
        cout << Z;
     }


4.   for (float X=100; X>=0; X = X / 2 - 2)
     {
        cout << X << " ";
     }


5.   int A = 1;
     for (int X=1; X<5; X++)
     {
        A = A * 2 – X;
     }
     cout << A;

6.   for (int I=1; I<=5; I++)
     {
        for (int J=1; J<=I; J++)
        {
           cout << "*";
        }
        cout << endl;
     }

7.   Write a for loop that will print the following series of numbers:

     3 6 9 12 15 18 21

8.   Write a for loop that will print the following series of numbers:

     4 2 0 -2 -4

9.   Write a for loop that will print the following series of numbers:

     1 3 7 15 31 63 127

10. Write nested for loops (similar to exercise 6) that print the following:

     *****
     ****
     ***
     **
     *
                                                                                 Chapter 14 – Arrays       61



                                     Chapter 14 – Arrays
14.1 One Dimensional Arrays

Sometime you may need to write a program that uses many variables. Perhaps the program will need ten
or even ten thousand variables. Perhaps you are working with a program that reads a large quantity of
data from a scientific instrument and performs statistics on this data. In any case, it would be inefficient
to declare so many variables. It would be even more difficult working with these variables in the
program. This is where you would use an array – a set of variables, all declared using one name. The
following line declares an array of 10 integers:

int MyArray[10];

The first element, or integer, in the array is numbered 0. The last element is numbered 9. To assign the
value of 42 to the first element, and the value of 61 to the second element, you would do the following
assignment statements:

MyArray[0] = 42;
MyArray[1] = 61;

You can declare an array and assign values to the entire set of elements in one line by doing the
following:

int MyArray[10] = {42, 30, 16, 8, 27, 38, 99, 81, 7, 61};

Since the elements are numbered, arrays are ideal for using within loops to process the data. The
following for loop will print all elements of the previously declared array:

for (int X=0; X<=9; X++)
  cout << MyArray[X] << endl;

The following complete program demonstrates using this array.

Program 14.1a – One Dimensional Array

#include <iostream.h>

main()
{
  int MyArray[10] = {42, 30, 16, 8, 27, 38, 99, 81, 7, 61};
  cout << "Here are the elements in the array:\n";
  for (int X=0; X<=9; X++)
    cout << MyArray[X] << " ";
  cout << endl;
}

Output
Here are the elements in the array:
42 30 16 8 27 38 99 81 7 61
62   Chapter 14 – Arrays


You can use a for loop to parse through the elements not only for printing, but also for totaling their
values. The next program uses the same ten element array and calculates the average of the elements. We
declare a variable named Total and assign it a value of 0. The for loop steps through the array and adds
the value of each element to the variable Total. To calculate the average, simply divide Total by 10.0.

Program 14.1b – Calculating Averages Using Arrays

#include <iostream.h>
main()
{
  int MyArray[10] = {42, 30, 16, 8, 27, 38, 99, 81, 7, 61};
  int Total = 0;
  for (int X=0; X<=9; X++)
    Total = Total + MyArray[X];
  cout << "The average of the array elements is: "
       << Total / 10.0 << endl;
}

Output
The average of the array elements is: 40.9



14.2 Multidimensional Arrays

Arrays can have more than one dimension. For example, a two dimensional array can be used for storing
information in a spreadsheet that contains               Coffee   Espresso     Cappuccino Mocha
rows and columns. Take a look at this      Oct. Sales    152      73           97             44
table of sales data from a coffee shop.    Nov. Sales 166         76           123            49
We could declare a two dimensional array   Dec. Sales 189         89           118            51
for storing these numbers as shown in the
following line:

int Sales[3][4] = {{152, 73, 97, 44},{166, 76, 123, 49},{189, 89, 118, 51}};

The following program will calculate the total sales of beverages for December.

Program 14.2 – Two Dimensional Array

#include <iostream.h>
main()
{
  int Sales[3][4] = {{152, 73, 97, 44},{166, 76, 123, 49},{189, 89, 118, 51}};
  int TotalSales = 0;
  for (int Y=0; Y<=3; Y++)
    TotalSales = TotalSales + Sales[2][Y];
  cout << "Total December beverage sales was " << TotalSales << endl;
}

Output
Total December beverage sales was 447
                                                                                 Chapter 14 – Arrays      63


Exercises – Chapter 14

1. Write a C++ line to declare an array of integers named Corvettes with 5 elements and assign them the
following values: 1956, 1963, 1968, 1983, 1997.



2. Write a C++ line to declare an array named Days with the following values: Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday, Sunday.



3. Given the following array, write a for loop that increments each element:
short int Scores[10] = {100,40,30,90,75,60,100,0,25,80};




4. Using the array declared in the previous exercise, write a for loop that adds all the elements and stores
the sum in the variable Total.
64   Chapter 15 – Strings



                                   Chapter 15 – Strings
15.1 String Variables
A string is a group of characters such as "Hello" or "I am 21 today". Strings are enclosed in double
quotes – unlike character variables which are enclosed in single quotes. Strings are actually character
arrays. To use strings, you must include the string library at the top of your program:

#include <string>

Note: Using Microsoft Visual C++ you must do the following at the top of your program:

#include <iostream>
#include <string>
using namespace std;

The following program shows how to declare a variable of type string, assign it a value (Hello World!),
and print it out.

Program 15.1a – Declaring and Using a String

#include <iostream.h>
#include <string>
main()
{
  string A = "Hello World!";
  cout << A << endl;
}

Output
Hello World!


The next program shows how strings can be concatenated (joined together) using the plus sign. Notice
how a space between the two words was included by placing it in the double quotes " ".


Program 15.1b - Concatenating Strings

#include <iostream.h>
#include <string>
main()
{
  string A = "Hello";
  string B = "World";
  string C = A + " " + B + "!";
  cout << C << endl;
}

Output
Hello World!
                                                                                   Chapter 15 – Strings      65


Strings can be compared. The next program compares "apple" to "apricot" to see which one is greater.
When comparing strings, the ASCII number for each letter is compared (refer to the ASCII chart). Try
running the same program with "Apricot" capitalized.

Program 15.1c - Comparing Strings

#include <iostream.h>
#include <string>
main()
{
  string A = "apple";
  string B = "apricot";
  if (A < B)
    cout << A << " is less than " << B << endl;
  else
    cout << A << " is greater than " << B << endl;
}

Output
apple is less than apricot


15.2 String Functions
When you include the string library at the top of your program, you also have access to many functions
that allow you to work with strings. Example functions include the ability to search a string for a letter or
letters, the ability to insert text within a string, and the ability to print a portion of a string. The string
type is actually a class and its functions are actually called methods. Classes and methods are discussed
in later chapters.

Size

The size function allows you to count the total number of characters in a string. Remember to count
spaces. The following program demonstrates this function.

Program 15.2a - String Size

#include <iostream.h>
#include <string>

main()
{
  string A = "Hello World!";
  cout << A.size() << endl;
}

Output
12


All the string functions are called by placing a period after the string variable name followed by the
function name (size). After the function name, are open and close parentheses. With the size function,
there are no parameters. With most other string functions, however, there will be parameters to send the
function.
66   Chapter 15 – Strings


Substring

The substring (substr) function is used to return a portion of a string. This function requires two
parameters – (1) the starting position, and (2) the number of characters. Important - When you are
referring to the position of a character in a string, the first character is at position zero. When you are
referring to the number of characters in strings, always begin counting with one. Look at the string
definition below.

string S1 = "This sentence used to demonstrate substrings";

The table below shows various substring commands using S1 and what they return.

            Substring Examples
Substring Command      What it Returns
S1.substr(0,1)                "T"
S1.substr(0,4)                "This"
S1.substr(14,3)               "use"
S1.substr(1,2)                "hi"

The program below demonstrates use of the substring function.


Program 15.2b - Substring Function

#include <iostream.h>
#include <string>

main()
{
  string S1 = "0123456789";
  string S2 = "good morning";
  cout << "Today I am " << S1.substr(2,2) << " years old.\n";
  cout << "You are a " << S2.substr(0,4) << " neighbor.\n";
}

Output
Today I am 23 years old.
You are a good neighbor.
                                                                                  Chapter 15 – Strings         67


Insert

The insert function is used to insert text at any position in a string. Unlike the substring function, when
you use the insert function, the value of the string is changed. This function takes two parameters - the
position where the insert will be made, and the text to be inserted. The text is inserted before the text at
the specified position. The following program demonstrates the string insert function.

Program 15.2c - Insert Function

#include <iostream.h>
#include <string>

main()
{
  string X = "happy birthday";
  cout << X.insert(0,"have a ") << endl;
  string Y = "very ";
  X.insert(7,Y);
  cout << X << endl;
}

Output
have a happy birthday
have a very happy birthday


Replace

The replace function is used to replace a portion of a string with another string. As with insert, when you
use the replace function, the value of the string is changed. This function takes three parameters - the
position where the replace will be made, the number of characters to replace, and the text to replace it
with. The following program demonstrates the replace function.

Program 15.2d - Replace Function

#include <iostream.h>
#include <string>

main()
{
  string X = "It is time for class";
  X.replace(11, 3, "to go to");
  cout << X << endl;
  X.replace(3, 2, "will be");
  cout << X << endl;
}

Output
It is time to go to class
It will be time to go to class
68     Chapter 15 – Strings


Find

The find function is used to search for character(s) within a string. It takes two parameters - the
character(s) to search for and the position where to begin the search. The function returns an integer that
corresponds to the starting position of where the character(s) were found. Observe the following string
definistion:

string Z = "It is time for class.";

The table below shows various find commands using the above string definition. Notice that the last
example searches for the letter "q" which is not contained in the string Z. When the search string is not
found, the find function returns the largest number an integer can be: 4294967295.

               Find Examples
Substring Command       What it Returns
Z.find("i", 0)          3
Z.find("me", 0)         8
Z.find("i", 4)          7
Z.find("q", 0)          4294967295

The program below demonstrates a search and replace program. It searches for any spaces in the string A
and replaces them with a dash. The while loop executes as long as the find statement returns a value less
than the length of A.

Program 15.2f – Search and Replace

#include <iostream.h>
#include <string>

main()
{
  string A = "This is a search and replace example";
  int X = A.find(" ", 0);
  while (X < A.size())
  {
    A.replace(X,1,"-");
    X = A.find(" ", X+1);
  }
  cout << A << endl;
}

Output
This-is-a-search-and-replace-example
                                                                                Chapter 15 – Strings    69



Exercises – Chapter 15

Given the following string definition, what will each of the cout statements print?
string Z = "abcdefghijklmnopqrstuvwxyz";

1.    cout   <<   Z[0] << Z[1] << Z[2];
2.    cout   <<   Z[25] << Z[24] << Z[23];
3.    cout   <<   Z[7] << Z[8];
4.    cout   <<   Z[19] << Z[4] << Z[23] << Z[0] << Z[18];


What will the following cout statements print?

#include <iostream.h>
#include <string>
int main()
{
  string A = "good morning";
  string B = "alphabet soup";

     cout << B[0] << B[1] << B[2];                         5. (a) goo       (b) mor        (c) alp

     cout << A.substr(0,4) << B.substr(9,4);               6. (a) goodsoup            (b) good soup

     cout << A.substr(5,3) << B[6];                        7. (a) mornbe        (b) more     (c) mor

     A.replace(5,3,"eve");
     cout << A;                                            8. (a) good evening           (b) good eve

     cout << A.find("e",0);                                9. (a) e     (b) 5     (c) v     (d) 7

     cout << B.substr(0,5);                                10. (a) alpha        (b) good     (c) bet

     A.insert(0,"very ");
     cout << A;                                            11. (a) very alpha
     return 0;                                                 (b) very good morning
}                                                              (c) very good evening


Given the following string definition, what do the functions return?

string Alpha = "it is rainy today", Beta = "it isn't sunny";

12. Alpha.size()                                 17. Alpha.find("i",1)

13. Beta.size()                                  18. Alpha.find("to",0)

14. Alpha.substr(6,4)                            19. Beta.find("nn",10)

15. Beta.substr(9,3)                             20. Beta.find("z",0)

16. Alpha.find("i",0)
70   Chapter 16 – Writing Functions



Chapter 16 – Writing Functions
16.1 Functions Defined

As your programs get larger and more complex, you will want a way to divide your program into smaller
modules. Chapter 10 gave an introduction to using some of the predefined functions located in other
libraries. An example in the math.h library is the square root function. To print the square root of 225,
you would simply type:

cout << sqrt(225);

Having the code to calculate square roots located in a separate function makes programming much easier.
For example, if you write a lot of programs that need to calculate volumes of various geometric shapes,
then it would be beneficial for you to create functions for each of these calculations. Whenever you need
to calculate the volume of a sphere in your program, you would just call that function (instead of writing
the code each time). This chapter will show how to write your own functions.

Functions may be located in the same file as your main program, or they may be located in a separate
library file that you can #include in your main program. Locating functions in the same file as your main
program gives you a way to divide up your program into smaller pieces. Locating functions in a separate
library file allows you to put common tasks (e.g. calculating the volume of a sphere) in a library that may
be used by any program you write.

16.2 Format of a Function

This section will demonstrate a function and explain its format. The next program demonstrates a
function to calculate the volume of a sphere. In this example, the sphere volume function is located in the
same file as the main program.

Program 16.2a – Sphere Volume Function

#include <iostream.h>

// This is the function to calculate sphere volumes
float VolSphere(float Radius)
{
  return (4.0/3.0) * 3.14 * Radius * Radius * Radius;
}

main()
{
  cout << "Sphere volume with radius of 2.0 is " << VolSphere(2.0) << endl;
  cout << "Sphere volume with radius of 5.5 is " << VolSphere(5.5) << endl;
}

Output
Sphere volume with radius of 2.0 is 33.4933
Sphere volume with radius of 5.5 is 696.557
                                                                      Chapter 16 – Writing Functions          71


In the previous program, there are actually two functions: VolSphere and main. You might not have
realized it, but every program you have written so far has a function – main. The main function always
executes first when you run your program.

The VolSphere function is called in each of the cout statements. When this happens, the parameter
(2.0 or 5.5) is sent to the function. The function calculates the volume of a sphere with that radius, then
returns the answer back to the main program. The diagram below explains the format of the function.

return     function    parameter parameter
 type      name        type      name


float VolSphere (float Radius)
{
  return (4.0/3.0) * 3.14 * Radius * Radius * Radius;
}

return type         Remember how a function works – you send it information (e.g. a radius), it makes
                    calculations (e.g. calculates the volume of a sphere), then returns the answer back to
                    whatever program called the function. The return type is the variable type of
                    whatever the function returns. In this case, the function returns the volume of a
                    sphere, so float was selected as the return type. If a function has a return type of
                    void, then it does not return anything.
function name       This is the name of the function. When you call the function from your main
                    program, you will put the function name followed by the parameter(s). Like any C++
                    variable name, the function name must begin with a letter and cannot contain spaces.
parameter type      When your main program calls a function, you put the function name followed by
                    any information (parameters) needed by the function. When you call the VolSphere
                    function, you must send it one parameter – a radius. The parameter type is the
                    variable type of the parameter sent to the function.
parameter name      This is the name of the parameter. In program 15.2a, the first cout statement calls the
                    VolSphere function and sends it one parameter – 2.0. Inside the VolSphere
                    function, the variable Radius takes on the value of the parameter – 2.0. Note that
                    Radius is a local variable (only visible in the VolSphere function) and should not be
                    used in your main program.

After the function header line, you will have an opening and closing brace, as with the main program.
Inside the braces, you may make calculations, declare variables, etc. The last thing your function should
do is return a value to the calling program.

Remember: When you call a function, you send it one or more pieces of information (parameters), and it
returns a value. While you are learning how functions work, it is better not to put any cout or cin
statements in them. They should be like a black box – information goes in, and information comes out.
There should not be any side effects such as cout statements.
72   Chapter 16 – Writing Functions


The next program shows an example of a function to calculate the area of a triangle. This function takes
two parameters – the base and the height of a triangle.

Program 16.2b – Area of Triangle Function

#include <iostream.h>

float AreaTriangle(float Base, float Height)
{
  float Volume = 0.5 * Base * Height;
  return Volume;
}

main()
{
  cout << "This program calculates the area of a triangle.\n";
  float B, H;
  cout << "Enter the base: ";
  cin >> B;
  cout << "Enter the height: ";
  cin >> H;
  cout << "The area is " << AreaTriangle(B,H) << endl;
}

Output
This program calculates the area of a triangle.
Enter the base: 3
Enter the height: 4
The area is 6



16.3 Function Prototypes

In the previous two programs, the VolSphere and AreaTriangle functions were both located above
the main function. If you were to place these functions below main, the compiler would give you an
error. As with variables, functions must be declared before they are used. As your programs become
more complex, you may have functions that call other functions. The order that you place your functions
can become a hassle. Therefore, it is good practice to place function prototypes at the top of your
program. Prototypes will declare your functions to the compiler so that the order they are located in your
program does not matter. A prototype for the VolSphere function is just the header line of the function
followed by a semicolon:

float VolSphere(float Radius);
                                                                    Chapter 16 – Writing Functions     73


The next program demonstrates the sphere volume program using a function prototype.

Program 16.3 – Function Prototype

#include <iostream.h>
float VolSphere(float Radius);

main()
{
  cout << "Sphere volume with radius of 2.0 is " << VolSphere(2.0) << endl;
  cout << "Sphere volume with radius of 5.5 is " << VolSphere(5.5) << endl;
}

float VolSphere(float Radius)
{
  return (4.0/3.0) * 3.14 * Radius * Radius * Radius;
}

Output
Sphere volume with radius of 2.0 is 33.4933
Sphere volume with radius of 5.5 is 696.557



16.4 Function Libraries

You may want to create a library of commonly used functions. For example, you may want to put the
functions for calculating areas and volumes in a separate file that may be included in any program you
write. This will allow you to calculate the volume of a sphere by simply including your library file and
calling the VolSphere function. To do this, simply use your editor to create another file that contains
your functions. In this next example, we first create a file named geometry.h for our geometry functions:

// geometry.h file

float VolSphere(float Radius)
{
  return (4.0/3.0) * 3.14 * Radius * Radius * Radius;
}

float AreaTriangle(float Base, float Height)
{
  float Volume = 0.5 * Base * Height;
  return Volume;
}


Now that you have the geometry.h file created, you can use its functions from any program you write.
Notice that when you include geometry.h, you must enclose the filename within double quotes:

#include "geometry.h"
74   Chapter 16 – Writing Functions


Using the Linux g++ compiler, it is acceptable to name your library files using extensions other than .cpp
or .c++. The files included into your main program are not compiled separately --- they are automatically
compiled when you compile your main program. The next program demonstrates using the geometry.h
library file.

Program 16.4 – Using Functions Located in Another File

#include <iostream.h>
#include "geometry.h"

main()
{
  cout << "Sphere volume with radius of 2.0 is " << VolSphere(2.0) << endl;
  cout << "Sphere volume with radius of 5.5 is " << VolSphere(5.5) << endl;
}

Output
Sphere volume with radius of 2.0 is 33.4933
Sphere volume with radius of 5.5 is 696.557



Exercises – Chapter 16

What is the return type and parameters needed to write the following functions? This exercise is to help
you begin thinking how a function works: you send it one or more pieces of data (the parameters), and it
returns a value.

                        Function                             Return Type           Parameter(s)
Example: A function to calculate the area of a               float         float Base
rectangle.                                                                 float Height
1. A function to calculate the surface area of a sphere.

2. A function to convert a Fahrenheit temperature to
Celsius.
3. A function to convert miles to kilometers.

4. A function to calculate the cube of an integer.

5. A function to calculate the product of three numbers.

6. A function to calculate the number of biscuits that
can be made from a given amount of flour, baking
powder, butter, and milk.
7. A function that gives the gemstone corresponding to
a given month (1 – 12).
8. A function that returns the reverse of a word – e.g. it
will return "olleH" if you send it "Hello".
9. A function that returns true if the first letter of a
word is a vowel, or false if it is a consonant.
10. A function that returns true or false depending on if
a given positive integer is a prime number.
                                                                       Chapter 16 – Writing Functions       75


11. Write a function named Area_Circle that calculates the area of a circle.




12. Write a function named Day_Week that returns the day (e.g. "Wednesday") for a given number 1 – 7.




13. Write a function named Reverse_Word that returns the reverse of a word.




14. Write a function named Vowel_First that returns true if the first letter of a word is a vowel, or false if
it is a consonant.
76   Chapter 17 – Variable Scope



                             Chapter 17 – Variable Scope
17.1 Local Variables

Variables declared inside a function or in the function header are local variables and are hidden from the
rest of your program. Local variables are stored in a section of memory called the stack. When a
function is called, variables declared in the function (including the header) are placed on the stack. When
the function returns (finishes), the variables are removed from the stack. The next program will be used
to demonstrate local variables.

Program 17.1 – Program to Demonstrate Local Variables

#include <iostream.h>
int IncreaseAge(int Age);
void WriteAge();

main()
{
  int Age = 20;
  Age = IncreaseAge(Age);
  WriteAge();
}

int IncreaseAge(int Age)
{
  Age = Age + 20;
  return Age;
}

void WriteAge()
{
  cout << Age << endl;            // error --- Age is undeclared in this function
}


In the previous program, the variable Age is declared in both main( ) and IncreaseAge( ) functions. These
are two different variables even though they have the same name. In the WriteAge( ) function, there will
be a compiler error since Age is not declared in that function. Age is a local variable in the functions that
declared it and not accessible in the WriteAge( ) function.

A variable declared in the header of a for loop is also a local variable which is only visible within the
loop. The following code demonstrates this.

for (int X = 1; X <= 10; X++)
{
   cout << X << endl;
}
cout << X;   // This will cause an error since X is local to the for loop

The reason for local variables is so that functions will not cause any side effects – they will not make any
changes to variables used in other functions. For example, when you call the sqrt( ) function located in
                                                                        Chapter 17 – Variable Scope      77


math.h, you know that the function will not make changes to any variables in your main program. Any
data needed by functions should be passed as parameters.

17.2 Global Variables

A global variable is declared outside of any function and is therefore visible to all functions. They are
normally declared at the top of your program beneath the #include statements. Global variables are
generally not recommended. It is usually best to pass values needed by functions as parameters. One
place that global variables could be used are as mathematical constants – declaring pi as a global constant
will allow all functions to use this value. The next program demonstrates using a global variable.

Program 17.2 – Global Variables

#include <iostream.h>
void CubeKiwi();

float Kiwi;        // Kiwi declared as a global variable

main()
{
  Kiwi = 5;
  CubeKiwi();
  cout << Kiwi << endl;
}

void CubeKiwi()
{
  Kiwi = Kiwi * Kiwi * Kiwi;
}

Output
125
78   Chapter 18 – File Input and Output



                        Chapter 18 – File Input and Output
18.1 File Output

So far, all programs in this book only output to the screen (console). This section shows how to output to
a file. This adds a lot of flexibility with your programming – the ability to output data into a file that
could be used to import the data into a different application. Outputting to a file is done by creating a file
output file stream using the fstream library. A file output stream works very similar to the cout
statement, but the results will be sent to a file instead of the console. The following program
demonstrates output to a file named "test".

Program 18.1 – Output to a File

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
  ofstream fout("test");
  cout << "This sentence is output to the console.\n";
  fout << "This sentence is output to the file.\n";
  return 0;
}

Console Output
This sentence is output to the console.

File Output
This sentence is output to the file.


In the preceding program, the iostream library is included for console output using the cout statement.
The fstream library is included for file output. The ofstream (output file stream) command is used
to create an output stream called fout which is directed to a file named “test”. Note that an output file
stream can be named anything (not just fout), but fout is a common name for the file output stream
since it works similar to the cout statement.

If you run this program on a Linux system, then do a directory listing by entering ls at the $ prompt. You
will notice that a file named "test" was created in your home directory after running the above program.
To see the contents of this file, you can type cat test at the $ prompt.

18.2 File Input

Whereas the cin statement gets data from the keyboard and places into variables, the fin statement gets
data from a file and places into variables. The fin statement is also located in the fstream.h library.
Reading data from a file is useful when you are working with large amounts of data or working with data
that was exported from another program. Before you can input data from a file, you must first open it
with the ifstream fin command.
                                                                   Chapter 18 – File Input and Output         79


The next program uses an input file named data which contains two numbers. If you are using a Linux
system, this file can be created using the pico editor. In this input file, the data should be separated by
spaces or carriage returns. The program reads the data into the variables A and B.
80   Chapter 18 – File Input and Output



Program 18.2a – Input Data from a File

#include <fstream.h>
#include <iostream.h>

main()
{
  ifstream fin("data");
  float A, B;
  fin >> A;
  fin >> B;
  cout << "The numbers are " << A << " and " << B << endl;
}

Input File – "data"
25.2 17.6

Output
The numbers are 25.2 and 17.6


In the next program, we add eight more numbers to the input file. The file data now has ten numbers in
it. Instead of declaring ten variables and using ten fin statements, we declare an array and use a for loop
for inputting the data. We also declare a variable named Total and add each number to it.

Program 18.2b – Input Data from a File into an Array

#include <fstream.h>
#include <iostream.h>

main()
{
  ifstream fin("data");
  float MyData[10];
  float Total = 0;
  for (int X=1; X<=10; X++)
  {
    fin >> MyData[X];
    Total = Total + MyData[X];
  }
  cout << "The total of the numbers is " << Total << endl;
}

Input File – "data"
25.2 17.6 14.7 8.9 10.5 3.1 5.3 19.4 21.4 25.8

Output
The total of the numbers is 151.9
                                                                 Chapter 19 – Random Numbers        81



                          Chapter 19 – Random Numbers
Random numbers are used in many types of programs. An example is the Windows solitaire game. Each
time you deal the cards, the deck is arranged differently. Let's say you would like a program to print 10
random numbers, each between 0 and 9. Can a computer truly generate random numbers for you? The
answer is no, but for practical purposes, the answer is yes. They can simulate random numbers by using a
complicated mathematical algorithm. A simplified way to view this would be to look at the front cover of
this book which contains pi printed out to thousands of digits. Pi is an infinitely long series of numbers
which contains no repeating patterns. Your computer program could take the next digit of pi every time it
prints a random number between 0 and 9. If your program prints 10 of these random numbers, then it
would print: 3141592653.

C++ has a random number generated located in the stdlib.h library. The rand( ) function returns a random
positive integer . If you were mod this integer by 50, then the result (remainder of the division) would be
a random number between 0 and 49:

cout << rand() % 50;               //Outputs a random number between 0 and 49

cout << rand() % 50 + 1;           //Outputs a random number between 1 and 50

The program below prints two random numbers between 0 and 49, inclusively.

Program 19a – Random Number Generator

#include <iostream>
#include <stdlib.h>            //Library containing the rand() function
using namespace std;

int main()
{
   cout << rand() % 50 << endl;
   cout << rand() % 50 << endl;

    return 0;
}

Output – Note: Your output may be different numbers
33
36


If you try running the preceding program multiple times, you will notice that it prints the same two
numbers every time. This is because the random number algorithm starts at the beginning every time.
Each time you call the rand() function in a program, it will give you a random number. But when you
run the program again, it will output the same numbers? Why? Because programs do the same thing
every time they run.

To correct this problem, random number algorithms need to be seeded with some external data that will
be different each time it runs. Seeding allows an external variable to be introduced into the random
number algorithm so that it will produce different results. The most popular way of seeding the random
number generator is to use time.
82    Chapter 19 – Random Numbers



The time.h library allows you to access the computer‟s clock. The time is used to seed the random
number generator. This seeding (srand function) only needs to be executed once at the beginning of a
program. Each time you run the program, the time has changed. Therefore, the random number
generator can produce different results. The next program is similar to previous, but with the addition of
seeding the random number generator.

Program 19b – Seeding the Random Number Generator

#include <iostream>
#include <time.h>              //Library containing time function
#include <stdlib.h>            //Library containing the rand() function
using namespace std;

int main()
{
   srand(time(NULL));          //Seed the random number generator with time

     cout << rand() % 50 << endl;
     cout << rand() % 50 << endl;

     return 0;
}

Output – Note: Your output may be different numbers
3
43


Try running the preceding program multiple times so you can verify that it prints different numbers each
time. Now that you understand how computer random number generators work, here's a question: Two
Windows computers are set to the exact same time. The solitaire program is opened on each computer at
the exact same time. Will they show the same cards?
                                                               Chapter 19 – Random Numbers   83


The next program is an example of how to print a random statement to the screen.

Program 19c – Printing A Random Statement

#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;

int main()
{
   srand(time(NULL));

    int R = rand() % 3 + 1;              //R is a random number between 1 and 3

    cout << "I like to eat ";

    if (R == 1)
       cout << "snails\n";
    if (R == 2)
       cout << "worms\n";
    if (R == 3)
       cout << "pizza\n";

    return 0;
}

Output – Note: Your output may be different
I like to eat pizza
84   Chapter 20 – Recursion



                                 Chapter 20 – Recursion
Recursion refers to when a program or function calls itself. A recursive function is one that when you run
it, it will call itself a certain number of times before returning to the calling program. The first
demonstration of a recursive function is one to calculate factorials: (6! = 6 * 5 * 4 * 3 * 2 * 1). To
calculate 6!, you could multiply 6 by 5!. Then to calculate 5!, you multiply 5 by 4!, and so forth... The
following recursive function calculates a factorial by multiplying the number by the factorial of that
number minus one.

int Factorial(int N)
{
  if (N >= 1)
    return N * Factorial(N – 1);                //Multiply N by the factorial of N-1
  else
    return 1;
}

The next recursion example calculates the Fibonacci number series. For 0 or 1, the Fibonacci number is
equal to 1. For all greater numbers, it is equal to the sum of the previous two. The following table lists
the first nine numbers in the Fibonacci series.

                                             Number      Value
                                                 0          1
                                                 1          1
                                                 2          2
                                                 3          3
                                                 4          5
                                                 5          8
                                                 6         13
                                                 7         21
                                                 8         34

The next program uses a recursive function to calculate a user selected Fibonacci number. You may not
want to try this with a large number (greater than 40) since it may tie up the computer for a while – the
number of calls to the Fib function grows exponentially with larger numbers.
                                                                  Chapter 20 -- Recursion   85




Program 20a – Recursive Function to Calculate Fibonacci Numbers

#include <iostream.h>
int Fib(int N);

main()
{
  cout << "This program calculates a Fibonacci number.\n";
  cout << "Enter a number between 1 and 40: ";
  int Number;
  cin >> Number;
  cout << "The Fibonacci number is " << Fib(Number) << endl;
}

int Fib(int N)
{
  if (N == 0 || N == 1) return 1;
  return Fib(N - 1) + Fib(N - 2);
}

Output
This program calculates a Fibonacci number.
Enter a number between 1 and 40: 9
The Fibonacci number is 55
86   Chapter 21 – More Input/Output



                         Chapter 21 – More Input/Output

21.1 ANSI Escape Codes
The ANSI escape sequences can be used with telnet sessions to change text colors, cursor positions, and
reassign keys. The escape character is ASCII number 27. In C++, you may print this character using the
\e within a cout statement as shown below.

cout << "\e[2J";                 // this escape sequence clears the screen

The table below shows some of these escape sequences that may be used in your programs. For a
complete listing, search the Internet for "ANSI Escape Sequences".

                   ANSI Escape Sequence                       Function
                   <ESC>[2J                      Clear screen and home cursor
                   <ESC>[K                       Clear to end of line
                   <ESC>[#;#H                    Move cursor to line #, column #
                   <ESC>[#A                      Move cursor up # lines
                   <ESC>[#B                      Move cursor down # lines
                   <ESC>[#C                      Move cursor right # lines
                   <ESC>[#D                      Move cursor left # lines
                   <ESC>[0m                      Set font color to normal (gray)
                   <ESC>[31m                     Set font color to red
                   <ESC>[32m                     Set font color to green
                   <ESC>[33m                     Set font color to yellow
                   <ESC>[34m                     Set font color to blue
                   <ESC>[35m                     Set font color to magenta
                   <ESC>[36m                     Set font color to cyan
                   <ESC>[37m                     Set font color to bright white
                                                                 Chapter 21 – More Input/Output    87



21.2 IO Manipulators

The iomanip.h library contains various functions for controlling the way output is displayed. You may
have noticed that large numbers are often converted to scientific notation automatically. This may be
changed using the setiosflags function.

To switch to scientific notation, you do: setiosflags(ios::scientific)
To switch to non-scientific notation, do: setiosflags(ios::fixed)
To left justify numbers in the field, do: setiosflags(ios::left)
To right justify numbers in the field, do: setiosflags(ios::right)

The setting remains in effect until changed. The next program demonstrates printing a large number in
non-scientific fashion.

Program 21.1a – Printing Large Numbers in Non-Scientific Notation

#include <iostream.h>
#include <iomanip.h>

int main()
{
   double X = 523243.2892 * 591234.1234;
   cout << setiosflags(ios::fixed) << X;
   return 0;
}

Output
309359287415.094730


You may set the number of digits past the decimal point that displays using the setprecision function. The
precision remains in effect until changed. The following program demonstrates this.

Program 21.1b – Setting the Number is Digits Past the Decimal Point

#include <iostream.h>
#include <iomanip.h>

int main()
{
   float A = 1.0 / 3.0;
   cout << setprecision(2) << A << endl;
   return 0;
}

Output
0.33
88   Chapter 21 – More Input/Output


You may set the minimum width for the display of numbers using the setw function. This will make it
easy for numeric data to line up on the display. After each number is displayed, the setw function is reset
back to the default of 1. The following program demonstrates this.

Program 21.1c – Setting the Display Width of Numbers

#include <iostream.h>
#include <iomanip.h>

int main()
{
   int A=1, B=20, C=2000;
   int D=600, E=3, F=10000;
   cout << setw(8) << A << setw(8) << B << setw(8) << C << endl;
   cout << setw(8) << D << setw(8) << E << setw(8) << F << endl;
   return 0;
}

Output
        1          20      2000
      600           3     10000
                                                               Chapter 21 – More Input/Output      89


21.3 Cout and Cin Methods
When you do output (cout), you place text on the output buffer which is then written to the screen.
When you do input (cin), you read text from the input buffer. The cout and cin statements are actually
classes with various functions (also called methods) that may be used with each statement. The following
table lists some of these methods.

                                         Cout and Cin Methods
Method                        Description
cout.flush()                  This will display and clean everything on the output buffer. This can be
                              useful if you are working on a real-time program. A cout statement puts a
                              string on the output buffer. There is no guarantee it will be displayed at
                              that exact time. The display of the output buffer could be delayed if the
                              program continues to execute. Use this if you are having problems with a
                              cout statement displaying at the proper time.
cin.ignore()                  This will throw away the next character on the input buffer. This is useful
                              if you would like to place a "Press <Enter> To Continue" prompt in your
                              program:

                              cout << "Press <Enter> To Continue";
                              cin.ignore();
cin.ignore(2)                 This will throw away the next 2 characters on the input buffer.
cin.getline(A,60)             Because the cin statement will terminate when a space is encountered, it
                              will not work for having the use enter a sentence. The getline method can
                              be used to let the user enter a sentence. In this case, a sentence up to 60
                              characters will be fetched and stored into a character array.

                              cout << "Enter a sentence: ";
                              char A[60];
                              cin.getline(A,60,'\n');
cin.clear()                   This is used to clear an error on the input buffer. An input error can occur
                              when you ask the user to enter a number, but they enter text instead. When
                              this happens, the cin statement returns boolean false. You must first
                              clear() the error on the input buffer, then remove the text by inputting it
                              into a dummy variable. Here's an example how to input a number with
                              error checking:

                              int Age;
                              string BadChars;
                              cout << "Enter your Age: ";
                              while (!(cin >> Age))
                              {
                                 cout << "You messed up! Please enter your age: ";
                                 cin.clear();
                                 cin >> BadChars;
                              }
90   Chapter 22 – Classes



                                  Chapter 22 – Classes
Classes are the primary feature added to the C programming language to create C++. They are also the
primary feature making C++ an object-oriented programming language. Classes allow us to define own
own custom variable type in C++. They allow us to model real-world objects in a program so that they
behave as they do in the real world.

22.1 Basic Classes
In the following program, we defined a new class called MyCube. Class definitions may be declared
before your main program, or in a separate file included in your main program. Note that the class
definition ends in a semicolon after the closing brace. In the main program, we declared an instance of
MyCube called Valerie. As in declaring variables, you must declare instances of classes before you can
use them.

Program 22.1 – Basic Class

#include <iostream.h>

class MyCube
{
   public:
     int Length, Width, Height;
};

int main()
{
  MyCube Valerie;     //declare an instance of MyCube called Valerie
  Valerie.Length = 2;
  Valerie.Width = 3;
  Valerie.Height = 4;
  cout << "Valerie's volume is "
       << Valerie.Length * Valerie.Width * Valerie.Height
       << endl;
  return 0;
}

Output
Valerie's volume is 24


Note: It would be incorrect to write MyCube.Length = 6. MyCube is the variable type, not the
variable name. This would be similar to writing float = 6. Float is a variable type --- you must
declare a variable of this type before you can use it.

In the previous program, the MyCube class was defined with three variables. Variables inside a class
definition are considered to be properties of the class. In this example, we define a cube as having the
following properties: length, width, and height. The variables were declared under the public heading so
that the main program has access to them.
                                                                           Chapter 22 – Classes     91



22.2 Class Functions (Methods)

Classes allow you to create member functions (also called methods) allowing you to interact with the
class. In the previous MyCube class definition, we defined the properties of a cube as being length, width,
and height. In the next program, we declare a function within the class definition to calculate the volume.

Program 22.2a – Class Functions

#include <iostream.h>

class MyCube
{
  public:
    int Length, Width, Height;

     int Volume()
     {
       return Length * Width * Height;
     }
};

int main()
{
  MyCube Valerie;
  Valerie.Length = 2;
  Valerie.Width = 3;
  Valerie.Height = 4;
  cout << "Valerie has volume of " << Valerie.Volume() << endl;
  return 0;
}

Output
Valerie has volume of 24


Another format for writing class functions to place them outside of the class definition. The program
below shows how to place the Volume function below the MyCube class definition.

Program 22.2b – Class Functions

#include <iostream.h>

 class MyCube
 {
    public:
      int Length, Width, Height;
      int Volume();
 };

 int MyCube::Volume()
 {
   return Length * Width * Height;
 }
92     Chapter 22 – Classes



 int main()
 {
   MyCube Valerie;
   Valerie.Length = 2;
   Valerie.Width = 3;
   Valerie.Height = 4;
   cout << "Valerie has volume of " << Valerie.Volume() << endl;
   return 0;
 }

Output
Valerie has volume of 24


In the previous program, the Volume function name was preceded by the name of the class it belongs to
and two colons: int MyCube::Volume() Notice that a function prototype was placed in the class
definition: int Volume();

22.3 Accessor Functions (Methods)

It is proper to keep the variables of a class private, preventing direct access to them. In the previous
programs, we accessed Valerie's length, width, and height directly when we assigned values to them:
Valerie.Length = 2; It is good programming to create public functions known as accessor methods
for setting and retrieving variable data. The class variables should then be set to private. Accessor
methods enable you to separate the details of how the data is stored from how it is used, enabling you to
change how the data is stored without having to rewrite the function calls that use the data. The program
below creates an accessor method called SetSize which is used to set the cube's dimensions.

Program 22.3a – Accessor Methods

#include <iostream.h>

class MyCube
{
  public:
    int Volume()
    {
      return Length*Width*Height;
    }

       void SetSize(int L, int W, int H)               // Accessor Method
       {
         Length = L;
         Width = W;
         Height = H;
       }

     private:
       int Length, Width, Height;
};

int main()
{
                                                                           Chapter 22 – Classes    93


     MyCube Valerie;
     Valerie.SetSize(2,3,4);
     cout << "Valerie has volume of " << Valerie.Volume() << endl;
     return 0;
}

Output
Valerie has volume of 24


The next program adds a surface area function and additional accessor methods to the our class definition.

Program 22.3b – Complete MyCube Class

#include <iostream.h>

class MyCube
{
  public:
    int Volume()
    { return Length*Width*Height; }

       int SurfaceArea()
       { return Length*Width*2 + Length*Height*2 + Width*Height*2; }

       void SetSize(int L, int W, int H)
       { Length = L; Width = W; Height = H; }

       int GetLength()
       { return Length; }

       int GetWidth()
       { return Width; }

       int GetHeight()
       { return Height; }

     private:
       int Length, Width, Height;
};

int main()
{
  MyCube Valerie;
  Valerie.SetSize(2,3,4);
  cout << "Valerie's volume is " << Valerie.Volume() << endl;
  cout << "Valerie's surface area is " << Valerie.SurfaceArea() << endl;
  cout << "Valerie's width is " << Valerie.GetWidth() << endl;
  return 0;
}

Output
Valerie's volume is 24
Valerie's surface area is 52
Valerie's width is 3
94     Chapter 22 – Classes


22.4 Constructors and Destructors

A constructor is a class method that can be used to initialize the value of class variables. In the previous
program, we might want to initialize the value the cube‟s length, width, and height (in case the main
program does not do this). A destructor is used to clean up (free up allocated memory) after a class
definition. It is good practice to include a destructor, even if the function is empty. The following
program demonstrates a constructor and destructor. The constructor initializes MyCube‟s length, width,
and height all equal to 1.

Program 22.4 – Constructors and Destructors

#include <iostream.h>

class MyCube
{
  public:
    int Volume()
    {
      return Length*Width*Height;
    }

       void SetSize(int L, int W, int H)
       {
         Length = L; Width = W; Height = H;
       }

       MyCube()     // Constructor initializes variables
       {
         Length = 1; Width = 1; Height = 1;
       }

       ~MyCube()       // Destructor cleans up memory
       {
       }

     private:
       int Length, Width, Height;
};

int main()
{
  MyCube Valerie;
  cout << "Valerie has volume of " << Valerie.Volume() << endl;
  return 0;
}

Output
Valerie has volume of 24
                                                      Appendix A – Answers to Exercises      95



                    Appendix A – Answers to Exercises

Chapter 2
1.    (a) 3     (b) 5    (c) 15    (d) 21      (e) 255      (f) 254

2.    (a) 101      (b) 10    (c) 111     (d) 1000        (e) 1111        (f) 11000

3.    (a) 1     (b) 1001     (c) 1011       (d) 11011100         (e) 11110001        (f) 11111111

4.    (a) 72 105
      (b) 97 112 112 108 108 101
      (c) 107 105 119 105
      (d) 69 120 99 105 114 101 33

5.    I am hungry.

6.    2,000,000,000 / 700,000 = 2857

Chapter 5
1.    HelloWorld                                     7.      5

2.    1 is less than 3                               8.      3

3.    X * Y = 8                                      9.      120
      The End
                                                     10.     3       2       1        GO!
4.    Z
                                                     11.     "apples"
5.    AB                                                     are good
      CD
                                                     12.     /---\
6.    21                                                     | " |
                                                             \ - /

Chapter 6
1.    short int         Note: You could also use unsigned short int
2.    float
3.    double
4.    char
5.    int               Note: You could also use unsigned int
6.    bool
7.    double
8.    short int
9.    0
10.   0.25
11.   2
12.   0
96     Appendix A – Answers to Exercises


13.     ABBA
14.     -4

Chapter 8
1.
#include <iostream.h>

main()
{
  cout << "Enter a number to convert from inches to centimeters: ";
  float Inches, Centimeters;
  cin >> Inches;
  Centimeters = Inches * 2.54;
  cout << "This is equal to << Centimeters << " centimeters.\n";
}

2.
#include <iostream.h>

main()
{
  int Age, Weight;
  cout << "Enter your age: ";
  cin >> Age;
  cout << "Enter your weight: ";
  cin >> Weight;
  cout << "You still have " << 100 – Age << " years before you are 100.\n";
  cout << "You can still gain " << 500 – Weight;
  cout << " pounds before you weigh 500.\n";
}



Chapter 9
1.    false                     6. false
2.    false                     7. false
3.    true                      8. true
4.    true                      9. false
5.    false                     10. true

Be careful on question 10 – here we accidentally used single equal signs instead of double. When using a
single equal sign, you are actually doing an assignment statement – this will change the values of Z to 15
and Y to 10.

11.    Yes
12.    Pear
13.    Yes
14.    blue
                                            Appendix A – Answers to Exercises   97


15.
#include <iostream>
using namespace std;
main()
{
  cout << "Please enter an integer: ";
  int N;
  cin >> N;
  if ((N%2) == 0)
     cout << "Your number is divisible by 2\n";
  if ((N%3) == 0)
     cout << "Your number is divisible by 3\n";
  if ((N%3) == 0)
     cout << "Your number is divisible by 4\n";
}

Chapter 11
1.
#include <iostream>
#include <math.h>
using namespace std;
main()
{
  cout << "This program raises one integer to the power of the other.\n";
  int A,B;
  cout << "Enter the first number: ";
  cin >> A;
  cout << "Enter the second number: ";
  cin >> B;
  cout << A << " to the power of " << B << " is " << pow(A,B) << endl;
}

2.
#include <iostream>
#include <math.h>
using namespace std;
main()
{
  cout << "a = sin(x)\n";
  cout << "b = cos(x)\n";
  cout << "c = tan(x)\n";
  cout << "Please select an option: ";
  char Choice;
  cin >> Choice;
  cout << "\nEnter a value: ";
  float Value;
  cin >> Value;
  if (Choice == 'a')
     cout << "The sine of " << Value << " is " << sin(Value) << endl;
  if (Choice == 'b')
     cout << "The cosine of " << Value << " is " << cos(Value) << endl;
  if (Choice == 'c')
     cout << "The tangent of " << Value << " is " << tan(Value) << endl;
}
98   Appendix A – Answers to Exercises


3. The sqrt(9) function returns an integer. You cannot assign an integer to a char variable type.

Chapter 12
1.   1234

2.   543210

3.   7 7 7 7 7 7 7

4.   2 4 8 16 32 64 128

5.   ******

6.   yes no yes no yes no yes no yes no yes

Chapter 13
1.   1 2 3 4 5

2.   10 9 8 7 6 5 4 3 2 1

3.   2468101214161820

4.   100 48 22 9 2.5

5.   -10

6.   *
     **
     ***
     ****
     *****

7.   for (int X=3; X<=21; X = X + 3)
     {
        cout << X << " ";
     }

8.   for (int Y=4; Y>=-4; Y = Y – 2)
     {
        cout << Y << " ";
     }

9.   for (int X=1; X<=127; X = X * 2 + 1)
     {
        cout << X << " ";
     }
                                             Appendix A – Answers to Exercises   99


10. for (int I=1; I<=5; I++)
    {
       for (int J=1; J<=(6-I); J++)
       {
          cout << "*";
       }
       cout << endl;


Chapter 14
1.   int Corvettes[5] = {1956, 1963, 1968, 1983, 1997};

2.   string Days[7] = {"Monday","Tuesday","Wednesday","Thursday",
                       "Friday","Saturday","Sunday"};

3.   for (int X=0; X<=9; X++)
     {
        Scores[X] = Scores[X] + 1;
     }

4.   int Total = 0;
     for (int X=0; X<=9; X++)
     {
        Total = Total + Scores[X];
     }

Chapter 15
1. abc
2. zyx
3. hi
4. texas
5. (c) alp
6. (a) goodsoup
7. (b) more
8. (a) good evening
9. (b) 5
10. (a) alpha
11. (c) very good evening
12. 17
13. 14
14. rain
15. sun
16. 0
17. 3
18. 12
19. 11
20. 4294967295
100   Appendix A – Answers to Exercises


Chapter 16
      Return Type      Parameter(s)
1.    float            float Radius
2.    float            float Temperature
3.    float            float Miles
4.    int              int Number
5.    int              int Number1, int Number2, int Number3
6.    int              float Flour, float BPowder, float Butter, float Milk
7.    string           int Month
8.    string           string Word
9.    bool             string Word
10.   bool             int Number

11.   float Area_Circle(float Radius)
      {
         return 3.1415 * Radius * Radius;
      }


12.   string Day_Week(int Day)
      {
         if (Day == 1) return "Sunday";
         if (Day == 2) return "Monday";
         if (Day == 3) return "Tuesday";
         if (Day == 4) return "Wednesday";
         if (Day == 5) return "Thursday";
         if (Day == 6) return "Friday";
         if (Day == 7) return "Saturday";
         return "invalid number";
      }

13.   string Reverse_Word(string Word)
      {
         string Reverse = Word;
         for (int X=0; X<Word.size(); X++)
         {
            Reverse[X] = Word[Word.size()-1-X];
         }
         return Reverse;
      }

14.   bool Vowel_First(string Word)
      {
         char F = Word[0];
         if (F == 'a' || F == 'e' || F == 'i' || F == 'o' || F == 'u')
            return true;
         else
            return false;
                                                             Table of Contents
Chapter 1 – Computer Science .................................................................................................................. 1
  1.1 Preface ............................................................................................................................................... 1
  1.2 Programming Languages ................................................................................................................... 1
  1.3 Software Development Life Cycle .................................................................................................... 3
Chapter 2 – Introduction to Numbering Systems .................................................................................... 5
  2.1 Decimal (base-10).............................................................................................................................. 5
  2.2 Unary (base-1) ................................................................................................................................... 5
  2.3 Binary (base-2) .................................................................................................................................. 5
  2.4 Hexadecimal (base-16) ...................................................................................................................... 7
  2.5 ASCII ................................................................................................................................................. 8
  2.6 Storing Text on a Computer .............................................................................................................. 9
  Exercises – Chapter 2 ............................................................................................................................... 9
Chapter 3 – Using Linux .......................................................................................................................... 10
  3.1 C++ Compilers ................................................................................................................................ 10
  3.1 UNIX/Linux Background ................................................................................................................ 10
  3.2 Logging Into Linux .......................................................................................................................... 11
  3.3 Linux File System............................................................................................................................ 11
  3.4 Linux File Commands ..................................................................................................................... 11
  3.5 The Pico Editor ................................................................................................................................ 12
  3.6 Other Linux Commands .................................................................................................................. 14
Chapter 4 – Hello World! ......................................................................................................................... 16
  4.1 Getting Started ................................................................................................................................. 16
  4.2 Your First Program Using Linux ..................................................................................................... 16
  4.3 Hello World Program Examined ..................................................................................................... 18
Chapter 5 – Cout Statement..................................................................................................................... 20
  5.1 Basic Cout Statement....................................................................................................................... 20
  5.2 Printing a Newline ........................................................................................................................... 20
  5.3 Printing Variables ............................................................................................................................ 21
  5.4 Printing Mathematical Expressions ................................................................................................. 21
  5.5 Extending the Cout Statement ......................................................................................................... 23
  5.6 Comments and Documentation........................................................................................................ 24
  5.7 Backslash Special Characters .......................................................................................................... 25
  Exercises – Chapter 5 ............................................................................................................................. 26
Chapter 6 – Variables ............................................................................................................................... 27
  6.1 Variables Defined ............................................................................................................................ 27
  6.2 Variable Names ............................................................................................................................... 28
  6.3 Variable Types................................................................................................................................. 28
  6.4 Using Integer Variables ................................................................................................................... 29
  6.5 Using Float Variables ...................................................................................................................... 31
  6.6 Using Char Variables....................................................................................................................... 32
  Exercises – Chapter 6 ............................................................................................................................. 32
Chapter 7 – Constants .............................................................................................................................. 33
  7.1 Declared Constants .......................................................................................................................... 33
  7.2 Defined Constants............................................................................................................................ 33
  7.3 Enumerated Types ........................................................................................................................... 34
Chapter 8 – Cin Statement ....................................................................................................................... 35
  Exercises – Chapter 8 ............................................................................................................................. 36
Chapter 9 – If...Else Statement ................................................................................................................ 37
  9.1 Basic If Statement ............................................................................................................................ 37
  9.2 If...Else Statement ............................................................................................................................ 37
  9.3 Comparison Operators ..................................................................................................................... 39
  9.4 Using Braces with the If Statement ................................................................................................. 41
  9.5 Logical Operators: AND, OR, and NOT ......................................................................................... 42
  9.6 Ternary Conditional Operator.......................................................................................................... 43
  Exercises – Chapter 9 ............................................................................................................................. 45
Chapter 10 – Switch Statement ............................................................................................................... 46
Chapter 11 – Using Libraries and Functions ......................................................................................... 48
  11.1 Functions Defined.......................................................................................................................... 48
  11.2 Using Math.h Functions ................................................................................................................ 48
  11.3 Using Stdlib.h Functions ............................................................................................................... 50
  Exercises – Chapter 11 ........................................................................................................................... 51
Chapter 12 – While Loop ......................................................................................................................... 52
  12.1 Basic While Loop .......................................................................................................................... 52
  12.2 Infinite Loops ................................................................................................................................ 53
  12.3 Using While Loops for Menus ...................................................................................................... 54
  Exercises – Chapter 12 ........................................................................................................................... 55
Chapter 13 – For Loop ............................................................................................................................. 56
  13.1 Basic For Loop .............................................................................................................................. 56
  13.2 Using For Loops with Mathematics .............................................................................................. 57
  13.3 Additional Information About Loops and Program Flow ............................................................. 57
  Exercises – Chapter 13 ........................................................................................................................... 58
Chapter 14 – Arrays ................................................................................................................................. 61
  14.1 One Dimensional Arrays ............................................................................................................... 61
  14.2 Multidimensional Arrays ............................................................................................................... 62
  Exercises – Chapter 14 ........................................................................................................................... 63
Chapter 15 – Strings ................................................................................................................................. 64
  15.1 String Variables ............................................................................................................................. 64
  15.2 String Functions............................................................................................................................. 65
  Exercises – Chapter 15 ........................................................................................................................... 69
Chapter 16 – Writing Functions .............................................................................................................. 70
  16.1 Functions Defined.......................................................................................................................... 70
  16.2 Format of a Function ..................................................................................................................... 70
  16.3 Function Prototypes ....................................................................................................................... 72
  16.4 Function Libraries.......................................................................................................................... 73
  Exercises – Chapter 16 ........................................................................................................................... 74
Chapter 17 – Variable Scope ................................................................................................................... 76
  17.1 Local Variables .............................................................................................................................. 76
  17.2 Global Variables ............................................................................................................................ 77
Chapter 18 – File Input and Output ....................................................................................................... 78
  18.1 File Output ..................................................................................................................................... 78
  18.2 File Input........................................................................................................................................ 78
Chapter 19 – Random Numbers .............................................................................................................. 81
Chapter 20 – Recursion ............................................................................................................................ 84
Chapter 21 – More Input/Output ............................................................................................................ 86
  21.1 ANSI Escape Codes....................................................................................................................... 86
  21.2 IO Manipulators............................................................................................................................. 87
  21.3 Cout and Cin Methods ................................................................................................................... 89
Chapter 22 – Classes ................................................................................................................................. 90
  22.1 Basic Classes ................................................................................................................................. 90
  22.2 Class Functions (Methods) ............................................................................................................ 91
  22.3 Accessor Functions (Methods) ...................................................................................................... 92
  22.4 Constructors and Destructors......................................................................................................... 94
Appendix A – Answers to Exercises ........................................................................................................ 95

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:28
posted:3/22/2011
language:English
pages:103