Write a recursive function that takes a non-negative integer as an argument and displays the same number in reverse order (i.e. in order from right to left). For example, if the argument is 76538, it would display 83567.

Respuesta :

Answer:

Following are the program in C++ language

#include<iostream> // header file

using namespace std; // namespace std

int reverse(int n1); // function prototype

int main()  // main function()

{

   int num; // Variable declaration

   cout << "Enter the number" << endl;

   cin >> num; // Read the number bu the user

  cout<<"After Reverse the digit:\n";

   int res= reverse(num); // calling function reverse

   

   cout<<res; // display  

}

int reverse(int n1) // function definition of reverse

{

   if (n1<10)  // checking the base condition

       {

           return n1;

       }

   else

       {

           cout << n1 % 10; // Printed the last digit

          return reverse(n1/10); // calling itsself

}

}

Output:

Enter the number:

76538

After Reverse the digit:

83567

Explanation:

Following are the description of the program

  • In the main function read the number by user in the "num" variable of int type.
  • Calling the reverse and pass that "num" variable into it.
  • After calling the control moves to the body of the reverse function.In this function we check the two condition

        1  base condition

   if (n1<10)  // checking the base condition

       {

           return n1;

     }

      2  General condition

  else

       {

           cout << n1 % 10; // Printed the last digit

          return reverse(n1/10); // calling itsself

       }

  • Finally return the reverse number and display them into the main function.

Otras preguntas

ACCESS MORE
EDU ACCESS
Universidad de Mexico