Question 3: modify a program (recursion, loops) [6]

Re-write functions f and g in the program below so that
(i) function f uses a loop instead of recursion to carry out its error checking/re-prompt cycle, and
(ii) function g uses recursion instead of a loop to display the countdown.

#include <cstdio>

int f();
void g(int n);

int main()
{
   int counter = f();
   g(counter);
}

void g(int n)
{
   while (n > 1) {
      printf("%d\n", n);
      n = n - 2;
   }
}

int f()
{
   int val, numRead;
   printf("Please enter an odd integer\n");
   numRead = scanf("%d", &val);
   if ((numRead == 0) || ((val % 2) == 0)) {
      printf("Incorrect, try again\n");
      if (numRead == 0) {
         scanf("%*s");
      }
      val = f();
   }
   return val;
}

Sample solution:
void g(int n)
{
   if (n > 1) {
      printf("%d\n", n);
      g(n-2);
   }
}

int f()
{
   int val, numRead;
   do {
      printf("Please enter an odd integer\n");
      numRead = scanf("%d", &val);
      if ((numRead == 0) || ((val % 2) == 0)) {
         printf("Incorrect, try again\n");
         if (numRead == 0) {
            scanf("%*s");
         }
      }
   } while ((numRead == 0) || ((val % 2) == 0));
   return val;
}