Wednesday, June 19, 2013

Implementing fibonacci series algorithm C++

Code below gives the recursive implementation of Fibonacci series algorithm.
The method Fibonacci finds the Fibonacci for the given number and we have printed out the Fibonacci series for the given number using the for loop in main method.


//Print the Fibonacci series

#include <iostream>
using namespace std;

int Fibonacci( int num )
{
    if (num <= 0 )
    {
        return 0;
    }

    if (num == 1 )
    {
        return 1;
    }

    return
(Fibonacci(num - 1) + Fibonacci(num - 2));
}

int _tmain(int argc, _TCHAR* argv[])
{
    int num = 10;
    //cin >> num;
    for(  int i = 0; i <= num; i++ )
    {
        cout << " " <<
Fibonacci(i) ;
    }
    cout << endl;
    return 0;
} 

The out put of above method will be as below for  10 as input value. 


 0 1 1 2 3 5 8 13 21 34 55

Tuesday, June 18, 2013

Check if the sub string exist in the target string : C++ code

Function below gives checks if the given sub string exists in the target string and prints the index of sub string.  


//Check if the given sub string exists in the string

#include <iostream>
using namespace std;

bool CheckIfSubStringMatches(char * pStr, char * pSubStr)
{
    while( ('\0' != *pSubStr) && ('\0' != *pStr) )
    {
        if( *pSubStr != *pStr )
            break;
        pSubStr++;
        pStr++;
    }

    if( '\0' == *pSubStr )
    {
        return true;
    }

    return false;
}

void SearchSubstring( char* pBigString, char* pSubstring)
{
    if( NULL == pBigString )
    {
        cout<< "Invalid string entered. None found" << endl;
        return;
    }

    if( NULL == pSubstring )
    {
        cout << "Invalid sub string to search." << endl;
        return;
    }

    if( strlen(pBigString) < strlen(pSubstring) )
    {
        cout << "None found " << endl;
        return;
    }

    char * pStr = pBigString;
    char * pSubStr = pSubstring;
    int index = 0;

    while( '\0' != *pStr )
    {
        if( *pStr == *pSubStr)
        {
            if( CheckIfSubStringMatches(++pStr, ++pSubStr) )
            {
                cout << "Found SubString at Index = " << index << endl;
                return;
            }
            pSubStr = pSubstring;
        }
        else
        {
            pStr++;
        }
        index++;
    }  

    cout << "None found " << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{

    char myStr[4][5] =    {{"This"},
                         {"put."},
                         {"xxxx"},
                         {"g I "}
                      };
    char * string = "This is the string I wanted to input.";
    for( int ctr = 0; ctr < 4; ctr++ )
    {
        SearchSubstring( string, myStr[ctr] );
    }
    return 0;
}

The output of code above is given below

Found SubString at Index = 0
Found SubString at Index = 33
None found
Found SubString at Index = 17