RSS

Search Engine

Wednesday, May 26, 2010

Basic C++ Elements

This article aims to provide information about the most basic C++ operations. It is intended for beginners in the C++ programming language.

Overview

C++ is a general-purpose programming language that supports procedural programming, object-oriented programming and generic programming. It was developed by Dr. Bjarne Stroustrup in 1979 at Bell Labs as an enhancement to the C programming language. C++ programs range from small applications that calculate the sum of 2 numbers to complex programs used in supercomputers.

General information

Basically, C++ is very similar to Python and other programming languages. The environment consists of an editor (where you write the code) and a compiler (the code interpreter; simply, the part of the program that executes the instructions you've written). C++ is case sensitive, so "nokia" is not the same as "Nokia". C++ files are saved with a .cpp extension. Also, when you compile a program, an .exe file is created so you can use the program without having to open the editor and compile it every time.

Installation and usage

There are a few free, open-source versions of C++ on the Internet, and also comercial versions, which provide slightly better features. The C++ compiler used for this tutorial is Dev-C++. After you download it, install it as you would any normal program. When you first run it, you are asked for some configuration options. The best ones are already selected, so just click "Next". After it is all set up, to open a new page, go to File->New->Source File (adapt these instructions to the C++ program you are using). After you've written an program, press F9 to save and compile it.

Image:Dev-C++.JPG

Program syntax

In C++, programs usually have the structure of a procedure (you'll understand better after you read the rest of this article). Here is an essential general structure of a C++ application, with explanation below:


//this is an example

#include
#include
//etc.
using namespace std;
int main()
{
operation1;
operation2;
//etc.
}


OK, here is what the above are for:

  • "//this is an example" is a comment. Comments are words used to describe operations and thus make the code easier to understand. They are optional, but recommended.

  • "#include": # is a key character (this means it has to be there), "include" tells the compiler to include the module named "module1" (modules are, roughly said, collections of information and functions that C++ uses in order to perform operations)

  • "using namespace std;" this also has to be here, though it is not its only form

  • "int main()" "int" means that the function named "main" will return an integer result. We'll discuss this when we get to variables.

  • "{" marks the beginning of a group of operations, in this case the body of the program

  • "operation1" is an operation that the program has to perform

  • "}" marks the end of a group of operations, in this case the body of the program

A variable is a "container" that is used to store a value. For example:

a=7;

stores the value 7 in the variable named a.


Classification

In C++, you may use the following types of variables:

  • int - an integer number, roughly between -2100000000 and 2100000000

  • long - an "extended" version of int; rarely used

  • float - a number with decimals

  • double - an "extended" version of float; a little less stable

  • bool - a logical variable (can be TRUE or FALSE)

  • char - a character

  • string - a sequence (may also be called array) of characters

Assignment and examples

There are 2 ways to assign a value to a variable:


int x=22434;

long z=34;
float a=1.2;
double y=3.4;
bool q=true;
char c="p";
string s="ala";


or


int x;

x=4;
float z,q,l;
z=3;
q=-1.7;
//etc.


There are some things to notice here: you have to write ";" after any operation and you can assign seceral variables in the same declaration (like the "float z,q,l" above).

Operators

Like in mathematics, you can compare values. A comparison can be true or false:

2<5>=34 is false

Operators are useful for conditions (see later in this article). The operators used in C++ are: < (smaller), > (greater), <= (smaller or equal), == (equal), >= (greater or equal), != (different) Here is an example

a=4;

b=18;

x<=y x!=y x>=y
//return true
x>y
x==y
//return false


We can also consider the boolean operators here:

  • "and" - returns true if all values are true, false otherwise

  • "or" - returns true if at least one value is true, false otherwise

  • "not" - returns true if the value is false and vice-versa

Examples:

(2<5)>1) returns true

(3<1)>3456) returns false
not(4<5)>


Operations

Operations are used to modify variables. Here is a list of the most commonly used operations:

  • "+" - adds two values

  • "-" - subtracts the value of the second from that of the first

  • "*" - multiplies two values

  • "/" - divides a value to another and returns the result without the modulus (i.e. 5%2=2)

  • "%" - the modulus (the number you get after dividing a number to another number, i.e. 5%2=1)

Incrementing (increasing a value by 1) and decrementing (decreasing a value by 1) are also operations. This is how it is done:

int i=0;

for each operation below, the initial value of i is 0
i=i+1 is the same as i+=1 and means that i is given its current value +1.
i++ means i is used with its current value and then increased by 1
++i means i is increased by 1 and its new value is used
The same goes for "-" instead of "+", the difference being that 1, or whatever quantity you are adding, is subtracted.

Note that i=i*3, i*=2, i/=5 etc are also valid operations.

In order to check if a condition is met we use the "if" conditional:

if(condition) { operation1; operation2; ... }

else { operationa; operationb; ... }

This is what happens: if the "condition" is true "operation1", "operation2"... are executed. If the "condition" is false "operationa", "operationb"... are executed. In the following example,

#include

using namespace std;
int main()
{
int x=2;
if((x==1) or (x<45)) { x=7; x=x+1; }
else x--;
}

the final value of x should be 8.


If we need to execute a series of instructions a certain number of times, or until a condition is met, we use the "while" and "for" loops.

"While" reapeats the operations until the condition set by the programmer is met. Remember to modify a variable once the desired result is achieved in order to avoid infinite loops.

while(conditions) { op1; op2;... }

Here is an example:

int x,i;

x=5, i=1;
while(i<=x) { cout << "that's one loop"; i++; }

This should print the message "that's one loop" 5 times.


"For" does the instructions as many times as the range of the variable says. The variable is automatically incremented/decremented, so there is no risk of infinite loop.

int variable;

for(variable=startingValue; variable) { op1; op2;... }

Example:

int i;

for(i=1; i<=5; i++) cout << "that's one loop";


Arrays are sequences of values. The most common types of arrays are uni-dimensional (vertice) and bi-dimensional (matrix). Examples:

  • a vertice:


1,2,3,4


  • a matrix:


1 2 3

4 5 6
7 8 9


Arrays are characterised by the index(es) of their elements. The index is the number of the element in that sequence, counting from 0. For example, in 1,3,5,6, the index of the element "5" is 2. The elements of a matrix have to indexes, which are coordinates given by the line and column number. For example: in

0 -3 5  6

2 5 5 67

the indexes of the element "-3" are 1 (because it is on the first line) and 2 (because it is on the second column)


Here is how to declare and read arrays:

  • Vertice:


int vert[noOfElements];

int i;
for(i=1; i<=noOfElements; i++) cin >> vert[i];

Where noOfElements is the maximum number of elements the vertice will ever have in our program. "cin" reads the value from the user.


  • Matrix


int mat[noOfL][noOfC];

int i,j;
for(i=1; i<=noOfL; i++)
for(j=1; j<=noOfC; j++) cin >> mat[i][j];

Where "noOfL" is the number of lines and "noOfC" is the number of columns.


Note that arrays can be of many kinds depending on the values they store. They can have integer, decimal, character and string elements. A string is an array all on its own. Its elements are its characters. For example:

s="yeah";

s[0] will return "y", s[3] will return "h" etc.

Functions are used to return the result of a series of operations that you don't have to write. In other words, instead of writing a series of operations, you just call a function that has them written in it.

Let's see an example. Say we want to make the function "factorial", which, for a given integer number x, returns 1*2*3*...*x.

#include

using namespace std;
//functions are created before they are used, in this case before the main program
int factorial(int x) //between the brackets is the list of variables the function uses
{
int i, f;
f=1;
for(i=1; i<=x; i++) f=f*i;
return f;
}
int main()
{
int x=5;
cout << style="color: rgb(0, 0, 0);">(x); //simply call the function and have it calculate for the value x
system("pause"); //makes the computer wait for a keypress instead of closing
return 0; //the window in a second
}

This should display 120. Functions are very useful in the development of large applications because they make it so you don't have to write all that code each time, but instead just call them.

Here we are, ready to make our first C++ program. Let's make the classic "Hello, world!":

1.Open your C++ editor (in this case Dev-C++)

2.Open a new file (File->New->Source File)

3.Write the following code:

#include

using namespace std;
int main()
{
cout << "Hello, world!";
system("pause");
return 0;
}

4.Compile the program (F9)


5.If all goes well you should see the message.

Here's a program that calculates the sum of n given numbers:

#include

using namespace std;
int main()
{
int n, s=0, i;
cin >> n;
int v[n];
for(i=1; i<=n; i++) { cin >> v[i];
s=s+v[i];
}
cout << style="color: rgb(0, 0, 221);">system("pause");
}


And there you have it, a walkthrough of the basic C++ elements. C++ codes used for developing mobile phone applications are a bit different, but work on the same principles described here.

Recommended reading:

Source: http://wiki.forum.nokia.com/index.php/Basic_C%2B%2B_Elements

0 comments:

Post a Comment