c++ guide for beginners

Guide to C++ Programming For Beginners

Estimated Read Time: 18 minute(s)
Common Topics: int, cout, data, variable, endl

Contents

1. Getting a C++ Compiler and Compiling Your First Program
2. Simple Datatypes and Declarations
3. Operators and Expressions
4. Input and Output (I/O)
5. Selection Statements
6. Iterative Statements
7. Arrays
8. Functions

1. Getting a C++ Compiler and Compiling Your First Program

Getting a C++ Compiler

For Windows users, especially beginners, I suggest getting an integrated development environment (IDE) for doing your work. You will get syntax highlighting, debugging, and compiling all in one package. For these tutorials, I suggest you use Bloodshed’s Dev-C++. It is a free IDE that has a compiler based on GCC. You can get it here:

http://www.bloodshed.net/devcpp.html

I’ve just tried the latest beta on windows and it works. If you want to run a different compiler or IDE that is fine, but it would be easier if you all stick to one type of environment for windows. I’ve also worked in Microsoft’s Visual Studios, so if you run it that’s ok. If your use Borland or any other compiler your own.

For Linux users, GCC should suffice and should already be on your computer. If you want an IDE I suggest Kdevelop. Linux users can get it here:

http://www.kdevelop.org/

Mac users should use Xcode. It is provided on your osx install cd.

Compiling Your First Program

Dev-C++ Users:

1. Open up the Dev-C++
2. On the top menu go to File->New->Project
3. Click on Console Application
4. Under the Name call it whatever you want
5. Save the Project wherever you want

At this point, it will create the project and a basic c++ file will show up in the main window. Before the line that says: “system(“Pause”)”, type the following:

cout << “Hello World\n”;

Now click on the floppy at the top to save the file. Then on the top menu go to execute->compile & run. If everything was successful a command prompt window should pop up and display the words “Hello World” without quotes.

GCC users:

Open up your favorite text editor and type the following:

#include<iostream>

using namespace std;

int main( int argc , char **argv ) {
cout << "Hello World\n";
return 0;
}

Save the file as program1.cpp and open the command prompt. Locate your program and type:

g++ program1.cpp

If that doesn’t work try CC program1.cpp or GCC program1.cpp. Depending on how your system is set up the compiler will be called differently. To run the program type:

./a.out

You should see “Hello World” displayed

For Kdevelop Users:

1. On the top menu go to Project->New Project->C++->Simple Hello World Program
2. Call the application whatever name you want and give an author-name
3. Hit Next 3 times then Finish
4. On the top menu go to Build->Execute Program
5. If a window comes up say yes.
6. When it is done compiling a window should pop up saying “Hello World!”

2. Simple Datatypes and Declarations

Datatypes

You’ve just decided to move across the country. Unfortunately(1), you arranged to use UHAUL to transfer your stuff to the new place. Being a non-waster, you pack the contents of your refrigerator, including the milk, cheese, leftover turkey from the last thanksgiving, and mayonnaise, and place it in the truck. A week later you arrive at your new home. As you open the back door of the truck to unload your prized possessions, you are greeted by a foul stench that overtakes your senses. You instantly collapse.

Variables in C++ are very much like the scenario above. You must pick the right storage facility to hold different types of data. If you had decided to go with a refrigerated truck from Ryder the food wouldn’t have gone bad.

Here is the list of the simple data storage types in C++, more commonly known as datatypes:

int – Integer – Usually 4 bytes – Examples: 3, 10, -123, 28
char – Character – 1 byte – Examples: ‘a’, ‘%’, ‘T’
float – Single-precision floating-point number – Usually 4 bytes – Examples: 2.3, 5.4, -2.3
double – Double-precision floating-point number – Usually, 8 bytes – Examples: Same as float but more decimal places can hold
bool – Boolean – 1 byte – Examples: 0, 1, true, false

You don’t want to put any floating-point number in an int because c++ will round to the nearest integer. You also don’t want to have a double-sized floating-point number in float because c++ will truncate it. The key is to use the right datatype for the right job.

Now your probably wondering what these byte things mean. Unlike our base 10 language (0,1,2,3,4,5,6,7,8,9), known as decimal, digital computers only understand base 2 (0,1) or binary. The amount of space taken up to hold a 0 or a 1 in a computer is a bit. 4 bits is a nibble and 8 bits is a byte. If you want to know how many bits or bytes an integer will need, here is a simple formula:

log(Number)/log(2) = number of bits (always round up)

Example:

Number = 15

log(15)/log(2) = 3.9
This means that in order to store the number 15 you need 4 bits

To get the number of bytes that is needed to divide the number of bits by 8.

Example

Number = 65536

log(65536)/log(2) = 16 bits = (16/8) bytes = 2 bytes

Why is this information important? When dealing with very large sets of data, it becomes crucial that you use the right data type for the job or you’ll be wasting precious memory and time.

Now that we got the basic data types out of the way, we can modify their behavior with these qualifiers:

short – Makes integer 2 bytes. ( short int )
long – Makes double 10 bytes. Does nothing to int (long double or long int)
signed – Allows negative numbers in char or int. Example: -128 to 127 (signed char or signed int)(Note: by default integers are signed)
unsigned – Doesn’t allow negative numbers in char or int. Example: 0 to 255 (unsigned char or unsigned int)
const – Constant – Doesn’t allow value to change.

As you can see from above, qualifiers can be used to tweak the type of information that can be stored in the different data types. It is also possible to string together multiple qualifiers together. For example, you can have long long int, or unsigned short int.

Variable Declarations

A variable, like in mathematics, is a name given to an object that stores information. For example: X=1, Y=2. The object names, in this case, are X and Y. The data stored in them are 1 and 2 respectively. In c++ you must ALWAYS declare what each variable is allowed to hold before you can use it.

Going back to the story from before, the variable name, in that case, was the company you rented from (UHAUL). The type of truck that they gave you (26′ Super Mover) is the datatype. If you were to also attach a trailer to the truck to expand the size, that would be the qualifier. In c++ the variable declaration is as follows:

trailer Super_Mover UHAUL;

In c++ terms the declaration is formatted in this fashion:

<qualifier(s)> <datatype> <variable name> ;

Notice the semicolon at the end. You must end a declaration with a semicolon. Also, qualifiers are the only component that isn’t required

Here are some example declarations:

unsigned int counter;
double money;
char letter;
const pi;

There are some rules for naming a variable:

1. the First character must be a letter or underscore
2. Must not be a keyword (See keyword list in footer)
2. Variables are case sensitive: ‘a’ is not equal to ‘A’
3. Upper or lower case letter, number, and underscores are allowed

When declaring multiple variables of the same type you can list the different variable names and separate them with a comma.

Example:

int counter1, counter2, counter3 ;

To initialize or set the value of a variable simply follow this format:

<variable name> = <value or expression>;

You can also do it this way:

<qualifier(s)> <datatype> <variable name> = <value or expression>;

And if you have multiple variables with the same datatype you can do it this way:

<qualifier(s)> <datatype> <variable name> = <value or expression>,<variable name> = <value or expression>, <variable name> = <value or expression>;

Here are some examples:

int a=1;
unsigned char b = ‘c’;
double c=2.4, d=4.2, e=2.7;

Assignment 1:

Create a new c++ project. Type the following:

#include<iostream>

using namespace std;

int main( int argc, char *argv[]) {
	char myCharacter = 'z';
	cout << "The datatype is " << sizeof(int) << " bytes!" << endl;
	cout << "The variable has a value of " << myCharacter << endl;
	return 0;
}

Compile and Run. See what the output is. Try changing the variable declaration to something else. If you change the variable name, change the second cout line to reflect that new variable name. Try different qualifiers and datatypes inside the sizeof().

Find the size in bytes of the long long int, the unsigned short int, and the unsigned long float.

(1) https://www.physicsforums.com/showthread.php?t=32599

Keywords:

asm, auto, break, case, catch, char, class, const, continue, default, deletc, do, double, else, enum, extern, float, for, friend, goto, if, inline, int, long, new, operator, private, protected, public, register, return, short, signed, sizeof, static, struct, switch, template, this, throw, try, typedef, union, unsigned, virtual, void, volatile, while

3. Operators and Expressions

Operators and Expressions

In mathematics, the solution to an expression depends on the order that the +, -, * and / operators are arranged. The same can be said for programming.

Here are a few places that have the precedence and associativity rules for c++:

http://www.bgsu.edu/departments/compsci/docs/prec.html [Broken]
http://www.programmershelp.co.uk/copprec.php
http://cs.stmarys.ca/~porter/csc/ref/cpp_operators.html

I will go through the more common ones that a beginner will use. Operators like ::, ->, etc will not be covered until the object-oriented programming tutorial. The bitwise operators will also not be discussed until the low-level programming tutorial.

As I’m sure you already know:

Addition +
Subtraction: –
Multiplication: *
Division: /
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to; <=

And maybe some that you might not already know:

Modulus: %
This is the remainder operator. For example 50 % 7 = 1. If you take 50 and divide it by 7 you get 49 remainder 1

Logical Not: !
Logically if I say: not true, that implies false. In c++ you do this by saying !true = false

prefixed incrementor: ++
If I have a variable X which is equal to 3 and I do ++X, that means I will increment X by one BEFORE doing any operations using the variable.

postfix incrementor: ++
If I have a variable X which is equal to 3 and I do X++, that means I will increment X by one AFTER doing any operations using the variable.

prefixed decrementer: —
If I have a variable X which is equal to 3 and I do –X, that means I will decrement X by one BEFORE doing any operations using the variable.

postfix decrementor: —
If I have a variable X which is equal to 3 and I do X–, that means I will decrement X by one AFTER doing any operations using the variable.

pointer: *
If this operator precedes a variable like this: *X, that means that X is a hex value that points to a memory location. This operator is used most often in more complicated datatypes such as linked lists. They are also used to access array values.

base address: &
If this operator precedes a variable like this: &X, that means that X starts at hex memory location &X. This operator is used most often when passing values by reference (You will see how this works in the function section of this tutorial)

type cast: (datatype)
This operator is used to change the datatype of an expression. For example:
int y;
float x = 3.14;
y = (int)x;

When the (int) is applied to the x, the 3.14 is truncated to 3. (Note: The value of X doesn’t not change. It remains 3.14)

new
This is used to reserve some memory

delete
This is used to destroy the memory you reserved

Size of Variable: sizeof
This operator returns the number bytes the variable occupies

Is equal to: ==
Used to see if two value match: Example: 2==2. (NOTE: It is a common mistake to just use one =. Do not do this unless you want to assign a value to a variable)

Logical And: &&
If something is true AND something else is true : If something is true && something else is true

Logical Or: ||
If something is true OR something else is true : if something is true || something else is true

?:
Format – expression?true result:false result;
If the expression is true the statement after the question mark and before the colon is executed, otherwise, the statement after the colon and before the semicolon are executed

Assignment: =
Assigns the value on the right to the object on the left

+=
Takes the object on the left adds it to the object on the right and assigns the result to the object on the left. Example: x += 2. The equivalent statement would be x = x + 2.

-=, *=, /=, %= are identical to +=, but the operation done is based on what operator comes first: Examples:
x-= 2 : x = x – 2, x*=2 : x = x * 2

,
used to separate multiple expressions. Example:
int x = 1, y = 2, z = 7;

Assignment 2:

Create a new C++ project. Type the following:

#include<iostream>

using namespace std;

int main( int argc, char *argv[] ) {

int x = 1, y = 3, z = 4;
int *num;
const float pi = 3.14;
z*=y;
y = x + (int)pi;
num = &y;

if( ++z <= y-- ) {
	cout << "Z: " << z << " <= Y: " << y << endl;
} else {
	cout << "Z: " << z << " > Y: " << y << endl;
}

cout << "Z: " << z << endl;
cout << "Y: " << y << endl;
cout << "The base memory address of Y: " << num << endl;
cout << "The value pointed to by num: " << *num << endl;

return 0;

}
Like the last assignment, compile and run the program. See what the output is. Then experiment by modifying the program. The best way to learn programming is to try different things.

4. Input and Output (I/O)

Output

In C++, the way to output to the screen is by using the cout statement. You’ve already seen this statement in the previous sections. I will now go into the details of how use the cout statement and how to modify its behavior.

The cout statement is composed of 3 parts

1. Insertion Operator: <<
2. Manipulator
3. Value

The insertion operator is similar to the < redirection operator in any command prompt language. It takes the value from the right side and inserts it to the left.

Manipulators change the way cout outputs stuff. In the iostream library there are 4 manipulators:

1. endl
2. dec
3. hex
4. oct

If you want more then you’ll need to include the iomanip library by using the following at the top of your program:

#include <iomanip>

The manipulators included in iomanip are as follows:

1. setw( <num> ) – Sets the output field width
2. left – left justify text
3. right – right justify txt
4. showpos – Shows leading + sign
5. noshowpos – Doesn’t show leading + (This is the default)
6. setfil( <character> ) – Sets the fill character (Use in conjunction with setw7. boolalpha – Display true or false with boolean datatypes
8. noboolalpha – Display 1 or 0 with boolean datatypes (This is the default)
9. scientific – Display floating point numbers in scientific notation
10. fixed – Display floating point numbers in decimal notation (This is the default)
11. setprecision( <num> ) – Set the number of digits displayed

NOTE: All manipulators are present except setw and endl. What this means is that when you output using a cout statement all previous modifiers apply except the setw and endl.

Examples (Quotes are used in the output to show white space in the output):

Statement: cout << “Hello World” << endl;
Output:

“Hello World

Statement: cout << “P” << “R” << “O” << “G” << “R” << “A” << “M” << endl;
Output:

“PROGRAM

Statement: cout << setw(10) << setfill(‘/’) << setprecesion(2) << 3.141;
Output:

“///////3.1”

Statment: cout << “Harry” << endl << “Potter”;
Output:

“Harry
Potter”

Input

What is a program if you can’t get user feedback? In order to accomplish this in c++ we use the cin statement

The cin statement is composed of 3 parts

1. Extraction Operator: >>
2. Manipulator
3. Value

The extraction operator is similar to the > redirection operator in any command prompt language. It extracts the value from the left side and inserts it to the right.

The cin statement also manipulates which are included in the iomanip library. There are as follows:

1. skipws – ignore spaces, tabs, newlines, and carriage returns when getting the users input
2. noskipws – Doesn’t ignore spaces, tabs, newlines, and carriage returns (This is the default)

Example:

int a, b, c;

cout << “Enter NUM1, NUM2 , and NUM3” << endl;
cin >> a >> b >> c;
cout << “NUM1: ” << a << endl;
cout << “NUM2: ” << b << endl;
cout << “NUM3: ” << c << endl;

———————————————-
Assignment 3:

1. Write a program that calculates and outputs the hypotenuse of a triangle using the Pythagorean theorem given the legs from user input. The output should have 3 decimal places.
2. Write a program that calculates and outputs the area of a triangle given the base and height by the user. The output should have 5 decimal places.
3. Write a program that calculates and outputs the distance between two points in space. The output should be in scientific notation.

NOTE: When raising a number to the power to, do not use the ^ operator. In c++ that is the bit-wise operator known as the exclusive or. Instead multiple the same number together.

5. Selection Statements

If Statement

Conditional statements are probably the easiest concept to grasp in programming.If something isn’t true do something else. This is how conditional statements work.

Case 1 – If :

if ( condition ) {
statements;
}

In this case, if the condition is true it executes the statements inside the curly braces. If the condition is false it doesn’t execute anything

Case 2 – If-Else:

if ( condition ) {
statements;
} else {
statements;
}

In this case, if the condition is true it executes the statements inside the first pair of curly braces, else it executes the statements inside the second pair of curly braces.

Case 3 Nested If-Else:

if( condition ) {
statements;
} else if(condition) {
statements;
} else {
statements;
}

case 3 can also be written this way:

if( condition ) {
statements;
} else {
if( condition ) {
statements;
} else {
statements;
}
}

Here is an example of a program that uses a nested if-else

#include <iostream>

using namespace std;

int main( int argc , char *argv[] ) {

int number ;

cout << "Enter a Integer: " ;
cin >> number ;

if( number % 2 == 0 ) {
	cout << number << " is even." << endl;
} else {
	cout << number << "is odd." << endl;
}

return 0;
}

Switch Statement

A switch statement is a useful way to handle menu-driven systems. Here is an example code of how a switch:

#include <iostream>

using namespace std;

int main( int argc , char *argv[] ) {

int number ;

cout << "1. Print Hello World" ;
cout << "2. Print Physics Forums" ;
cout << "3. Print C++" ;
cin >> number ;

switch( number ) {
case 1:
	cout << "Hello World" << endl;
	break;
case 2:
	cout << "Physics Forums" << endl;
	break;
case 3:
	cout << "C++" << endl;
	break;
default:
	cout << "Input Error" << endl;
	break;
}

return 0;
}

Note: Switch only works with integers or single characters

If the break is omitted from the end of a case statement, then subsequent case statements will be executed until a break is reached.

Conditional Operator

Although not used often, it is a shorthand method for writing an if statement

format:

<expression> ? <true_statment> : <false_statement> ;

If the expression is true, then the true_statment is used. If the expression is false, then the false_statement is used.

Example:

time = ( 1 < 2 ) ? 6 : 7 ;

Assignment 4:

Write a program that will check if the input meets the following criteria:

1. The first input is a number with at least three digits
2. The second input is a character between A and Q
3. The third input is divisible by 3

6. Iterative Statements

While Loop

while( condition ) {
statements;
}

While the condition is true the statements inside of the curly braces will be executed.

Example:

#include <iostream>

using namespace std;

int main( int argc, char **argv) {

int x = 0 ;

while( x < 2 ) {
      cout << "HELLO" << endl;
      x++;
}

return 0;
}

Output:

HELLO
HELLO

Do-While Loop

do{
statements;
} while (condition) ;

Do the statements inside of the curly braces while the condition is true.

Example:

#include <iostream>

using namespace std;

int main( int argc, char **argv) {

int x = 0 ;

do {
      cout << "HELLO" << endl;
      x++;
} while( x < 2 ) ;

return 0;
}

Output:

HELLO
HELLO
HELLO

For Loop

for( initial values ; condition ; counter ){
statements;
}

In a for loop, the initial values are set. The condition is then checked. If the condition is true it executes the statements inside of the curly braces. The variables are then incremented or decremented and the condition is checked again. While the condition is true it will continue to go through the loop

Example:

#include <iostream>

using namespace std;

int main( int argc, char **argv) {

for( int x = 0 ; x < 2 ; x++ ) {
     cout << "HELLO" << endl;
}
return 0;
}

Output:

HELLO
HELLO
——————————-
Assignment 5:

Create a menu-driven system within a loop that can do the following:
1. Calculate pascal’s triangle. Have the user enter the number of rows they want to see. (http://mathworld.wolfram.com/PascalsTriangle.html)
2. Calculate the Fibonacci sequence. Have the user enter the number of numbers they want to see. (http://mathworld.wolfram.com/FibonacciNumber.html)
3. Average as many numbers together as the user likes.

7. Arrays

An array is the mathematical equivalent of a matrix. A matrix is declared as follows:

<datatype> <variable name> [size] … [size] ;

Here is an example declaration of a 1 dimensional array:

int myarray[1] ;

A 2 dimensional array:

int myarray[3][3] ;

A 3 dimensional array:

int myarray[3][3][7] ;

The [size] is how many sections a certain dimension has. If size=3, then there are three sections to the particular dimension. To better visualize this concept take this example:

int myarray[3][4] ;

Visually myarray can be represented like this:

[][][]
[][][]
[][][]
[][][]

or like this:

[][][][]
[][][][]
[][][][]

When declaring an array you can set the value of each cell and this is how you would do it:

int myarray[3] = {1,2,5};
int myarray[3][2] = {{1,2},{3,5},{6,3}} ;

If you want to access the values in an array you use index values. Indexes start at 0 and go until size-1. Here is an example :

#include <iostream>
using namespace std;
int main( int argc, char **argv) {
int myarray[2][2] ;
cout << "Determinant Finder: " << endl ;
cout << "Enter Matrix in the following format: X11 X12 X21 X22" << endl ;
for( int i = 0 ; i < 2 ; i++ ) {
for( int j= 0 ; j < 2 ; i++ ) {
cin >> myarray[i][j] ;
}}

cout << myarray[0][0]*myarray[1][1]-myarray[1][0]*myarray[0][1] << endl ;

return 0;
}

INPUT: 1 2 3 4
OUTPUT: -2

Assignment 6:
Create a program capable of solving two simultaneous linear equations in the form:

Ax+By=C
Dx+Ey=F

8. Functions

Functions are very powerful. They allow programmers to encapsulate sections of code that get repeated often within a program. You’ve already known the basic structure of a function because you always use one: the main function.

A function has the following format:

<datatype> <function name> ( <parameter list> ){}

The datatype in front of the function name is the type of value that gets returned by the function. If you noticed there is always return 0; at the end of the main function which has an int datatype. This is used by the operating system to let it know that everything has gone fine.

The parameter list is a list of all the variables that you pass to the function. You can use the variables you pass inside the function. There are two types of passing variables.

1) Pass by Value: You copy the data in the variable and create a local variable within the function by the same name.
2) Pass by Reference: You copy the address of the variable and create a local variable by the same name that points to the address.

Here is an example of pass by value:

void myfunction(int x1, int x2) { }

Here is an example of pass by reference:

void myfunction(int &x1, int &x2){ }

Note 1: Pass by reference is the most efficient way to pass values to a function. The reason is that you only copy the address instead of everything stored by the variable.

Note 2: void is used when you don’t want to return any value or don’t want to tell the compiler what type you’re returning.

Here is an example of using a function:

#include <iostream>
using namespace std;

double square_area(double length, double width) {
return length*width ;
}

int main( int argc, char **argv) {
double L, W ;
while(1) {
cout << "Enter Length and Width of Square.(L=0 or W=0 to quit)" << endl;
cin >> L >> W ;
if( L==0 || W == 0) break ;
else cout << "Area: " << square_area(L,W) ;
} 

return 0;
}

Assignment 7:

By now you pretty much have all the basics of programming C++. Try and create a text adventure game using functions.

Discussion Thread

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply