Program to print numbers from N to 1 in reverse order
Last Updated :
11 Jul, 2022
Given a number N, the task is to print the numbers from N to 1.
Examples:
Input: N = 10
Output: 10 9 8 7 6 5 4 3 2 1
Input: N = 7
Output: 7 6 5 4 3 2 1
Approach 1: Run a loop from N to 1 and print the value of N for each iteration. Decrement the value of N by 1 after each iteration.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void PrintReverseOrder( int N)
{
for ( int i = N; i > 0; i--)
cout << i << " " ;
}
int main()
{
int N = 5;
PrintReverseOrder(N);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void PrintReverseOrder( int N)
{
for ( int i = N; i > 0 ; i--)
System.out.print( +i + " " );
}
public static void main(String[] args)
{
int N = 5 ;
PrintReverseOrder(N);
}
}
|
Python3
def PrintReverseOrder(N):
for i in range (N, 0 , - 1 ):
print (i, end = " " );
if __name__ = = '__main__' :
N = 5 ;
PrintReverseOrder(N);
|
C#
using System;
class GFG{
static void PrintReverseOrder( int N)
{
for ( int i = N; i > 0; i--)
Console.Write(i + " " );
}
public static void Main(String[] args)
{
int N = 5;
PrintReverseOrder(N);
}
}
|
Javascript
<script>
function PrintReverseOrder(N)
{
for (let i = N; i > 0; i--)
document.write(i + " " );
}
let N = 5;
PrintReverseOrder(N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Approach 2: We will use recursion to solve this problem.
- Check for the base case. Here it is N<=0.
- If base condition satisfied, return to the main function.
- If base condition not satisfied, print N and call the function recursively with value (N – 1) until base condition satisfies.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void PrintReverseOrder( int N)
{
if (N <= 0) {
return ;
}
else {
cout << N << " " ;
PrintReverseOrder(N - 1);
}
}
int main()
{
int N = 5;
PrintReverseOrder(N);
return 0;
}
|
Java
class GFG{
static void PrintReverseOrder( int N)
{
if (N <= 0 )
{
return ;
}
else
{
System.out.print(N + " " );
PrintReverseOrder(N - 1 );
}
}
public static void main(String[] args)
{
int N = 5 ;
PrintReverseOrder(N);
}
}
|
Python3
def PrintReverseOrder(N):
if (N < = 0 ):
return ;
else :
print (N, end = " " );
PrintReverseOrder(N - 1 );
N = 5 ;
PrintReverseOrder(N);
|
C#
using System;
class GFG{
static void PrintReverseOrder( int N)
{
if (N <= 0)
{
return ;
}
else
{
Console.Write(N + " " );
PrintReverseOrder(N - 1);
}
}
public static void Main()
{
int N = 5;
PrintReverseOrder(N);
}
}
|
Javascript
<script>
function PrintReverseOrder(N)
{
if (N <= 0)
{
return ;
}
else
{
document.write(N + " " );
PrintReverseOrder(N - 1);
}
}
let N = 5;
PrintReverseOrder(N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...