Reputation: 5602
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?
Upvotes: 2
Views: 10340
Reputation: 175
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);
}
Upvotes: 1
Reputation: 1171
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);
Upvotes: 0
Reputation: 17277
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) );
Upvotes: 3
Reputation: 13596
Use a for loop changing the increment stage:
for (int i = 1; i < 10; i += 2)
System.out.println(i);
Upvotes: 1