Need help (for loop)
Feb 12, 2014 at 7:32pm UTC
How can I get my code to print from input number to zero with only odd numbers?
I want my code to look like
input=10
9 7 5 3 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
My code looks like this :
#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 number = 0; number <= input;number= number+2)
cout << number << " " ;
cout << endl;
// Print ODD numbers from [input..1] (FIX)
for (int numbe = 1; numbe <= input && numbe>0;numbe= input-2)
if (numbe%2 == 0){
cout << (input-1) << " " ;}
cout << numbe;
cout << endl;
return 0 ;
}
Feb 12, 2014 at 8:10pm UTC
Hi @mlor3,
it's fairly simple
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
//PrintOdd.cpp
//##
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main(){
int number;
cout<<"\nEnter number: " ;
cin>>number;
for (int i=number-1;i>=1;i--){
if (i%2!=0)
cout<<i<<' ' ;
}//end for
cout<<endl;
return 0; //indicates success
}//end of main
./PrintOdd
Enter number: 15
13 11 9 7 5 3 1
Feb 12, 2014 at 8:17pm UTC
@eyenrique
Thank you so much! its so tough to understand.
Feb 12, 2014 at 8:24pm UTC
You are welcome!
for (int i=number-1;i>=1;i--)
The loop starts at
number-1
if number is 10
then:
subtracting one
i--
until variable
i is greater or equal to
1 -one-
and you already
know the rest.
Topic archived. No new replies allowed.