Click here to Skip to main content
14,828,250 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Write a C++ program to print the following output-

5 4 3 2 1
5 4 3 2
5 4 3
5 4
5

What I have tried:

#include <iostream>

using namespace std;

int main()
{
     int i,j;
     for(i=1; i<=5; i++){
        for(j=5; j<=i; j--){
            cout<<j;
        }
        cout<<'\n';
     }
      return 0;
}


I don't know what is wrong with this code but it doesn't gives me the desired output.
Posted
Updated 7-Sep-18 2:53am

Try
C++
for(j=5; j>=i; j--){
   
Comments
Member 13837433 7-Sep-18 9:53am
   
Thanks!
Patrice T 7-Sep-18 12:43pm
   
you are welcome
You should be testing j to be greater than or equal to i.
C++
for(j=5; j >= i; j--){
   
Comments
Member 13837433 7-Sep-18 9:54am
   
Thanks, I don't know how I didn't notice that, thanks again for helping me.
Take a look at underlined text:
for(j=5; j<=i; j--)

j will never be less or equal i, because on the beginning j=5 and i=1.
   
Comments
Member 13837433 7-Sep-18 9:54am
   
Thanks, I don't know how I didn't notice that, thanks again for helping me.
Maciej Los 7-Sep-18 11:45am
   
You're very welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900