SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Recursion
Exercise:
Self-test Exercises
Question:9 | ISBN:9780321531346 | Edition: 7

Question

Write an iterative version of the function defined in Self-Test Exercise 3.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Before start the program, see the recursion function of 'backwardNums' in Self-Test Exercise 3. Now need to convert from recursive function to iterative function.

Iterative function of 'backwardNums':

//Recursive function of backwardNums:
//It takes one parameter, which is a positive integer. 
//When called, the function writes its argument to the screen backward.
void backwardNums(int number)
{
    while (number >= 10)
    {
         cout << (number%10);
          number = number/10;
    }
    cout << number;
}

 

Complete program by using above Iterative method:

//Header section
#include <iostream>
using namespace std;
//Function prototype
void backwardNums(int n);

//main program
int main( )

{
    //Call the method
    cout<<"If the argument is 1234,then the output: ";
    backwardNums(1234);

    return 0;
}
//Iterative function of backwardNums:
//It takes one parameter, which is a positive integer. 
//When called, the function writes its argument to the screen backward.
void backwardNums(int number)
{
    while (number >= 10)
    {
         cout << (number%10);
          number = number/10;
    }
    cout << number;
}

Output of the program:

0 0

Discussions

Post the discussion to improve the above solution.