Monday, September 29, 2008

Functions with no types. The use of void.

If you remember the syntax of a function declaration:
type name
( argument1, argument2 ...) statement

you will see that it is obligatory that this declaration begins with a
type, that is the type of the data that will be returned by the function with the return instruction. But what if we want to return no value?
Imagine that we want to make a function just to show a message on the screen. We do not need it to return any value, moreover, we do not need it to receive any parameters. For these cases, the
void type was devised in the C language. Take a look at:

#include <iostream.h>
void dummyfunction (void)
{
cout << "I'm a function!";
}
void main ()

{
dummyfunction ();
getch();
}

The following is the result:
I'm a function!
Although in C++ it is not necessary to specify
void, its use is considered suitable to signify that it is a function without parameters or arguments and not something else.

What you must always be aware of is that the format for calling a function includes specifing its name and enclosing the arguments between parenthesis. The non-existence of arguments does not exempt us from the obligation to use parenthesis. For that reason the call to dummyfunction is
dummyfunction ();

This clearly indicates that it is a call to a function and not the name of a variable or anything else.

Source : Cplusplus.com

Function

A function is a block of instructions that is executed when it is called from some other point of the program. The following is its format:

type name ( argument1, argument2, ...) statement

where:
· type is the type of data returned by the function.
· name is the name by which it will be possible to call the function.
· arguments (as many as wanted can be specified). Each argument consists of a type of data followed by its identifier, like in a variable declaration (for example, int x) and which acts within the function like any other variable. They allow passing parameters to the function when it is called. The different parameters are separated by commas.
· statement is the function's body. It can be a single instruction or a block of instructions. In the latter case it must be delimited by curly brackets {}.

Here you have the first function example:

#include <iostream.h>
 
int addition (int a, int b)
{
  int r;
  r=a+b;
  return (r);
}
 
void main ()
{
  int z;
  z = addition (5,3);
  cout << "The result is " << z;
  getch();

}

Output of the above program is shown in below:

The result is 8


In order to examine this code, first of all remember something said at the beginning of this tutorial: a C++ program always begins its execution with the main function. So we will begin there.

We can see how the main function begins by declaring the variable z of type int. Right after that we see a call to addition function. If we pay attention we will be able to see the similarity between the structure of the call to the function and the declaration of the function itself in the code lines above:

The parameters have a clear correspondence. Within the main function we called to addition passing two values: 5 and 3 that correspond to the int a and int b parameters declared for the function addition.

At the moment at which the function is called from main, control is lost by main and passed to function addition. The value of both parameters passed in the call (5 and 3) are copied to the local variables int a and int b within the function.

Function addition declares a new variable (int r;), and by means of the expression r=a+b;, it assigns to r the result of a plus b. Because the passed parameters for a and b are 5 and 3 respectively, the result is 8.

The following line of code:


return (r);

finalizes function addition, and returns the control back to the function that called it (main) following the program from the same point at which it was interrupted by the call to addition. But additionally, return was called with the content of variable r (return (r);), which at that moment was 8, so this value is said to be returned by the function.

The value returned by a function is the value given to the function when it is evaluated. Therefore, z will store the value returned by addition (5, 3), that is 8. To explain it another way, you can imagine that the call to a function (addition (5,3)) is literally replaced by the value it returns (8).

The following line of code in main is:

cout << "The result is " << z;

that, as you may already suppose, produces the printing of the result on the screen.


Source : Cplusplus.com


The For Loop


The for loop.

Its format is: for (initialization; condition; increase) statement; and its main function is to repeat statement while condition remains true, like the while loop. But in addition, for provides places to specify an initialization instruction and an increase instruction. So this loop is specially designed to perform a repetitive action with a counter.

The initialization and increase fields are optional. They can be avoided but not the semicolon signs among them. For example we could write: for (;n<10;) if we want to specify no initialization and no increase; or for (;n<10;n++) if we want to include an increase field but not an initialization.

Optionally, using the comma operator (,) we can specify more than one instruction in any of the fields included in a for loop, like in initialization, for example. The comma operator (,) is an instruction separator, it serves to separate more than one instruction where only one instruction is generally expected. For example, suppose that we wanted to intialize more than one variable in our loop:

for ( n=0, i=100 ; n!=i ; n++, i-- )

{

// whatever here...

}

This loop will execute 50 times if neither n nor i are modified within the loop:

n starts with 0 and i with 100, the condition is (n!=i) (that n be not equal to i). Beacuse n is increased by one and i decreased by one, the loop's condition will become false after the 50th loop, when both n and i will be equal to 50.

Source: cplusplus.com


The do-while loop

Format: do statement while (condition); Its functionality is exactly the same as the while loop except that condition in the do-while is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following program echoes any number you enter until you enter 0.

#include <iostream.h>
void main ()
{
  long n;
  do {
    cout << "Enter number (0 to end): ";
    cin >> n;
    cout << "You entered: " << n << "\n";
  } while (n != 0);
 getch();
}
 

The do-while loop is usually used when the condition that has to determine its end is determined within the loop statement, like in the previous case, where the user input within the block of intructions is what determines the end of the loop. If you never enter the 0 value in the previous example the loop will never end.



Source : Cplusplus.com

Repetitive structures or loops

Loops have as objective to repeat a statement a certain number of times or while a condition is fulfilled.

The while loop.

Its format is: while (expression) statement and its function is simply to repeat statement while expression is true.

For example, we are going to make a program to count down using a while loop:

void main ()
{
  int n;
  cout << "Enter the starting number > ";
  cin >> n;
  while (n>0) {
    cout << n << ", ";
    --n;
  }
  cout << "FIRE!";
  getch();
}

When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n be greater than 0), the block of instructions that follows will execute an indefinite number of times while the condition (n>0) remains true.

All the process in the program above can be interpreted according to the following script: beginning in main:

1. User assigns a value to n.

2. The while instruction checks if (n>0). At this point there are two possibilities:

true: execute statement (step 3,)

false: jump statement. The program follows in step 5.

3. Execute statement:
cout << n << ", ";
--n;
(prints out
n on screen and decreases n by 1).

4. End of block. Return Automatically to step 2.

5. Continue the program after the block: print out FIRE! and end of program.

Source : Cplusplus.com

Switch

The selective Structure: switch.

The syntax of the switch instruction is a bit peculiar. Its objective is to check several possible constant values for an expression, something similar to what we did at the beginning of this section with the linking of several if and else if sentences.  Its form is the following:
 switch (expression) {
  case constant1:
    block of instructions 1
    break;

case constant2:
    block of instructions 2

break;

 default:

 default block of instructions

  }



 
It works in the following way: switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes block of instructions 1 until it finds the break keyword, then the program will jump to the end of the switch selective structure.



If expression was not equal to constant1 it will check if expression is equivalent to constant2. If it is, it will execute block of instructions 2 until it
finds the break keyword.



Finally, if the value of expression has not matched any of the previously specified constants (you may specify as many case sentences as values you want to check), the program will execute the instructions included in the default: section, if this one exists, since it is optional.
 

Both of the following code fragments are equivalent:

switch example

switch (x) {
  case 1:
    cout << "x is 1";
    break;
  case 2:
    cout << "x is 2";
    break;
  default:
    cout << "value of x unknown";
  }

if-else equivalent

if (x == 1)
{

cout << "x is 1";

}
else if (x == 2)
{

cout << "x is 2";

}

else
{

cout << "value of x unknown";

}

Source: cplusplus.com

Control Structure

A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done to perform our program.

With the introduction of control sequences we are going to have to introduce a new concept: the block of instructions. A block of instructions is a group of instructions separated by semicolons (;) but grouped in a block delimited by curly bracket signs: { and }.

Most of the control structures that we will see in this section allow a generic statement as a parameter, this refers to either a single instruction or a block of instructions, as we want. If we want the statement to be a single instruction we do not need to enclose it between curly-brackets ({}). If we want the statement to be more than a single instruction we must enclose them between curly brackets ({}) forming a block of instructions.

Conditional structure: if and else

It is used to execute an instruction or block of instructions only if a condition is fulfilled. Its form is:

if (condition) statement

where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues on the next instruction after the conditional structure.

For example, the following code fragment prints out x is 100 only if the value stored in variable x is indeed 100:

if (x == 100)
cout << "x is 100";

If we want more than a single instruction to be executed in case that condition is true we can specify a block of instructions using curly brackets { }:

if (x == 100)
{
cout << "x is ";
cout << x;
}

We can additionally specify what we want that happens if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is:

if (condition) statement1 else statement2

For example:

if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";

prints out on the screen x is 100 if indeed x is worth 100, but if it is not -and only if not- it prints out x is not 100.

The if + else structures can be concatenated with the intention of verifying a range of values. The following example shows its use telling if the present value stored in x is positive, negative or none of the previous, that is to say, equal to zero.

if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";

Remember that in case we want more than a single instruction to be executed, we must group them in a block of instructions by using curly brackets { }.



Source : Cplusplus.com