Reputation: 25
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
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
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
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
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
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
Reputation: 4637
For you loop you should use:
for (int i=0; i<x; i++) {
System.out.println((i*2)+1);
}
Upvotes: 0