My experience on my daily works... helping others ease each other

Friday, March 16, 2012

Improved Recursive Function that is not improving at all

#include

#include
void printIntegesr(int n);
main()
{
   int number;
   cout << “\nEnter an integer value :”;
   cin << number;
   printIntegers(number);
}


void printIntegers (int nom)
{
    cout << “\Value : “ << nom;
    printIntegers (nom);
}

The above is the original recursive function which will definitely put the program in infinite mode.


#include
#include


void printIntegers(int n);


main()
{
   int number;
   cout<<“\nEnter an integer value :”;
   cin >> number;
       printIntegers(number);
}


void printIntegers (int nom)
{
    if (nom >= 1)
          cout << “\Value : “ << nom;
     printIntegers (nom-2);
}

What is wrong with the above 'improved recursive function'?

Not sure? Guess what will happen if the condition is met? It will print out the value and then move to the next step and continue to call the function again. What if the condition failed? It will just call the function again. And this will continue in a never ending loop.

The above two code is extracted from a lecture note. An email has been send to them for confirmation.

How to solve that?

Here the fraction of it on how it can be solved.... have fun trying. BTW, the above infinite loop code will allowed hackers to hack into the program :)

void printIntegers (int nom)
{
    if (nom >= 1)
          cout << “\Value : “ << nom;
    if ( nom < 1 )
         exit(1);
     printIntegers (nom-2);
}
Share:

0 comments:

About Me

Somewhere, Selangor, Malaysia
An IT by profession, a beginner in photography

Blog Archive

Blogger templates