You are on page 1of 13

Turbo C++ Tutorial

------------------
By Ken Rockot
Table of Contents
-----------------
Part 1. Introduction
Part 2. Basic C++ Program Stucture
Part 3. Text Stuff
Part 4. User Input
Part 5. Example Program #1
Part 6. Math
Part 7. Arrays
Part 8. String Variables
Part 9. Graphics
Part 10. Example Program #2
Part 11. Conclusion
Part 1. Introduction
--------------------
All I really have to say here is make sure you understand Part 2 before
going any further. I'm probably not going to test most source code I put
in here, so if it doesn't work, ask me about it. If you have any problems
with understanding this, or any other questions or anything, just ask me
about it. If you happen to see a function in a program that I haven't
explained in the tutorial, try looking at the Index under the Help menu in
your Turbo C++ editor. If you can't understand it by reading it's description
just E-Mail me.
To ask me crap, my E-Mail address is: Rockotman@juno.com
KMissle@aol.com
I recommend that you send mail to my AOL name, because I don't check my
Juno mail as often.
Part 2. Basic C++ program structure
-----------------------------------
Alright. Hopefully, by the time you are done with this you might know C++
well enough that you can do something pretty cool on it. Okay, first a
little about header files. A header file is a simple file that defines
different functions. Since you need a header file for just about every C++
function, there is built-in command, #include. It would be used kinda like
this:
#include <graphics.h>
Throughout this tutorial, several source code fragments will be shown to
give a general idea of how you use a function or something. For most programs
you will ever make, you will almost definately use these three lines at the
start of your program:
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>
Those are the most important header files. They contain the majority of all
C++ functions. Okay, now to start writing your first program. I strongly
suggest that you know QBasic, because if not, you will probably
have no idea what I'm talking about a lot of the time. Every program's
basic structure is first you have the included header files. Then, any
constants, which are defined by #define. Say you want VAR to ALWAYS equal
3 and not be changable (a constant), you'd simply type:
#define VAR 3
Another important note (and it IS important) is that C++ is case sensitive.
All variables are case sensitive, so VAR is different from var, both of which
are different from VaR. Functions are also case sensitive. So be careful.
After defines, any global variables (In QB, they're 'DIMmed' using DIM SHARED)
are defined. I'll get into that later. Then, we have any functions to
be used in the program. Anyone who know QBasic should know about SUBs and
FUNCTIONs. If you want to make a function (a SUB that returns a value), you
would define it as you would a variable. Then you have any parameters that
you want passed to the function in parentheses, defined with int or whatever
(more on defining crap later) Say you want a function called pointless to
return the value of a number you give it, minus one:
int pointless (int uservar)
{
return (uservar-1);
}
Notice the ; at the end of the line. You need this at the end of every
line (well...most of them). This is helpful because unlike QBasic (ya know,
the cheap, crappy, slow language), you can have multi-line statements, because
once C++ starts reading a line, it keeps reading until it hits a ;. Then it
starts again as a new statement. Any lines beginning with a # don't need a ;
at the end.
Also, notice the { and the }. Okay. Well, they are used for several
statements. They are used for while, if, for, switch (like SELECT CASE), and
any functions. In C++, there is no NEXT, END FUNCTION, END SUB, WEND, END IF,
or END SELECT. When you use a command like for, if, while, etc..., You do
not include a ; at the end of the if (or whatever other) statement. You just
type that line, then on the next one, put a {. That specifies the start of
the while, if, switch, or for clause. A } specifies the end. Anything on
the lines in between them are executed during that clause. There. Glad
that's over with.
As for the main program, that's defined by:
void main ( void )
{
}
The { specifies the start of the program, and the } specifies the end.
I always put all my functions that I make above the main program, because
it's easier. You can put them below, but you just have to type more crap,
so I recommend you don't. Oh, and another quick thing before I show you some
examples. To make a comment (In QB, it's '), use //. To make a multi-line
comment, start the comment with /* and everything after that will be a comment
until C++ hits a */. Any comments appear dark gray in the main editor. Okay
these examples show stuff about some the stuff I've said so far:
// A One-lined comment
/* A
multiple-lined
comment */
// Please note that if you run this program, you'll get absolutely no output.
#include <conio.h> // May not use them all in this particular program,
#include <stdlib.h> // but hey, what the heck?
#include <stdio.h> // <--- The header files
#define A 3 // <--- Our constants
#define B 96 // <---
int var1,var2; // <--- Global variables. These are integers.
int pointless ( int uservar ); //Typed in before main.
{
return (uservar+);
}
void main ( void ) //Main program
{
long pointless_variable; /* Yep. C++ allows _'s to be used in
variable/function names. */
pointless_variable=1000000;
pointless(6);
}
Another thing you may have noticed. Instead of making main a function
and defining it with int, long, or something, I defined it with void. This
is easy to explain. If you define a function as void, it's basically a SUB.
It doesn't return a value.
Since I've been talking about defining variables, maybe you want to know
how to define certain types as compared to the QBasic method.
-----------------------------------------------------------
| Type: | QBasic: | C++ |
|---------------------------------------------------------|
| | | |
| Integer | DIM x AS INTEGER | int x; |
| Long Integer | DIM x AS LONG | long x; |
| Single-Precision | | |
| Floating Point | DIM x AS SINGLE | float x; |
| Double-Precision | | |
| Floating Point | DIM x AS DOUBLE | double x; |
-----------------------------------------------------------
There are others like strings, streams, registers, structs, unions, etc...
but as for now just stick with the above stuff.
Part 3. Text Stuff
------------------
In QBasic, there's PRINT. Well, in C++, printf is the equivilant. It
prints text on the screen. Here's how to basically use it:
printf ("Hi.");
That's very basic. QBasic automatically goes to the next line after a PRINT
staement. Not C++. To start a new line, any where in the string to print,
type \n and it will start a new line. Ex: printf ("Hi.\n"); That would
print Hi. just like QBasic would; move down a line after printing. Another
thing you can put in a printf statement is %d. This prints an integer
variable inside the printed string. Then, after the closing ", put a comma
and type the variable name to be printed. Example:
int B;
printf ("Variable B = %d",B);
If you want to use more that one variable in the printing, you just specify
them after the closing ", in respective order of what %d you want them to
appear at, and seperate them with commas. Example:
int A,B=3; //As shown with B, a var.'s value can be set while defining it.
A=5;
printf ("A = %d and B = %d.",A,B);
Output:
A = 5 and B = 3.
Some other QBasic text-related statements can be quickly translated.
QBasic: C++:
LOCATE 5,6 gotoxy(6,5); (Row and column are reversed in C++)
COLOR 15 textcolor(15);
COLOR 1,3 textcolor(1);
textbackground(3); (Background can only be 0-7)
Some other C++ text-related functions:
clreol(); Clear the current row without moving the text cursor at all
clrscr(); Clear the text screen and move cursor to 1,1
That about does it for the basic text stuff.
Part 3. If/While/Switch/For
---------------------------
If:
In QBasic, you use like IF a = 0 THEN PRINT a. In C++:
if (a==0) printf("%d",a);
I just put a ; at the end instead of using {} because only one thing happens
in the statement. If you want to check to see if a variable = something,
do not type: if(var=0) That will actually set a to 0 and then check if it
is not equal to 0. It's hard to explain, so I won't, but just don't do it.
You want to type: if(var==0).
To use else in C++, close the if statement with a }. Then start the else
statement followed by a {. Then do whatever and close it with a }.
Example:
if (b==0)
{
textcolor(4);
printf("b=0\n");
}
else
{
textcolor(3);
printf("b!=0");
}
While:
QBasic: WHILE var=0
...
...
WEND
C++: while (!var) //! is an abbreviation for NOT in C++
{ //Like in QBasic not equal is <>. In C++ it's !=
}
If you know QBasic then you know what while does. Here's a small example in
C++:
int a=0;
while (a<10)
{
a+=10; //a+=10 is an short way of saying a=a+10. This will work with
//any math operation like %(MOD), /(div.), *(mult.),and - (sub.)
//While on the subject, a++ would add 1 to a, a-- sub.'s 1, etc.
printf("%d",a);
}
For:
In QBasic, you might do:
FOR i = 0 to 10
LOCATE 1,1
PRINT i
NEXT i
In C++, to get the same output, you'd do:
int i;
for (i = 0;i <= 10;i++)
{
gotoxy(1,1);
printf("%d",i);
}
The (i=0;i<=10;i++) needs some explaining. The format of a for statement
is as follows: for (exp1;exp2;exp3) { statements }. exp1 is executed
immediately before the loop. The loop keeps going until exp2 is not true.
exp3 is executed after every time the loop repeats.
Switch:
In QBasic, you might do:
a = 2
DO
SELECT CASE a
CASE 0
PRINT a
END
CASE 1
PRINT a
a = 0
CASE 2
PRINT a
a = 1
END SELECT
LOOP
In C++, you would do:
int a=2,i=0;
while (!i)
{
switch (a)
{
case 0: //You need a colon there
{
printf("%d",a);
exit(1);
}
break; //After the } to close a case statement, you need a break;.
//Except on the last case statement of the switch.
case 1:
{
printf("%d",a);
a=0;
}
break;
case 2:
{
printf("%d",a);
a=1;
}
} //Close the switch
} //Loop
Since there is no DO...LOOP in C++, just do what I did there...Use while
and have it loop until a variable does not = 0, but never actually change that
variable, so it will loop forever.
I think switch is also self-explanitory.
In closing of this topic, I'd like to just quickly explain how to use
compound statements for if, while, etc. Here's some examples:
QB: C++:
IF a = 1 if (a==1)
IF a = 1 AND b = 2 if ((a==1)&&(b==2))
WHILE a = 0 while (!a)
WHILE a = 0 OR b = 0 while ((!a)||(!b))
That basically just shows that || means OR and && means AND.
Part 4. User Input
------------------
Getting user input is not too complicated. Here, I'm just going to tell
you some functions to get user input from the keyboard.
kbhit(); If no key is currently being pressed, kbhit() = 0. If a key is
being hit, it returns nonzero (usually -1).
getch(); Like SLEEP, in that it waits for a key to be pressed, only it
equals the key's character. For example, if you had the line:
a = getch()
and it was being executed, and you pressed w, a would then
equal w.
scanf(format, variables)
scanf is like INPUT, in that it you type all you want, until Enter
is pressed. Format most likely will be "%d" or "%s" or a combo.
It can be other things, though. Refer to your help file for
C++ for more. Variables work like in printf.
Here's an example:
Code:
int a;
printf ("Enter an integer: ");
scanf("%d",a);
clrscr();
printf("You entered %d.",a);
Line of code being executed: scanf("%d",a);
Program Output: Enter an integer:
You type: 56
Final Output: You entered 56.
Not too difficult.
That's enough for some standard input for now. Go try and make a program
or something now. I bet you didn't realize it, but that's a lot of crap that
I've gone over now. Read the next part for a program that uses I think
everything, if not, most of the stuff I have gone over so far.
Part 5. Example Program #1
--------------------------
/* The output of this program isn't really supposed to make sense, in case you
were wondering. */
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#define const_var 100
int global_variable_1;
void Useless_SUB (int Useless_User_Input)
{
int a=10;
while (a!=0)
{
a--;
printf("a=%d\n",a);
}
printf("global_variable_1=%d\n",global_variable_1);
printf("You inputed: %d\n",Useless_User_Input);
}
int Useless_FUNCTION (int Useless_Crap)
{
int a;
textcolor(15);
textbackground(4);
for (a=0;a<=10;a++)
{
printf("a=%d\n",a);
printf("getch() is waiting...\n");
getch();
}
return (1);
}
void main (void)
{
int i;
i=0;
clrscr();
printf("Gimme a number: ");
scanf("%d",i);
clrscr();
Useless_SUB(i);
i=Useless_FUNCTION(4);
printf("Useless_FUNCTION returned %d when 4 was passed to it.\n",i);
getch();
printf("Press any to use gotoxy to go to 1,1, then use clreol to clear line 1.
\n");
getch();
gotoxy(1,1);
clreol();
getch();
clrscr();
printf("Press q.");
i=0;
while (!i)
{
if(kbhit())
{
switch (getch())
{
case 'q':i=1;
}
}
}
printf("Okay.");
printf("By the way, const_var = %d",const_var);
}
// End of program
If you run that, you'll see a lot of crap that makes no sense. Just look
at the code. It's just to show how certain commands work.
Part 6. Math
------------
The math in C++ is pretty simple. It works the same as in QBasic, except
there are a few better ways of doing things. Some of this was explained
earlier, but I'll show it again. In QBasic, you can do something like:
a = a + 5 or a = a / b. In C++, you CAN do it that way, but there is a
shorter method. For thos same two examples, you could do:
a+=5 or a/=b. That's simple. Also, a lot of times, like in a loop or
something you might want to keep adding 1 to a variable or something like
that. Instead of doing a = a + 1, or even a+=1, you can do a++. a-- just
subtracts one. That's also simple.
Here's a little table:
Greater than: >
Less than: <
Verify equality: ==
Set equal to: =
Greater than or equal to: >=
Less than or equal to: <=
Not equal to: !=
Not (equals 0): !
For trig. or complex math, you need to include a new header file. This file
is called math.h. So in a program, in the beginning, you'd just add the line
#include <math.h>
Then you can use sin, cos, tan, etc...
Another cool math function in math.h is hypot, which returns the hypotenuse
of a right triangle, given the length of the two sides. In other words,
hypot (3,4); will return the hypotenuse of a right triangle whose two sides
have a length of 3 and 4. It calculates it using the pretty easy equation:
z^2 = x^2 + y^2, where z is the hypotenuse, x is one side's length and y is
the other side's length.
Also, functions like abs(), which gives the absolute value of a variable or
number, are the same as the QBasic ones.
Part 7. Arrays
--------------
Arrays are simple. In QBasic, you do DIM a(2). In C++, for the same thing,
you'd do: int a[2]; For a 2d array in QB, you'd do: DIM a(2,2). In C++, that
would be: int a[2][2]; That's very simple so I just though I'd clear that
up now. That was a short section, but if I didn't explain it, you might have
kept trying int a(2,2); or something.
Part 8. String Variables
------------------------
String variales are defined with char. Here are examples for different
types of strings.
//For an unknown/nonfixed-length string (most common)
char *a = "abcdefg";
//Fixed length
char a[4] = "abc";
//For an array of fixed-length strings
char a[5][4] = { "abc", "def", "ghi", "jkl", "mno" };
//For an array of unknown/nonfixed-length strings
char *a[] = { "FIRST_ITEM", "SECOND_ITEM", "THIRD_ITEM", "FOURTH_ITEM",
"FIFTH_ITEM" };
Note that it's not necessary to set the variables while defining them, like
all of the above examples showed. Like for the last example, you could do:
char *a[];
a[0]="FIRST_ITEM";
...etc...
Part 9. Graphics
----------------
There's a little thing that C++ uses for it's graphics. A little thing
called BGI. Now, those people who use 320x200 resolution with 256 color
graphics (SCREEN 13 in QBasic) a lot, might be quite disappointed, because
the BGI drivers that come with Turbo C++ have a max. capability of 16 colors,
although 640x480 is still supported. There are, however, ways to make your
own BGI drivers, and there are drivers on the Internet for just about any
resolution or amount of colors. For now, we'll just use the highest
resolution possible -- 640x480 - 16 colors. To use BGI, at least the BGI
we'll be using, you must copy EGAVGA.BGI into whatever directory you will
be running your program from. BGI stands for Borland Graphics Interface, by
the way. Okay. You first need to define a couple of variables. These
variables will be used by initgraph. These will be the ones we use:
int gr_mode=VGAHI, gr_drv=VGA, error;
Then we make a call to initgraph:
initgraph(&gr_drv,&gr_mode,"");
NOTE: You will need to include graphics.h to use BGI!
Now we need to check for errors:
error=graphresult();
if (error != grOk)
{
printf("Graphics Error: %s", grapherrormsg(error));
exit(1); //Exits program immediatly
}
There. You should be in 640x480 if all went well. Now for some graphics
functions. First I'll do simple QB -> C++ conversions.
QB: C++:
PSET (x,y),c putpixel(x,y,c);
LINE (x1,y1)-(x2,y2) line(x1,y1,x2,y2);
POINT (x,y) getpixel(x,y);
LINE -(x,y) lineto(x,y)
Other C++ functions:
setcolor(color);
Sets the current drawing color (usually for lines).
moveto(x,y);
Moves the current graphics cursor (used a lot with lineto) to x,y.
closegraph(); You must use this to uninitialize the graphics and restore
the video mode to text mode.
cleardevice(); Clears the graphics screen.
getmaxx(); Returns the maximum x coordinate on the screen.
getmaxy(); Returns the maximum y coordinate on the screen.
getmaxcolor(); Returns the maximum available color.
drawpoly(numpoints,pointarray);
This draws a polygon on the screen. The polygon is not automatically closed
so make sure the last point always equals the first point.
Example:
//Draws a green triangle
point[0]=0; //Evens are x's
point[1]=0; //Odds are y's
point[2]=100;
point[3]=100;
point[4]=0;
point[5]=100;
point[6]=0;
point[7]=0;
setcolor(2);
drawpoly(4,point);
fillpoly(...);
Same as drwapoly() except it fills it. Set the line color
with setcolor and set the fill pattern and color with setfillstyle (explained
below).
setfillstyle(pattern, color);
Color must equal a number from 0 to getmaxcolor().
Pattern must equal a number from 0 to 11. The patterns are explained below.
Pattern # | Description
-----------+---------------------
0 | Empty
1 | Solid
2 | Horizontal lines
3 | ///
4 | Thick ///
5 | Thick \\\
6 | \\\
7 | Light hatch
8 | Heavy crosshatch
9 | Interleaving line
10 | Widely-spaced dots
11 | Closely-spaced dots
setfillpattern(pattern_array,color);
If you want to use your own pattern, use this instead of, not with,
setfillstyle.
Color must be a number from 0 to getmaxcolor().
Patter_array is thme name of a user-defined string array which has a fixed
length of 8. The 8 characters need explaining. First I'll give an example.
char my_pattern[8] = { 170,170,170,170,170,170,170,170 };
setfillpattern(my_pattern,4);
That example will make the current fill pattern be verticle lines. Now we
need explaining. Each pattern consists of 64 pixels, 8 horizontally and
8 vertically. Each seperate character in the string stands for a horizontal
line in the pattern, giving us eight lines. A character can have a value
from 0 to 255. 255 in hex. is FF. In binary it is 11111111. If you look at
that binary number, you'll notice that 255 (the maximum value for a character)
in binary is 8 digits. Usually, you'll need a calculator to make a pattern.
170 in binary = 10101010. Therefore, if we put 8 170's in my_pattern, we will
have:
10101010
10101010
10101010
10101010
10101010
10101010
10101010
10101010
Anywhere where there's a 1 is where a pixel, of the color you set, will be
placed. Any 0's will be a pixel of the background color (defaulted to black).
Say you wanted diagonal lines like \\. Get a calculator. Okay. The first
line should look like:
10001000
Set your calculator to binary mode and enter 10001000. Convert that to
a decimal number. You get 136. There's your first character. Here's the
rest:
Binary: Decimal:
Second: 01000100 68
Third: 00100010 34
Fourth: 00010001 17
Fifth: 10001000 136
Sixth: 01000100 68
Seventh: 00100010 34
Eighth: 00010001 17
Therefore, you could now make a pattern like this:
char cool_pattern[8] = { 136,68,34,17,136,68,34,17 };
That would be \\.
setpalette(color1,color2); Sets the attributes of color1 to those of color2.
Example: setpalette(1,15);
That makes color 1 bright white instead of blue.
There are other methods of doing better, faster graphics, but they require
implementations of the Assembly language into your C++ program. Since this
is not a graphics tutorial, I won't cover how to make your own functions
to set the screen mode to 320x200 - 256 colors, and the functions to set
pixels and the palette in this screen mode. It also does it without the
use of BGI. If you would like a tutorial on that stuff, E-Mail me your
request (See Part 1. Introduction for E-Mail address). If I get enough
requests, I'll make one. As for now, though, that's enough for graphics.
Part 10. Example Program #2
---------------------------
//This program just does some stuff with graphics
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_PIXELS 10000
#define NUM_LINES 5000
void main (void)
{
int Gr_Driver=VGA, Gr_Mode=VGAHI, Error_Code;
initgraph(&Gr_Driver, &Gr_Mode, "");
Error_Code=graphresult();
if (Error_Code != grOk)
{
printf ("Graphics Error: %s", grapherrormsg(Error_Code));
exit(1);
}
cleardevice();
int i;
randomize();
for (i=0;i<=NUM_PIXELS;i++)
{
putpixel(rand()%640,rand()%480,(rand()%15)+1);
}
getch();
moveto(rand()%640,rand()%480);
for (i=0;i<=NUM_LINES;i++)
{
setcolor((rand()%15)+1);
lineto(rand()%640,rand()%480);
}
getch();
cleardevice();
char My_Pattern[8] = { 129, 0, 0, 24, 24, 0, 0, 129 };
setfillpattern(My_Pattern,4);
int Poly_Points[8];
Poly_Points[0]=0;
Poly_Points[1]=0;
Poly_Points[2]=0;
Poly_Points[3]=479;
Poly_Points[4]=639;
Poly_Points[5]=479;
Poly_Points[6]=639;
Poly_Points[7]=0;
fillpoly(4,Poly_Points);
i=0;
while (!i)
{
setpalette (4, rand()%16);
if (kbhit()) i=1;
}
closegraph();
}
Part 11. Conclusion
-------------------
That's about it. This is a short, very basic tutorial, though. I typed
this in a total of about 4 or 5 hours. I think I included more than enough
information to make a good program. If you think there are any really
important things that I may have missed, let me know and I'll add them.

You might also like