C Plus Plus examples

From ArticleWorld


This article contains various C++ examples so that readers can have an image of how C++ code looks.

Loops

There are three common ways of looping in C code: the for statement, and the while... or do...while statements. Some implementations also include support for goto statements, but its usage is not encouraged.

The following example will print the numbers from 0 to 35, using an iterator variable called i.

for(i=0;i<=35;i++) {
cout << i << endl;
}

Nevertheless, more complex operations may be performed in such a loop. The following example prints the powers of 2, from 2 to 1024.

for(i=2;i<=1024;i*i) {
cout << i << endl;
}

While and do-while conditional loops are also supported:

<pre>char a;
while(!filestrm.eof()) {
filestrm >> a;
cout << a;
}

which can be changed into:

do {
filestrm >> a;
cout << a;
} while (!filestrm.eof())

which checks the condition after each step, and not before.

Conditionals

Simple if-else structures are supported, along with nested decision structures:

if(a != 2) {
	if(a==3) {cout << 3;}
	else {cout << 4}
}
else {
cout << 2;
}

However, many such nested structures can be avoided using switch statements:

switch(a) {
case 1: cout << 1; break;
case 2: cout << 2; break;
default: cout << "Much"; break;
}

This piece of code compares a (which has to be a numerical constant) to all other values (namely 1 and 2). The statements following the default: case are executed if no match is to be found.

Functions

There are two important things used to describe a function in C++: its return type and its arguments.

A function can be declared like this:

void Shout(void){
cout << "Aaaaaah!"
}

and simply called by its name:

Shout();

The following is a slightly more complex example:

int factorial (int n)
{
 int result=1;
 for (int i=1; i<=n; ++i)
    result=result*=i;
 return result;
}

this function is called by enclosing its argument between the parenthesis:

<pre>factorial(42);

There is also support for recursive functions.