Monday, August 31, 2009

Searching data

Searching is the other problem that often occurs when handling data. The search can be done with some part of the actual data called a key. The easiest way to search is the linear search: successive elements are examined until either the item is found or the end of the list is reached. This is however an extremely inefficient way to search because in average about n/2 elements must be searched and in the worst case the element is not found but all n elements have been searched any way. A more efficient way to search is to first sort the elements. Searching is then faster because it is known that the item is missing when the correct place in the array is passed.

A rather simple but efficient searching algorithm is called binary search. The elements must be in ascending or descending order.

Algorithm: Binary search
    left <--- 0
    right <--- element_amount - 1
    WHILE left <= right
        middle <--- ( left + right )/2
        IF elements[ middle ].key == searched_key THEN
           item found at location middle
        ELSE IF elements[ middle ].key < searched_key THEN
           left <--- middle + 1
        ELSE
           right <--- middle - 1
    item not in the array

How does the binary search work with an integer key:
The search key is 4, there are 10 elements with the key 0-10 in the array

binary search technique

Fig: Binary search mechanism


Note that Binary Search can be used to work with other types than string by changing some points in the code to match the type. string must be changed to match the type of the searched data. The comparisons in the algorithms need to compare the wanted type.

Reference: allexperts, onesmartclick, informit

Previous post

Next post


Sorting in C++

in C++ the library algorithm provides many easy to use algorithms. The sorting algorithm available is called sort. The contents of an array are sorted with

sort( array_name, array_name+array_size );

Sorting an integer array with sort:

#include <iostream>
#include <algorithm>

using namespace std;

void printArray( int array[], int size );

int main( void )
{
    const int SIZE = 8;
    int array[ SIZE ] = { 4, 6, 5, 7, 8, 1, 2, 3 };

    printArray( array, SIZE );
    sort( array, array+SIZE );
    printArray( array, SIZE );
}

void printArray( int array[], int size )
{
    int i = 0;

    while( i < size )
    {
        cout << array[ i ] << " ";
        ++i;
    }
    cout << endl;
}

The algorithm requires that the smaller than relation, <, has been defined for the elements of the array. To sort an array of structure, the < operator needs to be defined manually to the sorting function:

struct Student
{
    string name;
    int st_number;
};

bool compare( const Student& s1, const Student& s2 );
const int SIZE = 20;

int main()
{
    Student array[SIZE];
    // ...
    sort( array, array+SIZE, compare );
    // ...
}

bool compare( const Student& s1, const Student& s2 )
{
    if( s1.st_number < s2.st_number )
    {
    return true;
    }
    return false;
}

Reference: wikipedia, mathbits, daniweb

Previous post

Next post


Sorting

Arranging the elements of any array (or some key fields in them) into an ascending or descending order is called sorting. Since sorting is a field of coputer science that has been studied a lot, there are dozens of sorting algorithms available. Different algorithms and their efficiency is usually covered on the course Utilization of Data Structures. Pseudocode for these algorithms can be found in the literature. Cormen, Leiserson, Rivest, Stein: Introduction to Algorithms for instance. An efficient function for sorting data can often be found in one of the libraries.

Reference: wikipedia, sorting-algorithm, smith


Previous post

Next post



Sunday, August 30, 2009

Modifiers: unsigned, short and long

Integers (and in some cases characters) can be adjusted with the modifiers: unsigned, short and long. These can be used to either restrict or widen the used data type:

 unsigned int An integer value represented with as many bits as int.
range: 0 and all positives
 short int An integer value represented with at most as many bits as int.
range: negatives and positives
 long int An integer value represented with at least as many bits as int.
range: negatives and positives
 unsigned short int like short int
range: 0 and positives
 unsigned long int like long int
range: 0 and positives



it depends on the processor used with how many bits are used to represent each type.

Reference: bilmuh, msdn, faqts


Previous post

Next post


Structures

Arrays can be used to handle several elements of the same type together. However, sometimes it would be useful to handle several data elements of different types as a unit. In C++ structures are used for this purposes.

Structures (like arrays) are called structured data types, i.e. they have a structure defined by the programmer. A structure is declared:

struct type_name
{
    data_type member_name1;
    ...
    data_type member_nameN;
};

This defines a new type called type_name which can be used as any other type in C++. Note the semicolon (;) at the end. It is a mandatory while declaring a structure.

The individual members in the structure act like any other variable with the type data_type. The members can be accessed using . (dot) operator:

struct Student
{
    string name;
    int student_number;
};
...
Student st; // Declare a new variable of type Student
...
st.name = "Harry Potter";
cin >> st.student_number;

The members of a structure can also be initialized with literals of the same type as the members:

Student harry=
{
    "Harry Potter", 12345
};

The members are initialized in the order they appeared at the declaration. A new value can be assigned to a structure with =, but comparison ( == and != ) is not possible.

The members can be of any type, including arrays:

struct Grade
{
    string name,
    int problem_points[4];
};
...
Grade grade1;
...
grade1.problem_points[2] = 5;

On the other hand, the elements of any array can be of any type, too, including structures:

Student students[200];
...
students[0].name = "Ron Weasley";
cin >> students[54].student_number;

A struct is an aggregate of elements of (nearly) arbitrary types. Structures allow the programmer to define a new data type and group related components together. When structure is passed as a parameter of a function, by default it is passed by value but it can be passed by reference as well.

Reference: fredosaurus, wikipedia, msdn


Previous post

Next post




Saturday, August 29, 2009

Arrays as parameters

Even though call-by-value is the default parameter-passing mechanism in C++, arrays as parameters have some special features. Placing a pair of brackets ( [] ) after the name of a parameter indicates that the parameter is an array:

double arraySum( double array[ ], int array_size )
{
    double sum = 0.0;

    int i = 0;
    while( i < array_size )
    {
        sum = array[ i ] + sum;
    }
    return sum;
}

It is not necessary to specify the capacity of the array. There is no restriction on the capacity of the array passed to the function. It is necessary to use another parameter or a constant to pass the size of the array to the function.

Arrays are automatically passed by reference, i.e. specifying a parameter as an array makes it a reference parameter without the ampersand ( & ). If the function modifies the array, the corresponding argument will also be modified. This can be avoided by declaring the array as a constant reference parameter.

Let's take a larger example:

#include <cstdlib>
#include <iostream>

using namespace std;

const int MAX_NUMBER = 1000;
const int ERROR = -1;
const double END_NUMBER = -1.0;

int readNumbers( double numbers[ ] );
double calculateMean( const double numbers[ ], int how_many );

int main( void )
{
    double numbers[ MAX_NUMBERS ];
    int how_many_read = 0;

    how_many_read = readNumbers( numbers );

    if( how_many_read == ERROR )
    {
        return EXIT_FAILURE;
    }

    cout << "Mean value is: "
         << calculateMean( numbers, how_many_read )
         << endl;

    return EXIT_SUCCESS;
}

int readNumbers( double numbers[ ] )
{
    int how_many = 0;

    //we know that there is room for MAX_NUMBERS
    //amount of space in teh array
    while( how_many < MAX_NUMBERS )
    {
        cout << "Give "
             << how_many + 1
             << ". number: ";

        //The number is read from the input into
        //the array the change modifies the
        //coresponding argument
        cin >> numbers[ how_many ];

        if( numbers[ how_many ] == END_NUMBER )
        {
            return how_many;
        }
        ++how_many;
    }
    //if how_many got too large, and error has occured
    return ERROR;
}

double calculateMean( const double numbers[ ], int how_many )
{
    double sum = 0.0;
    int i = 0;

    if( how_many == 0 )
    {
        return sum;
    }

    //in this function the actual size of
    //the array doesn't matter. It is important
    //to know fo how many numbers the mean is
    //supposed to be calculated from
    while( i < how_many )
    {
        sum = sum + numbers[ i ];
        ++i;
    }
    return sum / how_many;
}


The other alternative woule have been:

int readNumbers( const double numbers[ ], int size )
{
    int how_many = 0;
    //now the size of the array is given as parameter
    while( how_many < size )
    {
        cout << "Give "
             << how_many + 1
             << ". number: ";
        //The number is read from the input
        //into the array the change modifies
        //the corresponding argument
        cin >> numbers[ how_many ];

        if( numbers[ how_many ] == END_NUMBER )
        {
            return how_many;
        }
        ++how_many;
    }
    //if how_many got too large, an error has occured
    return ERROR;
}

It would have been called in main:

how_many_read = readNumbers( numbers, MAX_NUMBERS );

The latter is recommended since the result can be used more widely.


Reference: cplusplus, macs, msdn


Previous post

Next post




Functions: Parameter-passing mechanisms

The simplest parameter-passing mechanism in C++ occurs by default. It is called call-by-value. Value passed using this method are called value parameters. Any modification of a value parameter within the function body has no effect on the value of its corresponding argument:

void divideByTwo( int parameter )
{
    parameter = parameter / 2;
}

int main( void )
{
    int figure = 42;

    divideByTwo( figure );
    cout << figure << endl;

    return EXIT_SUCCESS;
}

prints 42 as a result.

It would be often useful to be able to change the value of the corresponding argument. For example, if the function needs to return more than one value, data could be returned by changing the value of the parameters. There is also call-by-reference mechanism in C++. These parameters are called reference parameters. Reference parameters are aliases of their corresponding arguments, i.e. any change to the value of a reference parameter within the function body changes the value of its corresponding argument. When using call-by-reference, the values are passed by adding an ampersand (&) between the type and the name of the parameter.

The example mentioned before:

void divideByTwo( int& parameter )
{
    parameter = parameter / 2;
}

int main( void )
{
    int figure = 42;

    divideByTwo( figure );
    cout << figure << endl;

    return EXIT_SUCCESS;
}

prints now 21, i.e. function divideByTwo was able to change the actual value of the parameter.


Reference: msdn, comp, brpreiss


Previous post

Next post




Friday, August 28, 2009

Functions to deal with character

A lot of useful functions for dealing with characters can be found in the library cctype:

 Funstion  Funcionality 
 isalpha(c);  Returns true if c is a letter (a-z, A-Z) 
 isupper(c);  Returns true if c is an upper-case letter 
 islower(c);  Returns true if c is a lower-case letter 
 isdigit(c);  Returns trud if c is a number(0-9) 
 isspace(c);  Returns true if c is a white space character 
 ispunct(c);  Returns true if c is a punctuation mark 
 toupper(c);  If c is a lower-case letter a upper-case letter is returned, otherwise c is returned 
 tolower(c);  If c is a upper-case letter a lower-case letter is returned, otherwise c is returned 


These can be used by adding #include <cctype> to the includes.

However, the return type and the type of the parameter of these functions is int. This can cause problems in some systems. A safe way to use the functions is always explicitly cast the parameter to int with static_cast<int>( c ); The same can be done to the return type of the toupper and tolower to make sure the character value is correct.


Previous post

Next post




Thursday, August 27, 2009

Character string type string

Since words consist of sequences or strings of characters, there is naturally also the problem of storing and processing strings in C++. One of the solutions to the problem in C++ is the string type. string is part of the C++ standard library. When it is used #include <string> must be added at the beginning of the code file. After that string behaves in the same way as a basic data type:
  • Defining variables
  • Parameters and return types of functions
  • Assignment and initialization from another string variable or literal with =
  • Printing with cout and reading input with cin
  • Comparison with ==, !=, <=, >=, <>
In addition, string has other useful properties. Let's take a closer look at the string type.

A string variable is defined:

string variable_name = "init_value";

Any text inside the quotes can be assigned to a string variable. string is a special type that does not necessarily need the "init_value" but it is usually initialized for consistency.

Reading a string:

int main( void )
{
string name = "";
cout << "What's your name?" << endl;
cin >> name;
cout << "Hello" << name << endl;
}

The output of the program:

What's your name?
Harry Potter
Hello Harry

So cin stops reading the input when it encounters the first white space character. The entire line can be read by using the function getline():

int main( void )
{
string name = "";
cout << "What's your name?" << endl;
getline( cin, name );
cout << "Hello" << name << endl;
}

Now the output will be:

What's your name?
Harry Potter
Hello Harry Potter

getline always reads the entire line (including white spaces). It has two arguments, first the input stream (cin) and second which string you wish to write to.

A string variable can contain as many characters as needed. string has a lot of functions of its own that can be used to get information about the string. The size of the string can be obtained with the length() function. The function returns the amount of characters in the string.

cout << name.length();

would print 12 after the getline. The individual characters in a string can be accessed either with the at() function or with [].

name.at( 1 ) = name[ 10 ];

There are several functions for finding substrings:

name.find( "ot" );
name.find( "ot", 3 );

find() functions return the position of the substring "ot" in the string name. If the substring is not found, the function returns a special value string::npos

A part of a stirng can be accessed with the substr() function. On the other hand replace() function lets you to write to a substring.

name.substr( 0, 5 ); //equal Harry
name.replace( 0, 5, "Ron" ); //equals Ron Potter

A part of a string can be removed with erase()

name.erase( 0, 4); // leaves just potter

append() adds a substring to the end of the string:

name.append( " the wizard" );

The length of the string changes if needed. The size can also be changed explicitly with the resize() function:

name.resize( 6 ); //leaves again just potter


Reference: cplusplus, anaturb, cppreference


Previous post

Next post




Wednesday, August 26, 2009

Array

A variable of the type int or double can contain one value at a time. It would often be useful of the able to handle an aggregate of elements of the same type. An array is a structured datatype that:
  • has a specified size
  • consists of data elements of the same type
  • the elements are identified by their position in the array
In C++ array variables are declared:

type array_name[ capacity ];

The result is an array type variable named array_name in which data elements of the type type can be stored. The number of elements the array can contain is determined by capacity. type can be any defined type (predefined or programmer-defined). capacity needs to be a constant or a literal. For example, an integer array with nine elements:

int numbers[ 9 ];

An array can be seen as a row of numbered boxes, whose contents can be checked and changed. Every box fits one data element of the type type. In C++ arrays are indexed from zero through size-1.

int numbers[ 9 ] looks like this:

numbers:









 0  1  2  3  4  5  6  7  8 


the index of the last element is one smaller than the size of the array.

An element at index i can be accessed using [ ]:

numbers[8] = 2*numbers[0];

would give the last element the value of the first element times two. Any expression of the type integer can be used as an operand for the brackets.

For example,

const int SIZE = 10;

int maxValue( )
{
    int array[ SIZE ];
    int i = 0;
    int max = 0;
    while( i <>
    {
        cin >> array[ i ];
        if( array[ i ] > max )
        {
            max = array[ i ];
        }
        ++i;
    }
    return max;
}

No checking is done ot ensure that the indices stay within the range determined by the declaration of the array:

int index = 1000;
numbers[ index ] = 10; // logical error!

A compiler compiles the code above just fine. It is still incorrect because it refers to a non-existent element.

Like all variables, an array needs to be initialized with some sensible values before it can be used. An array can be initialized at declaration:


int numbers[ 9 ] = {1, 2, 3, 4, 5, 6, 7};

results in an array:

numbers:
 1  2  3  4  5  6  7  0  0 
 0 1 2 3 4 5 6 7 8


If there are less elements at initialization than the size of the array can contain, the rest of the elements are initialized to zero.

It is not necessary to tell the size of the array when initialized. It is automatically determined from the number of elements.

int numbers[ ] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

This is true only at initialization and cannot be used as a general method of handling array data. An array cannot be assigned another with =. Moreover, arrays cannot be compared with != and == operators. In array everything must be done one element at a time.

Arrays are static data structures. Their capacity cannot change during program execution. The capacity must always be fixed when the program is compiled:

int capacity = 0;
cin >> capacity;
int array[ capacity ]; // Error

results in a compilation error.


Reference: cplusplus, codesource, fredosaurus


Previous post

Next post




Tuesday, August 25, 2009

Comparing real numbers with = = and ! =

All computers use a limited amount of bits (0 and 1) to represent real numbers (and integers). This causes that in many cases there is a round off error in the results of calculations. the exact value might need more significant numbers than can be represented. In many cases it may not be possible because of the way real numbers are represented in the base of two. There are always round off errors and the result is only an approximate value. Fro example, the result of an expression 20.1 - 20.0 - 0.1 is not necessarily exactly 0.0 but instead because of round off errors 0.0(...lots of zeros...)1415926

Relational operators == and != can sometimes work illogically. The program:

#include <iostream>

using namespace std;

int main( void )
{
    double value1 = 20.1;
    double value2 = 20.0;
    double value3 = 0.1;

    if( ( value1 - value2 - value3 ) == 0 )
    {
        cout << "Corrrect!"
    }
    else
    {
        cout << "Sorry, there was an error!"
    }
}

prints "sorry, there was an error!" when executed.

In order to be able to live with this unfortunate feature instead of testing real numbers for equality we test for near equality. Two real numbers are equal if they are close enough to each other. Instead of writing a == b with real numbers we should write |a-b| < EPSILON where EPSILON is the maximum allowable difference, 1E-8 for instance. In C++ the comparison of reals a == b can be handled as follows:

//Define somewhere at the beginning of the
//program the maximum tolerance
const double EPSILON = 1E-8;
...
...
//When later in the program two reals are
//tested for equality:
abs( a-b )


Previous post

Next post




Monday, August 24, 2009

C++ libraries

C++ includes several different libraries. They provide a variety of different functions. So the programmer does not need to reinvent the wheel. The functions in a library are made available with the include directive:

#include <library_name>

For example,

iostream for I/O operations or
iomanip for manipulating the output

Let's take a closer look at a new one called cmath.
cmath contains predefined math related functions. The functions (listed in the table) can be used in a program by adding #include <cmath> at the beginning of the source code.

functiondescription
abs( x )Absolute value of real value x
pow( x,y )x raised to power y
sqrt( x )Square root of x
ceil( x )Least integer greater than or equal to x
floor( x )Greatest integer less than or equal to x
exp( x )Exponential function e^x
log( x )Natural logarithm of x
log10( x )Base 10 logarithm of x
sin( x )Sine of x (in radians)
cos( x )Cosine of x (in radians)
tan( x )Tangent of x (in radians)
asin( x )inverse sine of x
acos( x )Inverse cosine of x
atan( x )Inverse tangent of x
sinh( x )Hyperbolic sine of x
cosh( x )Hyperbolic cosine of x
tanh( x )Hyperbolic tangent of x



Reference: C++ reference, cpp reference, wikipedia


Previous post

Next post




Why the function is a programmer's best friend?

Function is a programmer's best friend because at least all these can be achieved with the help of functions:
  • Well-chosen function names make the program more understandable and say something about the functionality
  • Functions save time and effort. Often used actions need to be programmed only once
  • Errors need to be fixed in one place only
  • Changing the functionality of the program is easier when the change needs to be done in only one place
  • Functions are an important tool in structuring the program. The program can have a better manageable structure (divide and conquer) with the help of functions



Reference: blog, ddj, scribd


Previous post

Next post




Sunday, August 23, 2009

Where do little functions come from?

It is rather easy to find potential functions from a carefully planned algorithm:
  • Any part of the algorithm that needs clarification is usually sensible to be implemented as a function
  • Any part of the algorithm that is repeated several times as such in the algorithm
With the help of these simple rules a programmer already gets far. Experience and practice give more perspective. It is good to remember what has been said about the length of functions: preferably no longer than what fits on the screen.

Functions with a return type are found the same way by reading the algorithm carefully. Additionally one must think what kind of information each function needs to give back to its caller (if any).

Often a function can be recognized as an action that is a part of a statement:

    IF discriminant == 0 THEN
or
    print the equivalent fahrenheit temperature to temperature in centigrade
or
    social security number <--- ask for the user's social security number

where potential functions are in italics.

A function can take two or more lines in the algorithm. Be careful!

prompt the user and ask for his/her social security number
read the user's input
WHILE the input is not a legal social security number
    print an error message
    prompt the user and ask for his/her social security number
    read the user's input
social security number <--- user's input

The actions in italics together form a function called askForSocialSecurityNumber()


Previous post

Next post




Function declaration and definition

A function definition includes the program code of the function entirely. For example, the definition of printMultiples:

void printMultiples( int multiplier )
{
    cout << "| " << multiplier << " |";

    int multiplicant = 1;
    while( multiplicant <= 9 )
    {
        cout << setw(3) << multiplier*multiplicant;
        ++multiplicant;
    }

    cout << " |" << endl;
}


A function declaration specifies the characteristics:
  • The name of the function
  • The number of parameters
  • The type of each paramete
  • The return type of the function

Declaration has the form:
return_type Function_name(formal_parameters);

For example:
void printMultiples( int multiplier );

A function declaration is also called the function prototype. The declaration has all the information about the function the compiler needs in order to be able to check whether the function call in the code is legal, i.e. is semanctically correct.

The definition has all the information of the declaration, but it also included the body of the function. In practice:
  • A function must always be defined (only once) somewhere in the program code
  • A function must always be either declared or defined before it is called of the first time so that the compiler can check the code for errors
  • A function cannot be defined within another function definition



Previous post

Next post




Saturday, August 22, 2009

Function that returns a value

Functions seen so far don't have a return value, i.e. their return type is void. They can, however, have any data type as a return type. i.e. the function returns data back to where it was called. A function call evaluates a value that can be used as a parameter for other functions, as an operand of operators etc. A C++ function definition is as follows:

return_type function_name ()
{
     function_body
}

or if the function has parameters:

return_type function_name (formal_parameters)
{
     function_body
}

All the same rules and characteristics apply to function name and formal parameters as for void functions. The return type is in every function definition ( and declaration ) and is the type of the value the function returns. The return type defines where the function can be called. The return_type can be any data type.

The function body can be any sequence of executable statements. For example:

double area( double x, double y )
{
     double result = x*y;
     return result;
}

return result; is called a return statement. It terminates the function execution and indicates the value given as the result of the function to the caller. One return statement must always get executed. The syntax of the return statement:

return return_value;

return immediately terminates the execution of the function and the execution continues from where the function was called. The value of the return_value decides to which value the function evaluates in the expression where it was called. The return_value must be of the same type as the return_type of the function.

There can be more than one return statement on the function body. The execution returns from the function immediately when one of the return statements is executed.

double absoluteValue(double x)
{
     if ( x > 0 )
     {
          return x;
     }
     else
     {
          return -x;
     }
}

Also the execution of a void function can be terminated with return. It is just used without the return_value:

return;

Information is passed only into one direction between the caller and a function (caller -> function) when the function does not return a value. Information is passed into both directions between the caller and a function (caller <==> function) when the function returns a value. A function can return only one value at a time. void is in fact a datatype without a value (an "empty" data type). The same rules apply to the declaration and definition of all kinds of functions.


Previous post

Next post




Function

Functions can be used to structure the program by breaking it into smaller, more manageable units. The goal of using functions is again to break difficult and large problems into smaller and smaller pieces until the pieces are small and simple enough. The program is completed by combining the small pieces to work together.

In C++ a function is defined:

void Function_name ()
{
     The body of the function
}

or if the function has parameters:

void Function_name (formal_parameters)
{
     The body of the function
}

Function name is an identifier that names the function. Function name can be any name that is valid as variable name. It is sensible to choose a name that describes well what the function does. It makes the program more understandable.

The body of the function is a sequence of statements that describe the behavior of the function. Since the idea of functions is to break a large problem into more manageable parts the body shouldn't be too long. A good rule of thumb:

When the function takes more lines than fit the screen think hard how it could be divided into two or more functions that together have the same functionality.

Formal parameters is a list of declarations of the function's parameters, separated by commas. The formal parameters defined in the parameter list function like normal local variables in the function body except that they are automatically assigned the values given when the function is called with actual parameters. So formal parameters are a kind of "dummy" parameters and they are bound to actual parameters only when the function is called. A function can gain access to data and process that data through formal parameters. A function can have several parameters or none depending on the situation. The body of the function is executed by calling the function.

A function call:

The name of the function and then in parentheses expressions
  • int the same order
  • the same amount
  • of the same type


As the formal parameters define (empty parentheses if there are no parameters) and ;

When the function is called, the execution is transferred to the first executable statement in the body. When the last statement in the function has been executed, the program execution returns to the point from which the function was called.


Previous post

Next post




Wednesday, August 19, 2009

The ++ operator

In C++ the expression n = n + 1 can be replaced with n++ or ++n. They don't have exactly the same functionality though:

int n = 0;
if( n++ == 1 )
{
     cout << "Hi" << endl;
}

n = 0;
if( ++n == 1 )
{
     cout << "Hello" << endl;
}

Even though n is same after both ifs, only Hello will be printed. The pluses decided whether the value of n is changed before or after the comparison. If we use the ++ preceding the variable then the value will be incremented before the comparison. Care should be taken when using operators like ++. Always try to use a particular one. Prefix ++ is recommended by most persons.


Previous post

Next post




Manipulating the output

For different purposes we may need to manipulate the output in the screen. In C++ a particular header file is given where the manipulating functions are defined. So the first step is to include this header file at the beginning of the code file:

#include  <iomanip>

The most important format manipulators are in the following table but not discussed in detail:

setw(width) Display the next value in the field of size width
left Display values left justified within a field when the value printed needs less space than the width of the field.
right Like left but the value are displayed right justified (default)
setprecision(p) Display p fractional digits for all subsequent output of real values.
fixed Use fixed point notation for real values (with p number of digits)



Previous post

Next post




Tuesday, August 18, 2009

Logical operators

The conditional statements are often too complicated to be expressed by using only the relational operators. Logical operators can be used to combine conditions.

! !p Not (negation)
!p is true if p is false
&& p && q And (conjugation)
p && q is true if both p and q are true
|| p || q Or (disjunction)
p || q is true if either p or q is true


An important feature of the && || operators is that they, unlike arithmetic operators, do not always evaluate their second operand. The operands are evaluated one at a time from left to right and no more operands are evaluated when the result can be deducted. This is called short-circuit evaluation. One expression can be used to guard a potentially unsafe operation. For example: a possible division-by-zero:

int distance = 0;
int speed = 0;
int time = 0;
//...
if( speed != 0 && distance % speed == 0 )
{
     time = distance / speed;
}

where the short-circuit evaluation of && guarantees that an attempt to get the remainder from the division-by-zero or the division-by-zero never occur.


Previous post

Next post




Monday, August 17, 2009

The if statement

The if statement is the most versatile way of writing conditional execution in C++. The if statement has the form:

if( condition1 )
{
     statement1:1;
     ...
     statement1:I;
}
else if( condition2 )
{
     statement2:1;
     ...
     statement2:J;
}
// a necessary amount of else ifs
else
{
     statementN:1;
     ...
     statementN:K;
}

When the execution reaches an if statement the first condition is evaluated first and so on until the condition that evaluates true is found. If the expression is true, the statements following the condition are executed and the execution is continued from the next statement following the if.

The else branch is executed if none of the previous conditions is true. The else if and else branches are volitional.None of the if statement branches is executed if the else is missing and none of the conditions is true.

The braces are not necessary (although recommendable) if there is only one statement in the branch.



Previous post

Next post




Variable scope

The scope of a variable is the section of a program where the variable can be used. The scope depends on where the variable is declared:
  • If a variable is declared within a block, its scope runs from its declaration to the end of the block
  • If a variable is declared outside all blocks (global variable), its scope runs from its declaration to the end of the program


Note that within the scope of the variable other variables with the same name cannot be declared. If the compilers encounters a second variable declaration with the same name it generates an error because of a name conflict.


Previous post

Next post




Variables

Variables can be used to store data in a program. Furthermore, they are symbolic names for data values. They can also be seen as names associeated with a particular memory location in the memory of the computer.

Variables have three characteristics:

     1. a type
     2. a variable name, which is defined when the variable is declared,
        e.g. int line_number;
     3. a value, which is usually assigned to the variable with the = operator,
        e.g. line_number = 1;

The variable may also be initialized (be given an initial value) on declaration,
e.g. int line_number = 1;

All variables must always be declared once (and only once) before they can be used in the program. As a rule, only data of the same type as the variable can be stored in it.

Arithmetic types are an exception in C++. C++ can automatically convert arithmetic types if it is possible. It is correct to say int i = 5.5; NOTE: round-off errors and overflow may occur. A compiler will also complain about such things, so don not do this at home!

After declaration a variable name in the program is substituted with the latest value given to it (with some exceptions as mentioned earlier). Variable declaration can be placed in two places in the program code:

  • Inside any code block (between braces {}) where a statement could be placed. These are called local variables and can only be used inside the program segment it was declared in.
  • Outside all program segments. These kinds of variables are global variables.

It is recommended not to use global variables.

The name of the variable must start with a letter A-Z, a-z. The rest of the characters can also be numbers or underscore '_' characters. However, it is a good programming practice to use meaningful variable names that suggest what they present.
e.g. int current_val = 10; vs int xyz = 12;

A variable can also be a constant. It behaves like any variable but its value cannot be changed. A constant is declared in the same way as a variable but a reserved word const is places before hte declaration. For example:

const int TEMPERATURE = 10;

Constants must always be initialized on declaration since the value cannot be changed after declaration.

When declaring a variable, always think hard what kind of data it represents. The type of the data determines the type of the variable.

A data value with a type and a value but without a name is called a literal. Literals can also be called unnamed constants. For example:
'x', 123456, 3.1415, "Help" are all literals.

Sunday, August 16, 2009

break and continue

The execution of the loop body can be terminated with break and continue.

break terminates the execution of the loop immediately and the control passes to the next statement following the loop.

continue starts a new round in the loop (jumps to the closing brace of the loop body)

The statements effect only the innermost loop they are executed in.


The flow of the events in different loops:






Fig: The while loop





Fig: The do-while loop





Fig: The for loop


Previous post

Next post




do-while and for loop

do-while loop

The do-while loop has the form:

do
{
     statementlist;
} while( loop_condition );

the statementlist in the do-while loop is executed at least once, i.e. it is a post test loop. The basic behavior of do-while loop:

1. The statementlist is executed
2. The loop_condition is evaluated
3. If it is true the control returns to step 1, otherwise control passes to the first statement following the loop.


for loop

The for loop has the form:

for( init_expression; boolean_expression; step_expression )
{
     statementlist;
}

When the program execution reaches a for statement:

1. init_expression is evaluated
2. boolean_expression is evaluated
3. if it is true
a. statementlist is executed
b. step_expression is evaluated
c. Control returns to step 2
4. Otherwise control passes to the statement following the for

The init_expression is evaluated only once at the beginning of execution. Note that it is possible that the statementlist is never executed.


Previous post

Next post