Thursday, September 25, 2014

Using Enumeration in C++

Enumeration in C++ is a user defined type that contains a set of constant values. An enumeration consists of an identifier and a list of types. Every type in an enumeration corresponds to a constant value. Default value for the first type is integer 0 and the next one gets the integer value 1. But an enumeration type can have a value other than default integer 0. Therefore an enum type can be casted to integer.


Following sample project created by qt creator and contains following files:
1- UsingEnumeration.pro
2- device.h
3- device.cpp
4- main.cpp



UsingEnumeration.pro file contains project configuration.

TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt
SOURCES += main.cpp \
    device.cpp
HEADERS += \
    device.h

device.h header file contains definition for Device class and Status enumeration.

#ifndef DEVICE_H
#define DEVICE_H

namespace UsingEnumsSample
{

enum Status {
    IDLE = 0,
    ACTIVE = 1,
    DEAD = 2
};

class Device
{
public:

    Device();
    void setStatus(Status pStatus);
    Status getStatus();

private:
    Status status;
};

}

#endif // DEVICE_H


device.cpp file contains implementation for Device class. setDevice method accepts an enumerator and assigns the passed value to Device class private enumeration member.

#include "device.h"

namespace UsingEnumsSample
{

Device::Device()
{
}

void Device::setStatus(Status pStatus)
{
    status = pStatus;
}

Status Device::getStatus()
{
    return status;
}

}

main.cpp method creates a Device instance and calls its setStatus and getStatus methods to set the Status value to the private Status enumeration member.

#include <iostream>
#include "device.h"

using namespace std;
using namespace UsingEnumsSample;

int main()
{
    Device device;
    device.setStatus(ACTIVE);
    cout << device.getStatus() << endl;
    device.setStatus(IDLE);
    cout << device.getStatus() << endl;
    return 0;
}

When the main method is executed, values of the Status member is displayed on the terminal which are consequently 1 and 0 as the program runs.

Wednesday, August 13, 2014

boost::array of std::string items in Qt Creator

boost::array is a template class which enables it to be able to be declared for different type of items. There exists an array as a member inside boost:array template class declaration so boost:array also acts a C-array wrapper with fixed number of items inside it.

Following sample project created by qt creator and contains following files:
1- BoostArrayOfStrings.pro
2- main.cpp



BoostArrayOfStrings.pro file contains project configuration.

TEMPLATE = app
CONFIG += console

SOURCES += main.cpp

INCLUDEPATH += /home/tufan/boost_1_55_0

Boost header files and libraries are located under the directory : /home/tufan/boost_1_55_0

main.cpp file contains main method.

#include <boost/array.hpp>
#include <string.h>

using namespace std;

int main()
{
    typedef boost::array<string,3> boostArray;
    boostArray stringArray;

    stringArray[0] = "FirstStringMember";
    stringArray.at(1) = "SecondStringMember";
    stringArray.at(2) = "ThirdStringMember";

    // some common container operations
    cout << "size:     " << stringArray.size() << endl;
    cout << "empty:    " << boolalpha << stringArray.empty() << endl;
    cout << "front:    " << stringArray.front() << endl;
    cout << "back:     " << stringArray.back() << endl;
    cout << "elements:    " << endl;

    for(boostArray::iterator iter(stringArray.begin()); iter != stringArray.end(); ++iter)
    {
        cout << *iter << endl;
    }

    return 0;
}
boost array contains 3 string items. Members of the array are initialized by using array subscript operator and at() function.

size:     3
empty:    false
front:    FirstStringMember
back:     ThirdStringMember
elements:  
FirstStringMember
SecondStringMember
ThirdStringMember

Tuesday, August 12, 2014

boost::array of Integers in Qt Creator

boost::array provides C-style array declaration and usage with constant number of items inside it. When only static-constant sized arrays are required, then boost::array comes with a better memory management solution than std::vector.

After including boost libraries into a Qt Creator C++ project, it becomes easy to use boost::array type of members in your programs.

boost/array.hpp file contains boost::array type.

As the boost::array documentation indicates boost::array is the STL compliant container wrapper for arrays of constant size.



Following sample project created by qt creator and contains following files:

1- BoostArrayOfIntegers.pro
2- main.cpp


BoostArrayOfIntegers.pro file contains project configuration.
TEMPLATE = app
CONFIG += console

SOURCES += main.cpp

INCLUDEPATH += /home/tufan/boost_1_55_0

I have installed the boost library to the directory         :  /home/tufan/boost_1_55_0
and boost/array.hpp file is located at                           :  /home/tufan/boost_1_55_0/boost/array.hpp

so qt creator does not complain about path related errors.


There is also another installed boost library which contains an older version of boost libraries  at directory : /usr/include/boost


In BoostArrayOfIntegers.pro file I have stated that I will use the boost library from specific location and qt creator selected the library from : /home/tufan/boost_1_55_0


main.cpp file contains main method.

#include <boost/array.hpp>

using namespace std;

int main()
{
    typedef boost::array<int, 4> intArrayType;
    intArrayType myArray = {{1,2,3,4}};
    std::cout << "boost intArray content :" << "\n";
    for( intArrayType::const_iterator iterator = myArray.begin(),
         iteratorEnd = myArray.end();
         iterator != iteratorEnd; ++iterator )
    {
        cout << *iterator << endl;
    }

    return 0;
}
boost::array is initialized with 4 integer members in curly braces. I used an iterator to traverse the integer members of the boost::array.

When the project is executed the following terminal output is generated :

boost intArray content :
1
2
3
4

Friday, August 1, 2014

Build Boost 1.55.0 C++ Libraries on Ubuntu

  Boost libraries are used by C++ programmers to increase the productivity of software product development process. Instead of reinventing the wheel, by using Boost libraries initial-development time costs are decreased remarkably.
  Boost libraries include many benefits for C++ programmers, such as shared_ptr, arrays, serialization, I/O etc. , which most of the time causes troubles. So it becomes crucial to invest time to learn Boost libraries for a C++ programmer to use these benefits and advantages.
  Most Linux distributions come with pre-installed Boost libraries. However, they do not always contain the latest version of Boost libraries.
  In order to build and start using on Ubuntu OS following steps can be followed :

1- download boost_1_55_0.zip file from
 
    http://sourceforge.net/projects/boost/files/boost/1.55.0/

2- unzip your downloaded boost_1_55_0.zip file

    $ unzip boost_1_55_0.zip

3- get required dependencies which are going to help you during build process
 
    $ sudo apt-get update
    $ sudo apt-get install build-essential g++ python-dev autotools-dev libicu-dev build-essential libbz2-dev

4- change your location into your unzipped boost_1_55_0 folder from terminal
 
    $ cd boost_1_55_0/

5- start bootstrapping

    $ ./bootstrap.sh --prefix=/usr/local

6- start building boost libraries

    $ sudo ./b2

7- after waiting for a time-period all the Boost libraries are built successfully.

    "The Boost C++ Libraries were successfully built!"

8- now Boost header files and libraries are ready for being used in your C++ applications.

Sunday, May 11, 2014

Throw and Catch Custom Exception Object in C++

Exceptions are run-time errors that occur during program execution. C++ Standard Library comes with a base class "exception" which is mainly dealing with exceptions. In some circumstances it is required to create-design your own custom exception classes in C++ as in other object oriented programming languages.
what() function of exception class of C++ Standard Library used to provide detailed information about the problem to the client program code in the case of an exception.

Following sample project created by qt creator and contains following files:
1- CustomException.pro
2- DequeWrapper.h
3- DequeWrapper.cpp
4- EmptyContainerException.h
5- EmptyContainerException.cpp
6- main.cpp

CustomException.pro file contains project configuration.

TARGET = CustomException
TEMPLATE = app
SOURCES += main.cpp \
           DequeWrapper.cpp \
           EmptyContainerException.cpp

HEADERS += \
           DequeWrapper.h \
           EmptyContainerException.h

main.cpp file contains main method and the usage of the EmptyContainerException exception instance.
#include "DequeWrapper.h"
#include <iostream>

using namespace std;
using namespace CustomContainers;

int main()
{
    try
    {
        DequeWrapper mDequeWrapper;
        mDequeWrapper.popBack();
    }
    catch(const EmptyContainerException& ex)
    {
        cerr << ex.what() << endl;
    }

    return 0;
}

DequeWrapper.h is the header file for the deque wrapper class declaration.
#ifndef DEQUEWRAPPER_H
#define DEQUEWRAPPER_H

#include <deque>
#include "EmptyContainerException.h"

namespace CustomContainers
{

class DequeWrapper
{
public:
    bool empty() const;
    int popBack();

protected:
    std::deque mDeque;
};

}
#endif // DEQUEWRAPPER_H

DequeWrapper.cpp is the implementation file for the deque wrapper header file.

#include "DequeWrapper.h"

namespace CustomContainers
{

bool DequeWrapper::empty() const
{
    return mDeque.empty();
}

int DequeWrapper::popBack()
{

    if(mDeque.empty())
        throw EmptyContainerException();

    int mItem(mDeque.back());
    mDeque.pop_back();
    return mItem;
}

}
EmptyContainerException.h file is the header file for the custom exception class declaration.
#ifndef EMPTYCONTAINEREXCEPTION_H
#define EMPTYCONTAINEREXCEPTION_H

#include <exception>

namespace CustomContainers
{

class EmptyContainerException : public std::exception
{
    public:
        virtual const char* what() const throw();
};

}

#endif // EMPTYCONTAINEREXCEPTION_H

EmptyContainerException.cpp file is the implementation file for the custom exception class header file.

#include "EmptyContainerException.h"

namespace CustomContainers
{

const char* EmptyContainerException::what() const throw()
{
    return "container is empty!";
}

}

std::exception what() method is reimplemented in the derived class EmptyContainerException to provide the description of the exception. When you run the above sample program main method following console output "container is empty" exception message is generated :


Wednesday, March 5, 2014

Binary Search Sorted Int Array Recursively

There exists a recursive solution for the binary search algorithm. At each step lower and higher bounds for the search interval are updated and the search key is scanned in this new updated interval.
For recursive binary search implementation; search interval is updated depending on the midPoint value.

midPoint = lowerBound+(higherBound-lowerBound)/2

For the starting step; lowerBound is 0 and higherBound is the last array index.

Following sample project created by qt creator and contains following files:
1- SearchIntArrayRecursively.pro
2- main.cpp


SearchIntArrayRecursively.pro file contains project configuration.

TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt
SOURCES += main.cpp

main.cpp file contains main method and recursive binarySearch function implementations.

#include <stdio.h>

int getIndexOfItemRecursively(int pSearchedItem, int* pArray, int mLowerBound, int mHigherBound)
{
    if( mLowerBound > mHigherBound )
        return -1;
    int midIndex = mLowerBound+(mHigherBound-mLowerBound)/2;

    if( pSearchedItem < pArray[midIndex] )
        return getIndexOfItemRecursively(pSearchedItem, pArray, mLowerBound, midIndex-1);
    else if(pSearchedItem>pArray[midIndex])
        return getIndexOfItemRecursively(pSearchedItem, pArray, midIndex+1, mHigherBound );
    else
        return midIndex;
}

int findIndexOfItem( int pSearchedItem, int* pArray, int pTotalItemCount )
{
    return getIndexOfItemRecursively(pSearchedItem, pArray, 0, pTotalItemCount-1);
}

int main(int argc, char* argv[])
{
    int mArray[] = {1, 2, 4, 12, 34, 45, 56, 67, 78, 89, 90};
    int mLengthOfArray = sizeof(mArray)/sizeof(int);
    printf("There are %d items in the array\n", mLengthOfArray);
    printf("Items :\n");
    for(int i = 0; i<mLengthOfArray; i++)
    {
        if( i!=mLengthOfArray-1 )
            printf("%d,", mArray[i]);
        else
            printf("%d\n", mArray[i]);
    }
    printf("Indexes :\n");
    for(int i = 0; i<mLengthOfArray; i++)
    {
        if( i!=mLengthOfArray-1 )
            printf("%d,", i);
        else
            printf("%d\n\n", i);
    }
    int mSearchItem = 12;
    int mIndex = findIndexOfItem( mSearchItem, mArray, mLengthOfArray );
    if( mIndex!=-1 )
        printf("Item %d is at index %d\n", mSearchItem, mIndex);
    else
        printf("Item %d not found in the array\n",mSearchItem);

    mSearchItem = 89;
    mIndex = findIndexOfItem( mSearchItem, mArray, mLengthOfArray );
    if( mIndex!=-1 )
        printf("Item %d is at index %d\n", mSearchItem, mIndex);
    else
        printf("Item %d not found in the array\n",mSearchItem);

    mSearchItem = 91;
    mIndex = findIndexOfItem( mSearchItem, mArray, mLengthOfArray );
    if( mIndex!=-1 )
        printf("Item %d is at index %d\n", mSearchItem, mIndex);
    else
        printf("Item %d not found in the array\n",mSearchItem);

    return 0;
}

We can analyze the steps for the first search item 12.



Search for 12 :

  • Find midPoint. For this case midPoint is at index 5. If the searchItem (12) is less than the item at index midPoint (45) then update higherBound value with midpoint-1.
  • Search in the new range with new higherBound value. higherBound is now midPoint-1. And lowerBound is 0.
New Sub Array Shrinks To 5 Items:

  • Find midPoint. For this case midPoint is at index 2. If the searchItem is higher than the item at index midPoint then update lowerBound value with midpoint+1.
  • Search in the new range with new lowerBound value. lowerBound is now midpoint+1 and higherBound does not change for this case.
New Sub Array Shrinks To 2 Items :
  • Find midPoint. For this case midPoint is at index 3.
  • SearchedItem is not less than the item at midPoint.
  • SearchedItem is not higher than the item at midPoint.
  • Then item is at midPoint. Return index of midPoint.

When you run the above recursive binary search sample following console output is generated :


Tuesday, February 25, 2014

Binary Search Sorted Int Array Iteratively

Binary Search is one of the most widely known search algorithms. One of the main restrictions to use binary search for existing sets is that your list or container must be sorted before searching inside it.
Instead of searching a list or container by using linear-search algorithm, item-by-item, binary search is considered more efficient in terms of time and space.

Following sample project created by qt creator and contains following files:
1- SearchIntArray.pro
2- main.cpp

SearchIntArray.pro file contains project configuration.
CONFIG += console
TEMPLATE = app
SOURCES += main.cpp
main.cpp file contains main method and indexOfItem function implementations.
#include <stdio.h>

int indexOfItem(int pSearchedtem,int* pArray,int pTotalItemCount)
{
    int mLowerBound = 0;
    int mHigherBound = pTotalItemCount-1;

    while( mLowerBound<= mHigherBound )
    {
        int midIndex = mLowerBound+(mHigherBound-mLowerBound)/2;
        if( pSearchedtem < pArray[midIndex] )
            mHigherBound = midIndex-1;
        else if(pSearchedtem>pArray[midIndex])
            mLowerBound = midIndex+1;
        else
            return midIndex;
    }

    return -1;
}

int main(int argc, char* argv[])
{
    int mArray[] = {1, 2, 4, 12, 34, 45, 56, 67, 78, 89, 90};
    int mLengthOfArray = sizeof(mArray)/sizeof(int);
    printf("There are %d items in the array\n", mLengthOfArray);
    printf("Items :\n");
    for(int i = 0; i<mLengthOfArray; i++)
    {
        if( i!=mLengthOfArray-1 )
            printf("%d,", mArray[i]);
        else
            printf("%d\n", mArray[i]);
    }
    printf("Indexes :\n");
    for(int i = 0; i<mLengthOfArray; i++)
    {
        if( i!=mLengthOfArray-1 )
            printf("%d,", i);
        else
            printf("%d\n\n", i);
    }
    int mSearchItem = 12;
    int mIndex = indexOfItem(mSearchItem,mArray,mLengthOfArray);
    if( mIndex!=-1 )
        printf("Item %d is at index %d\n", mSearchItem, mIndex);
    else
        printf("Item %d not found in the array\n",mSearchItem);

    mSearchItem = 89;
    mIndex = indexOfItem(mSearchItem,mArray,mLengthOfArray);
    if( mIndex!=-1 )
        printf("Item %d is at index %d\n", mSearchItem, mIndex);
    else
        printf("Item %d not found in the array\n",mSearchItem);

    mSearchItem = 91;
    mIndex = indexOfItem(mSearchItem,mArray,mLengthOfArray);
    if( mIndex!=-1 )
        printf("Item %d is at index %d\n", mSearchItem, mIndex);
    else
        printf("Item %d not found in the array\n",mSearchItem);

    return 0;
}

indexOfItem function implements binary search algorithm in C programming language iteratively. indexOfItem function takes the item to search for inside the array as one of its incoming parameters and function returns the index of the found item or -1 if not was found.

Binary Search algorithm, as described at http://algs4.cs.princeton.edu/home/ ,
         
             - lowerBound = 0
             - higherBound = itemCount-1
             - loop until lowerBound is less than or equal to the upper bound
                       - divides the sorted container into 2 parts at the center, find middle index
                       - compares the searchKey with the the item which is at the middle index
                               - if the searchKey is greater than the item which is at the middle index
                                                     - then update the lower bound for search with (middle index+1)
                               - else if the searchKey is lower than the item which is at the middle index
                                                     - then update the upper bound for search with (middle index-1)
                               - else
                                       - then the searchKey is the item which is at the middle index
            - end loop
            return indexNotFound

main function contains 3 test-cases for binary search algorithm. First 2 searchKeys (12 and 89) are found in the test array whereas the last searchKey (91) is not found in the list.

Console output contains all the printf function results as follows :


Wednesday, February 12, 2014

Virtual Functions and Inheritance

Inheritance helps to reduce the amount of code written or repeated by using a base-derived relation in object-oriented-world. Common functions are collected in a base class and the derived class extends or directly uses the existing base class functions. In some situations base class also can be pointing to different derived classes depending on the run-time behavior.

When base class is used to point to derived class, base class pointer calls overridden base-class methods, if there are any base class virtual method re-implementations in the derived class. Virtual functions in C++ help to transfer a specific behavior in the base class to derived class by declaring the function virtual in the base class. Derived is free to re-implement base class virtual functions.

If the derived class does not provide any implementation for the base class virtual functions then the base class virtual functions are called. This is not always the expected behavior because base class virtual functions are declared to be overridden in the derived class.

Following sample project created by qt creator and contains following files:
1- VirtualFunctions.pro
2- main.cpp
3- abstractservice.h
4- abstractservice.cpp
5- activityservice.h
6- activityservice.cpp
7- userservice.h
8- userservice.cpp



VirtualFunctions.pro file contains project configuration.

TARGET = VirtualFunctions
CONFIG   += console
TEMPLATE = app
SOURCES += main.cpp \
    abstractservice.cpp \
    userservice.cpp \
    activityservice.cpp

HEADERS += \
    abstractservice.h \
    userservice.h \
    activityservice.h

abstractservice.h is the base class that contains virtual functions.

#ifndef ABSTRACTSERVICE_H
#define ABSTRACTSERVICE_H

#include <stdio.h>

class AbstractService
{
public:
    AbstractService();
    virtual ~AbstractService();
    // calls both base and derived dest
    // prevents memory leaks

    virtual void insertRecord();
    virtual void selectRecord();
    virtual void deleteRecord();
    virtual void updateRecord();

};

#endif // ABSTRACTSERVICE_H

In the base class abstractservice.h destructor is also defined virtual otherwise derived class destructor is not called at object deletion.

abstractservice.cpp is the base class implementation file that contains implementations for virtual functions, constructor and destructor.

#include "abstractservice.h"

AbstractService::AbstractService()
{
    printf("AbstractService::AbstractService called\n");
}

AbstractService::~AbstractService()
{
    printf("AbstractService::~AbstractService called\n");
}

void AbstractService::insertRecord()
{
    printf("AbstractService::insertRecord called\n");
}

void AbstractService::selectRecord()
{
    printf("AbstractService::selectRecord called\n");
}

void AbstractService::deleteRecord()
{
    printf("AbstractService::deleteRecord called\n");
}

void AbstractService::updateRecord()
{
    printf("AbstractService::updateRecord called\n");
}

userservice.h is the first derived class that contains its own implementations for the virtual functions that are declared in the base class abstractservice.
#ifndef USERSERVICE_H
#define USERSERVICE_H

#include "abstractservice.h"

class UserService : public AbstractService
{
public:
    UserService();
    ~UserService();

    void insertRecord();
    void selectRecord();
    void deleteRecord();
    void updateRecord();
};

#endif // USERSERVICE_H

userservice.cpp contains implementation details for the base class virtual functions.
#include "userservice.h"

UserService::UserService()
{
    printf("UserService::UserService called\n");
}

UserService::~UserService()
{
    printf("UserService::~UserService called\n");
}

void UserService::insertRecord()
{
    printf("UserService::insertRecord called\n");
}

void UserService::selectRecord()
{
    printf("UserService::selectRecord called\n");
}

void UserService::deleteRecord()
{
    printf("UserService::deleteRecord called\n");
}

void UserService::updateRecord()
{
    printf("UserService::updateRecord called\n");
}

activityservice.h is the second derived class that re-declares base class virtual functions in its header.
#ifndef ACTIVITYSERVICE_H
#define ACTIVITYSERVICE_H

#include "abstractservice.h"

class ActivityService : public AbstractService
{
public:
    ActivityService();
    ~ActivityService();

    void insertRecord();
    void selectRecord();
    void deleteRecord();
    void updateRecord();
};

#endif // ACTIVITYSERVICE_H

activityservice.cpp file contains implementation details for the base class virtual functions.
#include "activityservice.h"

ActivityService::ActivityService()
{
    printf("ActivityService::ActivityService called\n");
}

ActivityService::~ActivityService()
{
    printf("ActivityService::~ActivityService called\n");
}

void ActivityService::insertRecord()
{
    printf("ActivityService::insertRecord called\n");
}

void ActivityService::selectRecord()
{
    printf("ActivityService::selectRecord called\n");
}

void ActivityService::deleteRecord()
{
    printf("ActivityService::deleteRecord called\n");
}

void ActivityService::updateRecord()
{
    printf("ActivityService::updateRecord called\n");
}

Both of the derived classes provide their own implementations for the virtual functions declared in the base class abstractservice.

main.cpp file contains a main function that is creating different base class pointers which are pointing to derived class objects.
#include "userservice.h"
#include "activityservice.h"

int main(int argc, char *argv[])
{
   UserService *userServicePtr = new UserService;
   userServicePtr->insertRecord();
   userServicePtr->selectRecord();
   userServicePtr->updateRecord();
   userServicePtr->deleteRecord();
   delete userServicePtr;
   printf("\n");

   AbstractService *abstractServiceObjPtr = new AbstractService;
   abstractServiceObjPtr->insertRecord();
   abstractServiceObjPtr->selectRecord();
   abstractServiceObjPtr->updateRecord();
   abstractServiceObjPtr->deleteRecord();
   delete abstractServiceObjPtr;
   printf("\n");

   // base class pointer to derived class object
   char option = 'a';
   AbstractService *serviceObjPtr;
   if( option == 'u' )
   {
       serviceObjPtr = new UserService;
       serviceObjPtr->insertRecord();
       serviceObjPtr->selectRecord();
       serviceObjPtr->updateRecord();
       serviceObjPtr->deleteRecord();
       delete serviceObjPtr;
       printf("\n");
   }
   else if( option == 'a' )
   {
       serviceObjPtr = new ActivityService;
       serviceObjPtr->insertRecord();
       serviceObjPtr->selectRecord();
       serviceObjPtr->updateRecord();
       serviceObjPtr->deleteRecord();
       delete serviceObjPtr;
       printf("\n");
   }

   return 0;
}

At runtime base class pointer serviceObjPtr points to either UserService instance or ActivityService instance.

Console output also shows the order for object creation and destruction.


Monday, February 10, 2014

Swap Values With Function Template

Swap values function is commonly used in applications that make operations on arithmetic values such as int,double and float. Instead of implementing overloaded functions for different data types to handle swap operation, function templates can be preferred.

Following sample project created by qt creator and contains following files:
1- UsingTemplatesInCPP.pro
2- main.cpp


UsingTemplatesInCPP.pro file contains project configuration.

TEMPLATE = app
TARGET    = UsingTemplatesInCPP
CONFIG   += console
TEMPLATE  = app
SOURCES  += main.cpp

main.cpp file contains main method and swapValues template function implementations.

#include <stdio.h>

template<typename T>
void swapValues(T &param1, T &param2)
{
    T temp = param1;
    param1 = param2;
    param2 = temp;
}

int main(int argc, char *argv[])
{

 int iP1 = 1, iP2 = 2;
 printf("Initial Integer Values : p1 = %d  p2 = %d \n", iP1, iP2);
 swapValues(iP1,iP2);
 printf("Swapped Integer Values : p1 = %d  p2 = %d \n\n", iP1, iP2);

 double dP1 = 1.34, dP2 = 2.45;
 printf("Initial Double Values : p1 = %f  p2 = %f \n", dP1, dP2);
 swapValues(dP1,dP2);
 printf("Swapped Double Values : p1 = %f  p2 = %f \n\n", dP1, dP2);

 float fP1 = 1.67, fP2 = 2.89;
 printf("Initial Float Values : p1 = %f  p2 = %f \n", fP1, fP2);
 swapValues(fP1,fP2);
 printf("Swapped Float Values : p1 = %f  p2 = %f \n", fP1, fP2);

 return 0;
}

When swapValues template function is called with integer parameters the compiler binds integer values for the generic type parameter T and instantiates an instance of the function template with integer parameters.
The same process is followed when double and float instances are instantiated.
Console output contains all the printf function results as follows :

Wednesday, February 5, 2014

Search C-String for a Specific Character

First character of a c-style string which is terminated with a '\0' char can be pointed by a char pointer , " char *ptr ". In addition to that, it is possible to use a char array, " char arr[] " for storing c-style strings. char *ptr and char arr[] can be used interchangeably.

Following sample project created by qt creator and contains following files:
1- SearchCStringForSpecificChar.pro
2- main.cpp


SearchCStringForSpecificChar.pro file contains project configuration.

TEMPLATE = app
CONFIG += console
SOURCES += main.c

main.c file contains main method which is including the algorithm that is traversing the given sample c-string "asd1 a1sd1" to search for the '1' character.
#include <stdio.h>

int main(void)
{
    const char* charArray1 = "asd1 a1sd1";
    const char* charArray2 = "asd1 a1sd1";
    printf("initial char pointer charArray1 is pointing to : %s\n", charArray1);
    printf("char pointer charArray1 is pointing to the start address of the c-string: %d \n\n", charArray1);

    int strLength = 0;
    int foundCharCount = 0;

    while(*charArray1!='\0')
    {
        printf("%c - %c - %c\n", *charArray1, charArray1[0], charArray2[strLength]);
        printf("current char pointer is pointing to the address of : %d\n\n", charArray1);

        if(*charArray1=='1')
            foundCharCount++;

        strLength++;
        charArray1++;
    }

    if(*charArray1 == '\0')
        printf("Found end of string character and exited the while loop: %d\n", *charArray1);

    printf("total number of characters : %d\n", strLength);
    printf("total number of '1' characters : %d\n", foundCharCount);
    printf("last char pointer str is pointing to :%d\n\n", *charArray1);


    return 0;
}

Both charArray1 and charArray2 pointers are containig the same const char values. Till the end-of-string character, '\0' , is found the while loop iterates in the main function.

For the current item *charArray1, charArray1[0] and charArray2[strLength] all gives the same value. If the current value is '1' then the foundCharCount variable is incremented by one.

If the current value is not '\0' then increment the strLength variable by one and move the current char pointer charArray1 to the next address location in memory for checking. Console output contains all the printf function results as follows :

Monday, February 3, 2014

Traverse Array Of C-Strings Char By Char (char* array[])

char* arrayOfCStrings[] is used as an array of pointer to character. Because it is an array and each index of the array contains a pointer to the starting character of a c-string which is terminated by an end-of-string ‘\0’ character.

Following sample project created by qt creator and contains following files:
1- TraverseArrayOfCStringsCharByChar.pro
2- main.cpp
           

TraverseArrayOfCStringsCharByChar.pro file contains project configuration.

TARGET = TraverseArrayOfCStringsCharByChar
SOURCES += main.cpp

main.cpp file contains main method which is showing how to traverse an array of c-strings till an end-of-string character is found for each string.

#include <stdio.h>

int main(int argc, char *argv[])
{

    char* arrayOfCStrings[] = {"string1","string2","string3"};

    int stringCount = sizeof(arrayOfCStrings)/sizeof(char*);

    printf("Total number of strings in the string array : %d \n",stringCount);

    int i = 0;
    while(i<stringCount)
    {
        const char* currentString = arrayOfCStrings[i];
        while((*currentString))
        {
            printf(" %c ", *currentString);
            currentString++;
        }
        printf("\n");
        ++i;
    }

    return 0;
}
arrayOfStrings is initialized by curly braces.

char* arrayOfCStrings[] = {“string1”, “string2”, “string3”};

Total number of strings in the array is computed by dividing the total size of the arrayOfStrings to the size of each char* element.
int stringCount = sizeof(arrayOfCStrings)/sizeof(char*);

Outer while loop iterates till it reaches the total number c-strings. And the inner while loop iterates for each character in the current c-string till the end-of-string '\0' character is found. Console output displays the total number of c-strings in the array and each character of the current c-string in a new line.

Wednesday, January 29, 2014

Traverse C-String Char By Char

Character pointer points to the address of a single character. By accessing the next address location of the current character pointer, until it points to the '\0' char, it gives you the availability to read a whole c-string in a while loop.
Following sample project created by qt creator and contains following files:

1-TraverseC-StringCharByChar.pro
2-main.cpp



TraverseC-StringCharByChar.pro file contains project configuration.
TARGET = TraverseC-StringCharByChar
SOURCES += main.cpp

main.cpp file contains just main method which is showing how to traverse a c-string till an end-of-string character is found.

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
   char* str = "C-StringToTraverse";
   cout<<"Input String = "<<str<<endl<<endl;
   while(*str)
   {
        cout << *str<<endl;
        ++str;
   }
   return 0;
}

A char* points to the start address of the c-string. By incrementing 1, the address of the char* shows the address of the next character in the c-string. While loop executes until it finds the '\0' character which is corresponding to the 0. Therefore, the while loop terminates, because the current char pointer points to 0 which equals to false.
Console output is as follows :