-->




c++ recursive function to print numbers in descending order

Leave a Comment
Write a program in which a function takes input from user and print numbers in descending order using recursion. Make proper prototype with one integer as argument and return an integer. 
hint: int decrement(int);



Program Logic Explanation

  • In this program we have a function having an if-else statement 
  • If and else both have return on the basis of certain conditions.
  • If condition has the base case which means that program output will not return result
    until the base case is true
  • As we know function returns from where it has called so if user enters 5 then function will be
    called 5 times one from the outside and 4 times form else statement when base case becomes
    true it returns in else to 4 times and finally 5th time to main body

C++ Source Code

#include<iostream>
using namespace std;
int decrement(int);
int main()
{
 int number;
 cout<<"Enter number to get decrement using recursion";
 cin>>number;
 cout<<decrement(number);
 cout<<" "<<endl;
 return 0;
}
int decrement(int num)
{
 if(num==1)
 {

  return 1;
 }
 else
 {
  cout<<num<<" ";
  return decrement(num-1);
 }
}


Example input output
c++ recursive function example to output numbers in descending order

It is recommended to change the code, dry run on a paper and examine the output.
See more examples here
C++ Simple example for beginners

0 comments:

Post a Comment