Reputation: 210
I need some help -
At the end of a for loop, I need to set an original value to the next multiple of the value.
This is what I have so far -
int originalNumber = 1;
for (int i = 1; i <= 10000; i++) {
originalNumber *= i;
}
However, this code will not find the multiples of 1; as the multiples of 1 should be (1, 2, 3, 4, 5, 6, ... ...)
This code that I have written will be (1, 1, 2, 6, 24) etc;
What is a good way to get the multiples (inside of the loop)?
Upvotes: 0
Views: 35461
Reputation: 36
int n = scanner.nextInt();
for (int i = 1; i <= 10; i++){
int multiple = i * n;
System.out.println(n + " x " + i + " = " + multiple);
}
You can try this code, it prints any multiple till 10;
Your Output (stdout)
2 x 1 = 2
2 x 2 = 4
...
2 x 10 = 20
Upvotes: 1
Reputation: 141
You ask for version without additional variable:
int originalNumber = 1;
for (int multiple = originalNumber; multiple <= 10000; multiple += originalNumber) {
// Use multiple however you want to
}
Upvotes: 1
Reputation: 1500155
You don't need to change originalNumber
at all - just multiply i
by originalNumber
:
int originalNumber = 1;
for (int i = 1; i <= 10000; i++) {
int multiple = originalNumber * i;
// Use multiple however you want to
}
To get all the multiples of 2, you'd set originalNumber
to 2, etc.
Upvotes: 5