Register to reply

[C++] Tutorial 1: The Basics

by dduardo
Tags: basics, tutorial
Share this thread:
dduardo
#1
Jun26-04, 08:23 AM
Emeritus
dduardo's Avatar
P: 1,919
I recently noticed a substantial request for c++ information. Therefore it is my pleasure to announce the opening of c++ classes. I'm going to create two seperate threads, one for the actually tutorial and one for discussion.

For this first tutorial topics will include:

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

Every other day or two I will add a new section to this tutorial. I will do this until I feel I have adquately gone through all the topics I have listed above. When this is complete I will start a new tutorial but focus on more advanced topics of c++.

If you have any c++ questions that I haven't gotten to in the tutorial, please feel free to PM me or open a new thread. Further, if you think i'm missing something or made an error in my tutorials please tell me.
Phys.Org News Partner Science news on Phys.org
An interesting glimpse into how future state-of-the-art electronics might work
Tissue regeneration using anti-inflammatory nanomolecules
C2D2 fighting corrosion
dduardo
#2
Jun26-04, 09:51 AM
Emeritus
dduardo's Avatar
P: 1,919
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 hightlighting, 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 lastest 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 thats ok. If your use borland or any other compiler your own 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 whereever 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 successfull a command prompt window should popup and display the words "Hello World" without quotes.

----------------

GCC users:

Open up your favoriate 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 setup 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!"
dduardo
#3
Jun28-04, 09:29 AM
Emeritus
dduardo's Avatar
P: 1,919
Datatypes

You've just decided to move across 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, left over turkey from 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 the 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 held
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 probable 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 need 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 datatype for the job or you'll be wasting precious memory and time.

Now that we got the basic datatypes 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 tweak the type of information that can be stored in the different datatypes. 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 where to also attach a trailer to the truck to expand the size, that would be the qualifer. 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. First character must be a letter or underscore
2. Must not be a key word (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 unsigned long float.

---------------------------------------------

(1) http://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

dduardo
#4
Jun30-04, 12:16 PM
Emeritus
dduardo's Avatar
P: 1,919
[C++] Tutorial 1: The Basics

Operators and Expressions

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

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

http://www.bgsu.edu/departments/compsci/docs/prec.html
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 wil use. Operators like ::, ->, etc will not be covered until the object oriented programming tutorial. The bitwise operators will also not be dicussed 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 decrementor: --
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 operat
ions 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 preceds 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 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 are 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 assign 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 seperate 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
dduardo
#5
Jul2-04, 10:34 AM
Emeritus
dduardo's Avatar
P: 1,919
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 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 presisent except setw and endl. What this means is that when you output using a cout statement all previous modifers apply except the setw and endl.

Examples (Quotes are used in the output to show whitespace 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 manipulators 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 inore 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 pythogorean 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 triagle given the base and height by the user. The output should have 5 decimal places.
3. Write a program that calculates and ouputs 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 bitwise operator known as the exclusive or. Instead multiple the same number together.
dduardo
#6
Jul5-04, 11:45 AM
Emeritus
dduardo's Avatar
P: 1,919
If Statement

Conditional statements are probable the easiest concept to grasp in programming.If something isn't true do something else. This is how conditional statements works.

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 firest pair of curly braces, else it executes the statementes inside the second pair of curly braces.

Case 3 Nested If-Else:

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

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 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 ommited from the end of a case statement, then subsequent case statments 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 number with atleast three digits
2. The second input is a character between A and Q
3. The thrid input is divisible by 3
dduardo
#7
Jul20-04, 05:25 PM
Emeritus
dduardo's Avatar
P: 1,919
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 intial 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 check 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 number they want to see. (http://mathworld.wolfram.com/FibonacciNumber.html)
3. Average as many number together as the user likes.
dduardo
#8
Nov20-05, 07:59 PM
Emeritus
dduardo's Avatar
P: 1,919
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

If you need a refresher in matrices follow this link:

http://www.maths.surrey.ac.uk/intera...s/option1.html
dduardo
#9
Nov20-05, 08:26 PM
Emeritus
dduardo's Avatar
P: 1,919
Functions are very powerful. They allow programmers to encapsulate sections of code that get repeated often within a program. You've already know 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 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){ }

Note1: 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.

Note2: void is used when you don't want to return any value or don't want to tell the compiler what type your 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.


Register to reply

Related Discussions
SQL basics Programming & Computer Science 4
Op-Amp Basics Electrical Engineering 4
QFT basics? Quantum Physics 7
What is the difference between bearing and heading? General Physics 4
Basics General Discussion 6