C++

C++ is a common programming language. It was developed in the early 1980s by Bjarne Stroustrup. This program is also good for creating and using data abstraction, and object oriented design and programing. It has nice improvements over C, an earlier programming language, yet keeps the simplicity and speed of C.

C++ has preprocessor directives, which let the compiler know what groups of basic commands will be needed in the program. The compiler is the part of the software that interprets high level language into hardware code. For example, if part of your programming code is:

cout<<“You Win”; /*This will print out the text written in quotation marks on the screen. The slash and star tell the computer to ignore text after it, allowing for comments to be added, such as this one. The semi-colon ends the statement or command. */

// These two slashes tell the computer to ignore text for the rest of that line.

cout<<endl; /*The endl, the command for "end line," moves the cursor to the next line.*/

 

Then you must let the compiler know to include the set of commands “cout” is a part of. Assuming it is a part of the header file, iostream.h, then at the top of the program you would put:

#include <iostream.h>

 

A header file lets the compiler know where to find the definitions of the commands. There are many other header files, ones that include math functions, graphics functions, and functions dealing with the screen’s color and keyboard interaction. Some header files, however, are specific to the compiler or computer.

C++ has many data types. Here is a chart telling about each

Name

Bits

Range

Also Called

char (a character)

8

-128 to 127

signed char

unsigned char

8

0 to 255

int (an integer)

16

-32768 to 32767

signed, signed int, short, short int, signed short int

unsigned int

16

0 to 65535

unsigned, unsigned short, unsigned short int

long

32

-2147483648 to 2147483647

long int, signed long int

unsigned long

32

0 to 4294967295

unsigned long int

float (floating-point)

32

7 digits

double

64

15 digits

long float

long double

19 digits

pointer address size

16

0 to 65535

far pointer

32

0 to 4394967295

Arrays are also a type of data and can be made with any data type. An array is a group of values. All of these values have one variable name, but can be defined singly by “subscripting” the variable with brackets and the number of that element’s place in the array. For example, if I had an array of five int (integer) values called x:

int x[5];

 

Even though there are 5 elements in the array, the computer starts counting at zero. Let’s say now, I wanted to assign the first and last elements in the array to one:

x[0] = 1;

x[4] = 1;

An array of type char (characters) is called a string.

Pointers are variables whose values are the addresses of other objects in memory. Each pointer has to be associated with the type of variable to which it will be pointing. To specify that a variable will be a pointer, one would add an asterisk in front of the variable when defining it. For example:

int a, *ip;

char *cp, b;

Of these variable definitions, “ip” is a pointer to an int type and “cp” is a pointer to a char type. “a” and “b” are not pointers. To initialize a pointer, the ampersand, &, is used as, “the address of”:

a = 1;

ip = &a; //ip now points to a

b=’b’;//The ' ' around b indicated that b is a character.

cp = &b; //cp now points to b

Now, ip, as a pointer can be used to change the value of a. The asterisk, *, is now used as, “the value at”:

*ip++; //now a = 1

cout<<*ip; //the output is 2

But ip’s value can also change, this changes what it is that ip is pointing to, it is now pointing to whatever value is next in the memory.

ip++;

To what ip will now point depends on how the compiler stores its variables of different types.

Operators represent operations in an expression. Operands are the object of the operation. Binary operators have two operands in an expression, and unary operators can have just one. If there is more than one operation in an expression, then it is a compound expression.

 

int x, y, z;

x=7; //x is the left operand, 7 is the right operand, = is the operator, this //statement sets the value of x to 7

y= abs (-7); //this is a compound expression; = and abs() are both operators, //abs() is a unary operator, this statement sets y to the //absolute value of -7

z = x + y; //the variables are operands, and = and + are operators, + is a //binary operator, it’s operands are x and y, this statement //sets the value of z to the sum of the values of x and y

Here is a chart of arithmetic, along with logical, equality, relational, assignment, increment, decrement, bitwise operators, and more, in order of precedence, meaning the operators at the top of the list would be executed first in a compound expression. I will explain just some of them.

Each lines lists operations which are of equal importance to the computer, and done in order from left to right usually, unless otherwise noted.

Operators Associativity

1. parentheses, brackets, etc. ( ) [] -> :: .

2. not, increment, decrement, ampersand, asterisk (when used with pointers), etc. ! ~ ++ -- & * (typecast) sizeof new delete These are done from right to left.

3. .* ->*

4. * / %

5. + -

6. << >>

7. < <= > >=

8. == !=

9. &

10. ^ ->R

11. |

12. &&

13. ||

14. ?: These are done from right to left.

15. = *= /= %= += -= &= ^= |= <<= >>=

 

Arithmetic operators are like in simple math. They are all binary operators. The result of a division is truncated if the type of operands involved was not float (floating point). The modulus, %, is used with expressions without float types. It is represented by the percent sign. It calculates the remainder of the division:

x = 33 % 10; //this statement sets the value of x to the remainder of 33 / //10, which is 3

++ Increments (increases) a value by one, and -- decrements (decreases) a value by one. Symbols that are right in front of the = sign (not including the logical, relational, and equality operators) are also short hand. They apply the function before the equal sign to that variable and the value on the right side of the expression. For example:

x = 1;

y = 2;

z = 3;

x += 1; //this statement sets the value of x to x + 1, or 2

y *= z; //this statement sets the value of y to y * z, or 6

The logical "and" is represented by two ampersands. Any value except zero is considered true. The logical "or" is represented by ||. The == is an “is equal to” sign, used in if - statements. Greater than and less than signs are > and <, respectively greater than or equal to, and less than or equal to are >=, <=, respectively. They return a 1 if true, and a 0 if false.

Bitwise operators compare values bit by bit. To evaluate a bitwise operation, one must look at the values of the number in base 2. Each bit is compared to it’s parallel, with the given operation. For example:

z = 10 & 13; /* when comparing the binary values 1010 & 1101, we see that this statement sets the value of z to 1000, or 8. (If you need more help on base 2 numbers, goto the binary system)*/

The "sizeof" operator returns the number of bytes an expression, variable, or type, contains. The arithmetic "if" is used as in the following example. If the expression to the left of the question mark is true, the statement to the left of the colon is carried out. If it is false, the statement to the right of the colon will be executed.

 

cout<< (x > z ? x : z); // this statement will print out x if x is greater than cout<<endl; // z, otherwise, it will print out z

cout<< “x is” << (x % 2 ? “ ” : “ not”) << “ odd”; //this statement will tell cout<<endl; //us whether x is odd or not

 

The "if" statement can be used for things that need more than one statement executed in a specific case. The condition of an if statement is placed in parenthesis, and the statement to be executed, if true goes in braces, {}. If, however there is only one statement to be executed, it isn’t required to be in brackets. An "else" statement means just that, else.

if (x % 2) cout<<“x is even”;

else cout<<“x is odd”;

cout<<endl;

//---------------- A line such as this can be used to separate a thought

cout<<“x”;

if (x > z)

{

cout<<“ is greater than”;

}

else

{

if (x < z) cout<< “ is less than”;

else cout<< “ is equal to”;

}

cout<<“ z”<<endl;

 

The for loop is a very convenient command to use. In the following example, we work with an array of int type variables. I will explain the parts of a for loop, what they mean, and how they work.

int n, MAX = 10, r[MAX];

for (n=0; n<MAX; n++) /*of the three statements on this line, the left most one is executed first. Then, if the middle statement is true, it will perform anything within the braces one time. Then, it will perform the operation at the right. Next it checks again to see that the middle condition is true. If so, it continues in a loop until the condition is no longer true. If the condition is false, the computer will break out of the loop and continue the program. This for loop sets each value in the array to equal the value of it’s subscript, and prints it out, one element on each line.*/

{

x[n] = n;

cout<<x[n]<<endl;

}

One must be very careful when using a for loop, not to let it go continuously by mistake. Also, a common error, is letting the for loop execute one more time than it should, when working with arrays. In the above example, MAX should never = n, because there is no such x[MAX] or x[10]. The command “break” with a semicolon after it can be used as the statement following an if condition to get out of a for loop. Sometimes this is done in a purposely made continuous for loop; this however makes it no longer continuous:

for (n=MAX-1;;n--) //potentially continuous for loop

{

x[n] = 2n+1;

if (!n) break; //if n == 0, it will break out of the loop

}

A function is like an operation that the programmer writes. It can perform a simple task, or a mor challenging one. Functions are set up, or defined, at the beginning of the program with prototypes. A function can receive a variable, or some variables, perform a task with it, and return a value. In setting up a prototype, the type of value it will return is placed before the function’s name. The type(s) and name(s) of the variables being received by the function is placed in parentheses after the function name, and all of this is followed by a semicolon. If a function does not receive a value, a void is placed instead of the type and variable. If it does not return a value, a void is placed instead of a type. Then, in most programs, the main begins, which is where the program code can be written and functions can be called. In following program, the calculate function will receive two int type variables, and return their sum, to be displayed.

//==== This Program was written for the basic understanding of C++ ====

//================HEADERS=========================================

#include <math.h>

#include <stdio.h>

#include <conio.h>

#include <stdlib.h>

#include <string.h>

#include <iostream.h>

//=================PROTOTYPES====================================

void get_values (int &x, int &y);

int calculate (int x, int y);

void menu (void);

//=========================MAIN===================================

int main (void)

{

textcolor (WHITE); textbackground (BLUE); //sets the colors of the // text and background

clrscr (); //clears the screen from any previous output

int x, y, z;

get_values (x, y); // the function is called, in the parentheses are // the values with which it is called

cout<<“The sum of ” << x << “ and ” //The extra line does not make a

<< y <<“ is ”<<calculate (x,y); // difference, the only thing that

// finishes the statement is the // semicolon. The computer will goto

// the calculate function, then come // back to display the value it returns.

menu();//you will find out that even though there are things written

//below this point within main, the computer will never //reach them, because of the way the program is written

fflush (stdin);

getche(); //this waits to continue the program until any key is //typed

exit(0); //this finishes the program, and returns the value of 0.

}//end main

//====================FUNCTIONS=================================

void get_values (int &x, int &y) //notice no semicolon

{

cout<<“What numbers would you like to add? ”

cin>>x>>y; //this takes in two int type variables typed in by the user //of the program.

}//end get_values

//----------------------------------------------------------------

int calculate (int x, int y)

{

int ans;

ans = x+y;

return (ans);

}// end calculate

//----------------------------------------------------------------

void menu (void)

{

cout<<“Press Return to Start Again.”<<endl<<“Press Escape to Exit.”;

unsigned ch;

ch = getch ();//this sets the value of ch to the value of the key typed

if (ch==27) exit(0)//27 is the value of the escape key, this would

// end the program

if (ch==13) main();//13 is the value of the return key

}

 

Recursion is the act of a function calling itself.

Creating a struct is somewhat like creating another data type.

Classes are somewhat like structs, but they can have functions within them. They are used in object oriented programming.

If you would like, click on tic tac toe or pong to view the source code for the games we have. This was written in Turbo C++. They are both working programs. Go to our games section if you are interested in downloading them.