2

I would like to generate sequence number from 01 to 10. But I only want the odd ones. For example,

01 03 05 07 09

I tried this way.

for (int i = 1; i < 10; i++) { String sequence = String.format("%02d", i); System.out.println(sequence); //this prints out from 01,02,03.... to 09. 

So how should I change my code to omit the even ones in between?

11
  • 6
    Any reason you don't just use i += 2 in the loop? Commented Jun 3, 2014 at 18:57
  • 1
    my bad, Brendan. I have edited it now. Commented Jun 3, 2014 at 18:58
  • ones are not even. and what you want could also be if(i%2==1) (the modulo operator) Commented Jun 3, 2014 at 19:00
  • @nl-x would be less efficient though Commented Jun 3, 2014 at 19:11
  • @Chandrew that's why I didn't put it as an answer. But it can't hurt Zip's mind to know this Commented Jun 3, 2014 at 19:12

4 Answers 4

3

Since you want it formatted, only with odd numbers, this outputs:

01 03 05 07 09

for (int i = 1; i < 10; i+=2) System.out.println( String.format("%02d", i) ); 
Sign up to request clarification or add additional context in comments.

Comments

1

Use a for loop changing the increment stage:

for (int i = 1; i < 10; i += 2) System.out.println(i); 

2 Comments

haha.. I am so used to with the old for loop and forget that I can do this way. Thanks for the help!
No need to change the 10 to 8 @AnubianNoob
1

You can just make the loop increment by 2 instead of by just 1!

Example with your code:

for (int i = 1; i < 10; i+=2) { String sequence = String.format("%02d", i); System.out.println(sequence); } 

Comments

0

just use a loop

For loop

for(int i=1;i<=10;i+=2) System.out.println(i); 

While loop

int i=1; while(i<=10){ System.out.println(i); i+=2; } 

Do-While loop

int i=1; do{ System.out.println(i); i+=2}while(i<=10); 

3 Comments

@nl-x : No they wont! after 9 i will become 11 and the loops will break!
You don't like spaces?
@Chandrew : what do you mean?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.