C & C++
C is a computer language invented by Dennis Ritchie in 1972, while he was working for AT&T at Bell Labs. He called it “C” because it came after “B”, which was an earlier language developed by a colleague.
The previous chapters explained how to program in BASIC, JavaScript, and Java. C resembles those languages (especially Java) but has two advantages: C runs faster and consumes less RAM.
C has become the most popular language for creating advanced programs. The world’s biggest software companies have switched to C from assembly language:
If you become an expert C programmer, you can help run those rich software companies and get rich yourself!
Fundamentals
Before studying C, study an easier language, such as BASIC, JavaScript, or Java.
C is excitingly dangerous:
Unlike BASIC, JavaScript, and Java, C lets you easily create a pointer, which is a note about which part of RAM to use. If you create the pointer incorrectly, C will use the wrong part of RAM — and erase whatever info was there before. For example, C might erase the part of RAM used by your operating system (DOS or Windows), so your operating system becomes confused and accidentally erases your disks!
A faulty pointer (which points to the wrong part of RAM) is called a runaway pointer, and it’s a C programmer’s greatest fear. Even if your innocent-looking program doesn’t seem to mention pointers, a small error in your program might make C create a pointer that wrecks your computer. That’s why many C programmers look thin and haggard and bite their nails. To keep your nails looking pretty, make backup copies of your hard disk before trying to program in C.
C is like a sports car with no brakes: it’s fast, fun, slim, sleek, and dangerous. If you program in C, your friends will admire you and even whistle at you as you zoom along the freeway of computer heaven; but if you’re not careful, your programs and disk will crash, and so will your career!
C++
An improved C, called C++, was invented in 1985 at Bell Labs by Bjarne Stroustrup.
He was born in Denmark, where he studied at Aarhus University.
Then he moved to England, where he got a Ph.D. from Cambridge University.
Then he moved to New Jersey to work at Bell Labs, where he invented C++.
To pronounce his name, say
“Bee-ARE-nuh STRAH-stroop”,
but say the “Bee” and “STRAH-stroop” fast, so it sounds closer to
“BYAR-nuh STROV-strup”.
C++ uses the same fundamental commands as C but adds extra commands. Some of those extra commands are for advanced programming; others make regular programming more pleasant. C++ lets you use an advanced technique called object-oriented programming (OOP), in which you define “objects” and give those objects “properties”.
For input and output, C++ offers different commands than C. C++’s input/output commands are more pleasant.
Now most programmers use C++ instead of C.
The most popular version of C++ is Visual C++, which is by Microsoft and handles Windows. Microsoft is trying to invent a further improvement, called C# (pronounced “See sharp”), but C# is not ready yet.
This chapter explains how to use Visual C++. (At the end of this chapter, I’ll explain how C differs from C++.)
Visual C++ comes on a CD-ROM disk. The disk includes C also, so you can write traditional C programs. You can buy the disk by itself or as part of a suite, called Visual Studio.
Visual Studio 6 includes Visual C++, Visual J++ (which is a version of Java), Visual BASIC, and Visual FoxPro (which is a variant of DBASE).
Visual Studio .Net 2003 (which is newer) includes Visual C++, Visual C# (which is even fancier), Visual J# (which is a version of Java), and Visual BASIC. It requires Windows XP (or Windows 2000 or Windows Server 2003).
Copy C++ to the hard disk
Here’s how to copy Visual Studio 6 (enterprise edition) to the hard disk. (Other versions of Visual Studio and Visual C++ are similar.)
Make sure your computer contains Windows 98 (or Windows Me) and Internet Explorer 5 (or 5.5).
Turn on the computer without any floppy or CD-ROM disks in the drives, so the computer runs Windows 98 and the computer’s bottom left corner says Start. Put Visual Studio 6.0’s Disc 1 into the CD-ROM drive. The computer will say “Visual Studio 6.0”. Press ENTER. Click “I accept the agreement”. Press ENTER.
Type the 10-digit CD key number (printed on the orange sticker at the back of the CD-ROM disk’s square case). Press TAB. Type your name. Press TAB. Type the name of your company (if any). Press ENTER four times.
You’ll see a product ID. Copy it onto the registration form that you’ll mail to Microsoft. Press ENTER three times.
Finally, the computer will copy Visual Studio to the hard disk. Click “OK”. Press ENTER. The computer will reboot itself.
The computer will say “Install MSDN”. Put the MSDN Library’s Disc 1 into the CD-ROM drive. Click “Next”. Press ENTER.
You’ll see an MSDN product ID. Copy it onto a sheet of paper. Press ENTER three times The computer will copy the MSDN Library to the hard disk. Press ENTER six times.
Remove the check mark from the “Register Now” box (by clicking it). Press ENTER.
Start C++
To start using Visual C++ (version 6.0), do this:
Remove any CD-ROM disk. Click “Start” then “Programs” then “Microsoft Visual Studio 6.0” then “Microsoft Visual C++ 6.0”.
If the computer says “Did you know”, press ENTER.
Start a new program
Click “File” then “New” then “Files” then “C++ Source File”.
Click in the File Name box. Invent a name for your program (such as “joe”); type the name and press ENTER. (If the computer asks “Do you want to overwrite?”, the name you invented was already used by a colleague, so do this: click “No”, invent a different name instead, type it, and press ENTER.)
To emphasize that the program is written in C++, the computer automatically puts “.cpp” at the end of your program’s name. (The “cpp” stands for “C plus plus”.)
For example, if you said the program is “joe”, the computer automatically changes the name to “joe.cpp”. The computer will automatically put the program in your hard drive’s root directory, so the program will be called “C:\joe.cpp”.
Type your program
For your first experiment, type this C++ program, which teaches the computer to say “I love you”:
#include <iostream.h>
void main()
{
cout <<"I love you";
}
The include line Input and output is called I/O. The input and output comes as a stream of characters, called the I/O stream. The top line — #include <iostream.h> — tells the computer to include, as part of your program, an I/O stream header, containing definitions of C++ commands that manipulate the I/O stream.
Type that line carefully:
Make sure you type the symbols #, <, and > correctly.
Do not capitalize the word “include”. If you type “INCLUDE” instead of “include”, the computer will gripe. In C++, type all commands by using lower-case letters, not capitals.
If you type that line correctly, the computer will make the “#include” be blue. At the end of the line, press ENTER.
The main line The next line — void main() — marks the beginning of the program’s main part. Make sure you type the parentheses (), by pressing SHIFT with 9 or 0.
If you type that line correctly, the computer will make the “void” be blue.
The braces The next line is a brace, which is the symbol “{”.
Here’s how to type it: while holding down the SHIFT key, tap the key that’s to the right of the P key. Make sure you type the symbol “{”; do not type “[” or “(”.
The program’s bottom line is another brace, which means “here’s the end”; so the program’s lines are enclosed in braces {}. Those braces mark the beginning and end of the program’s main part.
Typical C++ That’s all typical! The typical C++ program begins by saying —
#include <iostream.h>
void main()
{
and ends by saying:
}
The cout line Any lines between the braces are the program’s heart. In the example, the program’s heart is this line:
cout <<"I love you";
That line says cout (which is pronounced “C out” and means “C++ output”). It makes the computer output “I love you” onto the screen.
The words in quotation marks, “I love you”, are called the string.
Since the symbol “<<” can be pronounced “from”, here’s how to pronounce that line: “C out from quote I love you quote semicolon”.
The computer understands “cout” because cout’s definition is part of <iostream.h>, which the program’s top line says to include. (If you accidentally omit the program’s top line, the computer will complain that it doesn’t know the meaning of “cout”.)
The whole cout line ends with a semicolon because C++ requires you to put a semicolon at the end of each simple line.
C++ handles two kinds of lines:
A simple line ends in a semicolon.
A line is called a structure line if it begins with “#” or “{” or “}” or is above “{”. A structure line does not end in a semicolon.
Indenting The computer is smart: it knows that any lines between “{” and “}” should be indented. So when you type that program, the computer automatically indents the “cout” line.
The computer automatically unindents the “}”. Here’s how: the “}” automatically hops to the left after you type it.
If you ever want the computer to indent differently, do this before typing a line’s first word or symbol:
Press the TAB key to indent.
Press the BACKSPACE key to unindent.
Build the program
After you’ve typed the program, the next step is to build the program, by pressing the F7 key. To do that, click the Build button, which is near the screen’s top right corner and shows a pair of arrows pointing down on a pile of papers (or press the F7 key or choose Build from the Build menu).
(If the computer then asks “Would you like to create a default project workspace?”, press ENTER twice.)
Then computer will accomplish two activities.…
First the computer will look at the program you’ve typed and automatically save the newest version of it. For example, if your program was named “C:\joe.cpp”, the computer will automatically update that file so it includes what you recently typed.
Next, the computer will try to create an .exe file and put it in the Debug folder. For example, if your program was named “C:\joe.cpp”, the computer will try to create a file called “C:\Debug\joe.exe”.
While creating the .exe file, the computer will analyze your program to see whether your programming makes sense. If you did everything right, the screen’s bottom window will say:
joe.exe - 0 error(s), 0 warning(s)
If the bottom window says you have more than 0 errors or more than 0 warnings, here’s how to see messages about why you had errors: click in that window, then scroll up (by pressing the up-arrow key several times or using the window’s scroll arrow or rotating the mouse’s wheel). Fix your errors, then try again to say “build”.
Execute the program
After the computer has said you have 0 errors and 0 warnings, execute the program. To do that, you can use two methods.…
The easy method Click the Execute button, which is a red exclamation point near the screen’s top right corner (or press Ctrl with F5 or choose Execute from the Build menu). The computer will execute (run) the program and say “I love you”. Then it will say “Press any key to continue” on the same line, so your screen looks like this:
I love youPress any key to continue
Press ENTER.
The good-looking method Get out of Visual C++ (by clicking the X at the screen’s top right corner). Get to a DOS prompt (by clicking “Start” then “Programs” then “MS-DOS Prompt”), so your screen looks like this:
C:\WINDOWS>
Type “\Debug\joe”, so your screen looks like this:
C:\WINDOWS>\Debug\joe
That makes the computer run C:\Debug\joe.exe, so the computer will say “I love you”. Then it will give you another DOS prompt, so your screen looks like this:
I love you
C:\WINDOWS>
Type the word “exit” (and press ENTER at the end of that word).
Switch programs
While the program you wrote is on the screen, you can edit it. After editing it, rebuild it (by clicking the Build button again) and then re-execute it (by clicking the Execute button again).
When you finish playing with that program, here’s how to create a totally different program instead:
If the program is still on the screen, click “File” then “Close Workspace” then press ENTER.
Start the process over again (by doing the “Start a new program” routine that I explained on page 519).
Here’s how to view an old program you created earlier:
Go into Visual C++. If a different program is on the screen, get it off the screen (by clicking “File” then “Close Workspace” then pressing ENTER). Click the Open button (which is near the screen’s top left corner and shows an opening manila folder). Make sure the “Look in” box says “C:”. (If it says otherwise, click that box’s down-arrow, then click “C:”.) You’ll see a list of C++ programs (and other folders); double-click the C++ program you want to use.
Erase files
If you type, build, and execute a program named “joe”, the computer generates 11 files.
One of them is the program you typed (C:\joe.cpp). One of them is the final result of the build (C:\Debug\joe.exe).
The remaining 9 files are useful just temporarily, to help the computer keep track of what’s being built. You can erase them:
C:\joe.dsp
C:\joe.ncb
C:\joe.plg
C:\Debug\joe.pch
C:\Debug\joe.obj
C:\Debug\joe.ilk
C:\Debug\joe.pdb
C:\joe.opt
C:\joe.dsw
\n
Let’s write a program that makes the computer say:
I love you
Let's get married
This program almost accomplishes that goal:
#include <iostream.h>
void main()
{
cout <<"I love you";
cout <<"Let's get married";
}
If you run that program by clicking the Execute button (which looks like a red exclamation point), the computer will say “I love you” and “Let’s get married” and “Press any key to continue”, but unfortunately it will print all those messages on a single line, so you’ll see this:
I love youLet's get marriedPress any key to continue
To make the computer print those three sentences on three separate lines, say “\n” at the end of each string, like this:
#include <iostream.h>
void main()
{
cout <<"I love you\n";
cout <<"Let's get married\n";
}
The \n means “new line”: it’s the symbol for the ENTER key. Telling the computer to print “I love you\n” makes the computer print “I love you” and then press the ENTER key, so the next sentence will be printed on the next line. Altogether, the computer will print this:
I love you
Let's get married
Press any key to continue
When you type the symbol \n, make sure you type a backslash: \. Do not type a division sign: /.
To make your output be pretty, put \n at the end of each typical string.
Instead of writing —
cout <<"I love you\n";
cout <<"Let's get married\n";
you can write:
cout <<"I love you\nLet's get married\n";
That single long line still makes the computer say:
I love you
Let's get married
Press any key to continue
endl
To make the computer end a line and start a new line, you can say \n. Another way to make the computer end a line is to say <<endl, like this:
cout <<"I love you" <<endl <<"Let's get married" <<endl;
That single long line makes the computer do this: print “I love you”, then end the line, then print “Let’s get married”, then end the line. Altogether, the computer will print this:
I love you
Let's get married
Press any key to continue
Math
The computer can do math. For example, this program makes the computer do 4+2:
#include <iostream.h>
void main()
{
cout <<4+2 <<endl;
}
It makes the computer print this answer on your screen:
6
Press any key to continue
This program makes the computer print the answer to 21+4 and also the answer to 68+1:
#include <iostream.h>
void main()
{
cout <<21+4 <<endl <<68+1 <<endl;
}
That cout line makes the computer print the answer to 21+4 (which is 25), then press ENTER, then print the answer to 68+1 (which is 69), then press ENTER, so you see this:
25
69
Press any key to continue
To print both of those answers on a single line instead of on separate lines, put a blank space between the answers by saying “ ” instead of endl, so the cout line looks like this:
cout <<21+4 <<" " <<68+1 <<endl;
That tells the computer to print the answer to 21+4 (which is 25), then a blank space, then the answer to 68+1, then press ENTER, so you see:
25 69
Press any key to continue
The computer leaves a space between the answers because of the <<“ ”. If you omit the <<“ ”, the computer will print:
2569
If you have 750 apples and buy 12 more, how many apples will you have altogether? This program prints the answer:
#include <iostream.h>
void main()
{
cout <<"You will have " <<750+12 <<" apples\n"
}
That cout line makes the computer print “You will have ”, then print the answer to 750+12 (which is 762), then print “apples”, then press ENTER (because of the \n), so you see this:
You will have 762 apples
Press any key to continue
Like most other languages (such as BASIC, JavaScript, and Java), C++ lets you use the symbols +, -, *, /, parentheses, decimal points, and e notation. But if you’re not careful, the computer will print wrong answers. Here’s why.…
Integers versus double precision
C++ handles two types of numbers well.
One type of number is called an integer (or int). An int contains no decimal point and no e. For example, -27 and 30000 are ints.
The other type of number that C++ handles well is called a double-precision number (or a double). A double contains a decimal point or an e. For example, -27.0 and 3e4 are doubles. You can abbreviate: instead of writing “-27.0”, you can write “-27.”, and instead of writing “0.37” you can write “.37”.
Largest and tiniest numbers
The largest permissible int is about 2 billion. More precisely:
the largest int is 2147483647
the lowest int you can write easily is -2147483647
the only int lower than that is a strange int you must write as -2147483647-1
(Warning: the largest int is 2147483647 just in Microsoft’s modern
versions of C & C++, such as Microsoft Visual C++ 6.0. In older versions of
C & C++ that were invented before Windows 95, the largest int is just
32767, and the lowest int is
-32767-1.)
If you try to feed the computer an int that’s too large or too low, the computer won’t complain. Instead, the computer will typically print a wrong answer!
The largest permissible double is about 1.7e308. More precisely, it’s 1.7976931348623158e308. If you feed the computer a math problem whose answer is bigger than that, the computer will give up and typically say the answer is —
1.#INF
which means infinity.
The tiniest double that the computer handles well is about 2.2e-308. More precisely, it’s 2.2250738585072014e-308. If you feed the computer a math problem whose answer is tinier than that, the computer will either handle the rightmost digits inaccurately or give up, saying the answer is 0.0.
Tricky arithmetic
If you combine ints, the answer is an int. For example, 2+3 is this int: 5.
11/4 is this int: 2. (11/4 is not 2.75.)
If you combine doubles, the answer is a double. If you combine an int with a double, the answer is a double.
How much is 2000 times 2000000? Theoretically, the answer should be this int: 4000000000. But since 4000000000 is too large to be an int, the computer will print a wrong answer. To make the computer multiply 2000 by 2000000 correctly, ask for 2000.0*2000000.0, like this:
#include <iostream.h>
void main()
{
cout <<2000.0*2000000.0 <<endl;
}
That program makes the computer get the correct answer, 4000000000.0, which the computer will write in e notation, so you see this answer:
4e+009
Cout precision
The computer can handle a double-precision number quite accurately, even if the number contains many digits. Here’s the limit: the computer can handle up to 15 significant digits.
When printing a double-precision number, cout assumes you don’t want to bother seeing all 15 significant digits, so cout typically prints just the number’s first 6 significant digits. If you want to see all 15 significant digits, insert this line above the cout lines:
cout.precision(15);
That line affects all cout lines below it.
When printing a number such as 3.00000000000000, cout assumes you don’t want to see the .00000000000000 (because zeros are boring), so cout typically prints just:
3
If you want to see the decimal point and zeros also, insert this line above the cout lines:
cout.setf(ios::showpoint);
That line affects all count lines below it.
Advanced math
The computer can do advanced math. For example, it can compute square roots. This program makes the computer print the square root of 9:
#include <iostream.h>
#include <math.h>
void main()
{
cout <<sqrt(9.0) <<endl;
}
The computer will print 3.
Say sqrt(9.0) rather than sqrt(9), because the number you find the square root of should be double-precision, not an integer. If you make the mistake of saying sqrt(9), Visual C++ 6.0 will print the correct answer but slowly; some older versions of C & C++ will print a wrong answer.
The program’s top line makes the computer include an I/O stream header (containing the definition of cout and other I/O words). The program’s second line tells the computer to include a math header (containing the definition of sqrt and other advanced-math functions).
Besides sqrt, you can use other advanced math functions. All advanced-math functions require that you use double-precision numbers and say #include <math.h>. Here’s a list of those advanced-math functions:
To handle exponents, you can use sqrt (square root), exp (exponential power of e), log (logarithm base e), and log10 (logarithm base 10). You can also use pow: for example, pow(3.0,2.0) is 3.0 raised to the 2.0 power.
For trigonometry, you can use sin (sine), cos (cosine), tan (tangent), asin (arcsin), acos (arccosine), atan (arctangent), sinh (sine hyperbolic), cosh (cosine hyperbolic), and tanh (tangent hyperbolic). You can also use atan2: for example, atan2(y,x) is the arctangent of y divided by x.
For absolute value, use fabs (floating absolute). For example, fabs(-2.3) is 2.3.
To round, use floor (which rounds down) or ceil (which stands for “ceiling” and rounds up). For example, floor(26.319) is 26.0, and ceil(26.319) is 27.0.
Numeric variables
Like BASIC, C++ lets you use variables. For example, you can say:
n=3;
A variable’s name can be short (such as n) or long (such as town_population_in_1999). It can be very long: up to 247 characters long. The name can contain letters, digits, and underscores, but not blank spaces. The name must begin with a letter or underscore, not a digit.
Before using a variable, say what type of number the variable stands for. For example, if n and town_population_in_1999 will stand for numbers that are ints and mortgage_rate will stand for a double, begin your program by saying:
#include <iostream.h>
void main()
{
int n, town_population_in_1999;
double mortgage_rate;
If n is an integer that starts at 3, you can say —
int n;
n=3;
but you can combine those two lines into this single line:
int n=3;
Here’s how to say “n is an integer that starts at 3, and population_in_1999 is an integer that starts at 27000”:
int n=3, population_in_1999=27000;
Increase
The symbol ++ means “increase”. For example, ++n means “increase n”.
This program increases n:
#include <iostream.h>
void main()
{
int n=3;
++n;
cout <<n <<endl;
}
The n starts at 3 and increases to 4, so the computer prints 4.
Saying ++n gives the same answer as n=n+1, but the computer handles ++n faster.
The symbol ++ increases the number by 1, even if the number is a decimal. For example, if x is 17.4 and you say ++x, the x will become 18.4.
Decrease
The opposite of ++ is --. The symbol -- means “decrease”. For example, --n means “decrease n”. Saying --n gives the same answer as n=n-1 but faster.
Strange short cuts
If you use the following short cuts, your programs will be briefer and run faster.
Instead of saying n=n+2, say n+=2, which means “n’s increase is 2”. Similarly, instead of saying n=n*3, say n*=3, which means “n’s multiplier is 3”.
Instead of saying ++n and then giving another command, say ++n in the middle of the other command. For example, instead of saying —
++n;
j=7*n;
say:
j=7*++n;
That’s pronounced: “j is 7 times an increased n”. So if n was 2, saying j=7*++n makes n become 3 and j become 21.
Notice that when you say j=7*++n, the computer increases n before computing j. If you say j=7*n++ instead, the computer increases n after computing j; so j=7*n++ has the same effect as saying:
j=7*n;
++n;
How to input
This program predicts how old you’ll be ten years from now:
Program Meaning
#include <iostream.h>
void main()
{
int age; The age is an integer.
cout <<"How old are you? "; Ask “How old are you? ”.
cin >>age; Wait for the human to input an age.
cout <<"Ten years from now, you'll be " <<age+10 <<" years old.\n"; Printout.
}
In that program, “cin” is pronounced “C in” and means “C++ input”. It’s the opposite of “cout”. After the “cin”, make sure you type “>>” (which is pronounced “to” and is the opposite of “<<”). Here’s how to pronounce that cin line: “C in to age semicolon”. Here’s a sample run:
How old are you? 27
Ten years from now, you'll be 37 years old.
(Below that, the computer will print its usual message of “Press any key to continue”.)
The next program converts feet to inches. It even handles decimals: it can convert 1.5 feet to 18.0 inches.
Program Meaning
#include <iostream.h>
void main()
{
double feet; The number of feet is double-precision.
cout <<"How many feet? "; Ask “How many feet? ”.
cin >>feet; Wait for the human to input how many feet.
cout <<"That makes " <<feet*12 <<" inches.\n"; Print the result.
}
Arrays
Like BASIC, JavaScript, and Java, C++ lets you create arrays. For example, if you want x to be a list of 3 double-precision numbers, begin your program by saying:
double x[3];
That says x will be a list of 3 double-precision numbers, called x[0], x[1], and x[2]. Notice that C++ starts counting at 0. (PASCAL starts counting at 1 instead; PASCAL would call those numbers x[1], x[2], and x[3].)
Here’s a complete C++ program using that array:
#include <iostream.h>
void main()
{
double x[3];
x[0]=10.6;
x[1]=3.2;
x[2]=1.1;
cout <<x[0]+x[1]+x[2] <<endl;
}
The computer will print the sum, 14.9.
Notice that if you say double x[3], you can refer to x[0], x[1], and x[2], but not x[3]. If you accidentally refer to x[3], you’ll be creating a runaway pointer.
If you want x to be a table having 2 rows and 3 columns of double-precision numbers, begin your program by saying:
#include <iostream.h>
void main()
{
double x[2][3];
Notice that C++ says x[2][3]. If you accidentally say x[2,3] instead of x[2][3], you’ll have a runaway pointer.
Since C++ always starts counting at 0 (not 1), the number in the table’s top left corner is called x[0][0].
Logic
Like most computer languages, C++ lets you say “if”, “while”, “for”, and “goto” and create comments and subroutines. Here’s how.…
If
If a person’s age is less than 18, let’s make the computer say “You are still a minor.” Here’s the fundamental line:
if (age<18) cout <<"You are still a minor.\n";
Notice you must put parentheses after the word “if”.
If a person’s age is less than 18, let’s make the computer say “You are still a minor.” and also say “Ah, the joys of youth!” and “I wish I could be as young as you!” Here’s how to say all that:
if (age<18)
{
cout <<"You are still a minor.\n";
cout <<"Ah, the joys of youth!\n";
cout <<"I wish I could be as young as you!\n";
}
Since that “if” line is above the “{”, the “if” line is a structure line, similar to a void main() line, and does not end in a semicolon.
Here’s how to put that structure into a complete program:
#include <iostream.h>
void main()
{
int age;
cout <<"How old are you? ";
cin >>age;
if (age<18)
{
cout <<"You are still a minor.\n";
cout <<"Ah, the joys of youth!\n";
cout <<"I wish I could be as young as you!\n";
}
else
{
cout <<"You are an adult.\n";
cout <<"Now we can have some adult fun!\n";
}
cout <<"Glad to have met you.\n";
}
If the person’s age is less than 18, the computer will print “You are still a minor.” and “Ah, the joys of youth!” and “I wish I could be as young as you!” If the person’s age is not less than 18, the computer will print “You are an adult.” and “Now we can have some adult fun!” Regardless of the person’s age, the computer will end the conversation by saying “Glad to have met you.”
The “if” statement uses this notation:
Notation Meaning
if (age<18) if age is less than 18
if (age<=18) if age is less than or equal to 18
if (age==18) if age is equal to 18
if (age!=18) if age is not equal to 18
if (age<18 && weight>200) if age<18 and weight>200
if (age<18 || weight>200) if age<18 or weight>200
Look at that table carefully! Notice that in the “if” statement, you should use double symbols: you should say “==” instead of “=”, say “&&” instead of “&”, and say “||” instead of “|”. If you accidentally say “=” instead of “==”, the computer will print wrong answers. If you accidentally say “&” instead of “&&” or say “|” instead of “||”, the computer will print right answers but too slowly — and give you a warning.
While
Let’s make the computer print the word “love” repeatedly, like this:
love love love love love love love love love etc.
love love love love love love love love love etc.
love love love love love love love love love etc.
etc.
This program does it:
#include <iostream.h>
void main()
{
while (1) cout <<"love ";
}
In that program, the “while (1)” means: do repeatedly. The computer will do cout <<“love ” repeatedly, looping forever — or until you abort the program by using one of these methods:
Method 1: while holding down the Ctrl key, tap the C key.
Method 2: while holding down the Ctrl key, tap the PAUSE key.
Method 3: click the window’s X box then click “Yes”.
Let’s make the computer start at 20 and keep counting, so the computer will print:
20
21
22
23
24
25
26
27
28
29
30
31
32
etc.
This program does it:
Program Meaning
#include <iostream.h>
void main()
{
int i=20; Start the integer i at 20.
while (1) Repeat these lines forever:
{
cout <<i <<endl; print i then press ENTER
++i; increase i
}
}
It prints faster than you can read.
To pause the printing, press the PAUSE key.
To resume the printing, press the ENTER key.
To abort the program, press ENTER, then press Ctrl with PAUSE.
In that program, if you say “while (i<30)” instead of “while (1)”, the computer will do the loop only while i remains less than 30; the computer will print just:
20
21
22
23
24
25
26
27
28
29
Instead of saying “while (i<30)”, you can say “while (i<=29)”.
For
Here’s a more natural way to get that output of numbers from 20 to 29:
#include <iostream.h>
void main()
{
for (int i=20; i<=29; ++i) cout <<i <<endln;
}
In that program, the “for (int i=20; i<=29; ++i)” means “Do repeatedly. Start the integer i at 20, and keep repeating as long as i<=29. At the end of each repetition, do ++i.”
In that “for” statement, if you change the ++i to i+=3, the computer will increase i by 3 instead of by 1, so the computer will print:
20
23
26
29
The “for” statement is quite flexible. You can even say “for (int i=20; i<100; i*=2)”, which makes i start at 20 and keep doubling, so the computer prints:
20
40
80
Like “if” and “while”, the “for” statement can sit atop a group of indented lines that are in braces.
Goto
You can say “goto”. For example, if you say “goto yummy”, the computer will go to the line whose name is yummy:
#include <iostream.h>
void main()
{
cout <<"my dog ";
goto yummy;
cout <<"never ";
yummy: cout <<"drinks whiskey\n";
}
The computer will print:
my dog drinks whiskey
Comments
To put a comment in your program, begin the comment with the symbol //. The computer ignores everything that’s to the right of //. Here’s an example:
// This program is fishy
// It was written by a sick sailor swimming in the sun
#include <iostream.h>
void main()
{
cout <<"Our funny God\n"; // notice the religious motif
cout <<"invented cod\n"; // said by a nasty flounder
}
The computer ignores all the comments, which are to the right of //.
While you type the program, the computer makes each // and each comment turn green. Then the computer ignores everything that’s turned green, so the computer prints just:
Our funny God
invented cod
Subroutines
Like most other languages, C++ lets you invent subroutines and give them names. For example, here’s how to invent a subroutine called “insult” and use it in the main routine:
Program Meaning
#include <iostream.h> the program will use I/O
void insult(); the program will use insult
void main() Here’s the main routine:
{
cout <<"We all know...\n"; print “We all know...”
insult(); do the insult
cout <<"...and yet we love you.\n"; print the ending
}
void insult() Here’s how to insult:
{ x
cout <<"You are stupid!\n"; print “You are stupid!”
cout <<"You are ugly!\n"; print “You are ugly!”
} x
The computer will print:
We all know...
You are stupid!
You are ugly!
...and yet we love you.
In that program, the top two lines warn the computer that the program will use I/O and a subroutine called “insult”. The next few lines, beginning with void main(), define the main routine. The bottom few lines, beginning with void insult(), define the subroutine called “insult”.
Whenever you write a subroutine’s name, you must put parentheses afterwards, like this: insult(). Those parentheses tell the computer: insult’s a subroutine, not a variable.
Here’s another example:
Program Meaning
#include <iostream.h> the program will use I/O
void laugh(); the program will use laugh
void main() Here’s the main routine:
{
laugh(); the main routine says to laugh
}
void laugh() Here’s how to laugh:
{ x
for (int i=1; i<=100; ++i) cout <<"ha "; print “ha ” a hundred times
cout <<endl; then press ENTER
} x
The main routine says to laugh. The subroutine defines “laugh” to mean: print “ha ” a hundred times and then press ENTER.
Let’s create a more flexible subroutine, so that whenever the main routine says laugh(2), the computer will print “ha ha ”and ENTER; whenever the main routine says laugh(5), the computer will print “ha ha ha ha ha ” and ENTER; and so on. Here’s how:
Program Meaning
#include <iostream.h> the program will use I/O
void laugh(int n); the program will use laugh(n)
void main() Here’s the main routine:
{
cout <<"Here is a short laugh: ";
laugh(2); do laugh(2), so print “ha ha ”
cout <<"Here is a longer laugh: ";
laugh(5); do laugh(5), so print “ha ha ha ha ha ”
}
void laugh(int n) Here’s how to laugh(n):
{ x
for (int i=1; i<=n; ++i) cout <<"ha "; print “ha ”, n times
cout <<endl; then press ENTER
} x
The computer will print:
Here is a short laugh: ha ha
Here is a longer laugh: ha ha ha ha ha
Average Let’s define the “average” of a pair of integers, so that “average(3, 7)” means the average of 3 and 7 (which is 5), and so a main routine saying “i=average(3, 7)” makes i be 5.
This subroutine defines the “average” of all pairs of integers:
int average(int a, int b)
{
return (a+b)/2;
}
The top line says, “Here’s how to find the average of any two integers, a and b, and make the average be an integer.” The next line says, “Return to the main routine, with this answer: (a+b)/2.”
Here’s a complete program:
Program Meaning
#include <iostream.h> the program will use I/O
int average(int a, int b); the program will use average(a, b)
void main() Here’s the main routine:
{
int i; make i be an integer
i=average(3, 7); make i be average(3, 7)
cout <<i <<endl; print i
}
int average(int a, int b) Here’s how to compute average(a, b):
{ x
return ((a+b)/2); return this answer: (a+b)/2
}
In that program, the main routine is:
int i; make i be an integer
i=average(3, 7); make i be average(3, 7)
cout <<i <<endl; print i
You can make that main routine be shorter, like this:
int i=average(3, 7); make the integer i be average(3, 7)
cout <<i <<endl; print i
You can make it be even shorter, like this:
cout <<average(3, 7) <<endl; print average(3, 7)
To make that program handle double-precision numbers instead of integers, change each int to double. After changing each int to double, the program will work, even if you don’t change 3 to 3.0 and don’t change 7 to 7.0.
Character variables
A variable can stand for a character. For example, suppose you’re in school, take a test, and get an A on it. To proclaim your grade, write a program containing this line:
grade='A';
Here’s the complete program:
Program Meaning
#include <iostream.h>
void main()
{
char grade; The grade is a character.
grade='A'; The grade is ‘A’.
cout <<grade <<endl; Print the character that’s the grade.
}
The computer will print:
A
In that program, you can combine these two lines —
char grade; The grade is a character.
grade='A'; The grade is ‘A’.
to form this single line:
char grade='A'; The grade is this character: ‘A’.
This program lets you input a grade:
#include <iostream.h>
void main()
{
char grade;
cout <<"Type the letter that is your grade: ";
cin >>grade;
cout <<"I'm amazed your grade is " <<grade <<endl;
}
It makes the computer say “Type the letter that is your grade: ”, then wait for the human to type a grade (such as B), then say “I’m amazed your grade is B”, so the screen looks like this:
Type the letter that is your grade: B
I'm amazed your grade is B
Strings of characters
A variable can stand for a whole string of characters:
#include <iostream.h>
void main()
{
char x[]="winks";
cout <<x <<endl;
}
That program makes x be this string of characters: “winks”. The cout line makes the computer print x, so the computer will print:
winks
In a string, the beginning character is called character 0; the next character is called character 1; the next character is called character 2. For example, here’s what happens if a string is named x:
The string’s beginning character is called x’s character 0 or x[0].
The next character is called x’s character 1 or x[1].
The next character is called x’s character 2 or x[2].
So if x is the string “winks”, here’s what happens:
x[0] is the string’s beginning character, which is ‘w’
x[1] is the next character, which is ‘i”
x[2] is ‘n’
x[3] is ‘k’
x[4] is ‘s’
x[5] is a special character that marks the end of the string
In the program you just looked at, if you change the cout line to this —
cout <<x[0] <<x[1] <<x[2] <<x[4] <<endl;
the computer will print x[0] then x[1] then x[2] then x[4], so the computer will print:
wins
In the program above, if you change the cout line to this —
cout <<x+1 <<endl;
The computer will print x but skip 1 character; it will print:
inks
Here’s how to input a string:
#include <iostream.h>
void main()
{
char firstname[81];
cout <<"What is your first name? ";
cin >>firstname;
cout <<"I like the name " <<firstname <<"very much!\n";
}
In that program, the char line says firstname can be a string of up to 81 characters. Since the computer’s screen is 80 characters wide, 81 is a fairly safe number: it’s big enough to hold a whole line of 80 characters, plus 1 end-of-string mark. When writing a program that inputs a string, it’s a good habit to put at least 81 in your program’s char line.
If you put in a much smaller number instead, such as 10, you run the risk that the human will input more characters than you reserved space for, and you’ll have a runaway pointer than can crash your program (and, if you’re unlucky, crash your operating system and your hard disk).
Even the number 81 is not totally safe, since the operating system lets the human input up to 254 characters (by continuing the typing onto the line below). To be totally safe, you’d have to change the number 81 to 255 (to allow 254 characters plus an end-of-string mark).
That program makes the computer ask “What is your first name? ” then wait for the human to type a first name. For example, if the human’s first name is Maria, the program makes the conversation go like this:
What is your first name? Maria
I like the name Maria very much!
Comparing strings
To put strings in an “if” statement, you must say “strcmp”, which warns the computer to do a “string comparison”.
For example, suppose x and y are strings, and you want to test whether they’re equal. Do not say “if (x==y)”. Instead, say “if (strcmp(x,y)==0)”, which means “if string comparison between x and y shows 0 difference between them”.
To test whether x’s string comes before y’s in the dictionary, do not say “if (x<y)”. Instead, say “if (strcmp(x,y)<0)”.
To make the computer understand “strcmp”, say “#include <string.h>” at the top of your program, so your program begins like this:
#include <iostream.h>
#include <string.h>
Copying strings
If x is a string, and you want to make y be the same string, do not say “y=x”. Instead, say “strcpy(y,x)”, which means “make y be a copy of the string x”.
Reserve space for y. For example, if x is a string that might contain up to 20 characters plus an end-of-string mark (making a total of 21 characters), warn the computer that y might contain 21 characters also, by saying “char y[21]”.
To make the computer understand “strcpy”, say “#include <string.h>” at the top of your program.
How C differs from C++
C++ is a modernized version of C. You should write programs by using C++, not C.
If you’re looking at an old program that was written in C, here’s how to understand it….
The program’s name
Visual C++ lets you write programs in C++ or C. To write a program in C++, the program’s name should end in .cpp. To write a program in C, the program’s name should end in .c.
Void
In C++, a program must say void main(). The same is true in most versions of C, but some early versions C let you omit the word “void”.
Indenting
The computer doesn’t care how you indent.
Nearly every C++ programmer does not indent the braces but does indent the lines between them. The C++ editor assumes you’ll follow that tradition, so it automatically indents the lines between the braces but does not indent the braces.
C programmers are less consistent: some indent the braces also; some move the top brace to the end of the preceding line instead of putting it on a separate line.
Where to say int
In C++, you can say “int i” anywhere in your program. In C, “int i” must be placed at the top of a group of indented line.
In C++ you can say:
for (int i=20; i<=29; ++i)
In C you must split that line into two lines —
int i;
for (i=20; i<=29; ++i)
and make sure the “int i” is at the top of a group of indented lines.
Comments
In C++, a comment begins with // and continues to the end of the line. In C, a comment begins with /* and continues until it reaches */, even if */ is on a different line.
Input and output
In C++, you output by saying “cout”, you input by saying “cin”, and you make the computer understand those words by putting this line at the top of your program:
#include <iostream.h>
In C, you output by saying “printf” or “puts” or “putchar”, you input by saying “scanf” or “gets” or “getchar”, and you make the computer understand those words by putting this line at the top of your program:
#include <stdio.h>
Unfortunately, those C words are awkward to use. Here are examples.…
Print a string To print a string onto the screen, you can say printf.
C++: cout <<"I love you";
C: printf("I love you");
To print a string message followed by ENTER, say “\n” or “puts”.
C++: cout <<"I love you\n";
C (method 1): printf("I love you\n");
C (method 2): puts("I love you");
C understands “\n” but not “endl”.
Print a number The “puts” function can print a string but not a number. To print an integer, say printf and “%d”. For example, here’s how to print the answer to 750+12:
C++: cout <<750+12;
C: printf("%d",750+12);
If you have 750 apples and buy 12 more, how many apples will you have? Here’s how to do that math and put the answer into a sentence that says “You will have ___ apples”:
C++: cout <<"You will have " <<750+12 <<" apples";
C: printf("You will have %d apples",750+12);
To print two answers on the same line, say %d twice:
C++: cout <<21+4 <<" " <<68+1;
C: printf("%d %d", 21+4, 68+1);
The %d is just for an integer. For a double-precision number, say %g instead; for a character, say %c instead; for a string, say %s instead.
Print a character To print a single character, either say printf and “%c” or say putchar:
C++: cout <<'A';
C (method 1): printf("%c",'A');
C (method 2): putchar('A');
Input a number To input an integer easily, say scanf and “%d”. For example, here’s how to input an integer age:
C++: cin >>age;
C: scanf("%d",&age);
Notice that scanf requires you to put the symbol “&” before the variable’s name. The “%d” is just for an integer. For a double-precision number, say “%lf” instead, which means “long floating-point”, which is a fancy way of saying “double precision”.
Input a character To input a character, say scanf and “%c” or say getchar(). For example, here’s how to input a character that’s a grade:
C++: cin >>grade;
C (method 1): scanf("%c",&grade);
C (method 2): grade=getchar();
The scanf method requires the user to type a grade and then press ENTER. The getchar method requires the user to type just a grade without pressing ENTER afterwards.