Javier
Javier

Reputation: 25

Java Odd Number Loop

I am trying to output the first "x" odds, but I am clueless on how to stop the loop at the number that x is. For example... if you input 6, I want it to show 1, 3, 5, 7, 9, 11. However, my coding does it for all the odds.

import java.util.Scanner;


public class OddNumber {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println("Please input a number.");
    Scanner keyboard = new Scanner(System.in);
    int x = keyboard.nextInt();
    int total = x*x;
    if (x > 0){
        System.out.println("The first 5 odd numbers are...");
    }
    if (x > 0){
        for (int i = 0; i < total; i++){
        if (i % 2 != 0){
            System.out.println(i+"");
        }}
    System.out.println("The total is "+total);
    }

        }


}

Upvotes: 2

Views: 17936

Answers (7)

Dima Bors
Dima Bors

Reputation: 40

For odd numbers:

for(int i=0; i<number; i++)
   {
   i=i+1;

   System.out.println(i);
   }

For even numbers:

for(int i=1; i<number; i++)
   {
   i=i+1;

   System.out.println(i);
   }

Upvotes: 0

Joe&#39;s Morgue
Joe&#39;s Morgue

Reputation: 173

Your if (i % 2 != 0){

You can address it a few ways.

After that, you can:

 if (i != x){
    System.out.print(i+", ");
 }

OR, you can:

 if (i % 2 && i != x){
    System.out.print(i+", ");
 }

that will do both checks at the same time.

Upvotes: 0

BateTech
BateTech

Reputation: 6506

Change your for loop to:

for (int i = 1; i <= x; i++){
    System.out.println(i * 2 - 1);
}

or an alternative:

for (int i = 1; i < x * 2; i = i + 2){
        System.out.println(i);
}

Upvotes: 0

Dave
Dave

Reputation: 144

This is most efficient (based on the unusual requirements):

var oddNumber = 1;
for (int i=0; i<x; i++) {
     System.out.println(oddNumber);
     oddNumber += 2;
}

Upvotes: 3

Peshal
Peshal

Reputation: 1518

Something like this should work:

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println("Please input a number.");
        Scanner keyboard = new Scanner(System.in);
        int x = keyboard.nextInt();
        for(int i =1; i<=x*2; i++) {
            if (i%2!=0) {
                System.out.print(i+", ");
            }
        }
        keyboard.close();
}

Upvotes: 1

mamboking
mamboking

Reputation: 4637

For you loop you should use:

for (int i=0; i<x; i++) {
    System.out.println((i*2)+1);
}

Upvotes: 0

newuser
newuser

Reputation: 8466

int total = x*2;

instead of

int total = x*x;

Upvotes: 0

Related Questions