Loop to print odd number is descending order.

Feb 24, 2017 at 4:14pm
Hi!
I am working on an assignment to print a set of odd and even number up to the given input number but I am having trouble with the last part. I want the odd numbers to print in descending order but I am not sure how to do that.

Here's what I have so far

#include <iostream>
using namespace std;
int main()
{
// Get number from user
int input = 0;
cout << "Enter a number:\n";
cin >> input;

// Print numbers from [1..input]
for (int num = 1; num <= input; num++)
cout << num << " ";
cout << endl;

// Print EVEN numbers from [0..input-1] (FIX)
for (int num = 0; num <= input-1; num+=2)
cout << num << " ";
cout << endl;

// Print ODD numbers from [input..1] (FIX)
for (int num = 1; num <= input-1; num+=2)
cout << num << " ";

return 0 ;
}




Thanks!
Feb 24, 2017 at 4:20pm
I want the odd numbers to print in descending order but I am not sure how to do that.

The loop needs to start from the highest number, then subtract 2 each time until the lowest number is reached.
Feb 24, 2017 at 5:46pm
Hi thanks for the reply!
I fix the last part of the code to say this



// Print ODD numbers from [input..1] (FIX)
for (int num=1; num>=input; num-=2)
cout << num << " ";

but now it doesn't print the odd values at all.
Feb 24, 2017 at 6:07pm
The loop starts from num=1. It should start from the highest odd number that you want to print.

The loop should end at 1, not start there.

Hint, you may need to check whether input is odd or even, in order to determine the start value of the for loop.
Last edited on Feb 24, 2017 at 6:11pm
Topic archived. No new replies allowed.