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:5 | ISBN:9780321531346 | Edition: 7

Question

Write a recursive void function that takes a single int argument n and

writes integers n, n-1, … , 3, 2, 1. Hint: Notice that you can get from the

code for Self-Test Exercise 4 to that for Self-Test Exercise 5 (or vice versa) by an exchange of as little as two lines.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Recursive function:

//Recursive function of decreaseCount:
//It takes a single int argument n and
//writes integers n, n-1, … , 3, 2, 1.
void decreaseCount( int n )
{
    if (n >= 1)   
    {   
       
        cout <<n << " "; 
         decreaseCount(n - 1);
    }
}

 

Complete program by using above recursive function:

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

//main program
int main( )

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

    return 0;
}
//Recursive function of decreaseCount:
//It takes a single int argument n and
//writes integers n, n-1, … , 3, 2, 1.
void decreaseCount( int n )
{
    if (n >= 1)   
    {   
       
        cout <<n << " "; 
         decreaseCount(n - 1);
    }
}

Output of the program:

0 0

Discussions

Post the discussion to improve the above solution.