Reputation: 171
So I am fairly new to Kotlin and I need to generate specific numbers from a for loop of 1 to 13.
For the first output I need only odd numbers
For the second output I need numbers 2, 5, 8, 11, 14, 19 and 20 from a for loop of 0 to 20
For starters I can print an entire list using:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
for (i in 1..13){
println(i)
}
}
}
But that's it. What do I need to print the other required outputs?
Upvotes: 1
Views: 2594
Reputation: 2733
To generate Odd numbers:
for (i in 1..13) {
if(i % 2 == 1 ){
println(i + ", ");
}
}
To Generate 2, 5, 8, 11, 14, 19 and 20:
for (i in 0..20) {
if (i % 3 == 2) {
println(i + ", ");
}
}
Upvotes: 0
Reputation: 54204
Once you know how to write a for
loop that prints every number, the question becomes how to identify a number that you "should" print from a number that you should not.
Your first sequence is all odd numbers, so @DipankarBaghel's answer covers that. Your second sequence seems to be all numbers for which the remainder when dividing by 3 is 2. (Except 19; did you mean 17 for that one?)
You can use the same operator in this case, but instead of checking for 0
(or for != 0
) you can check that the remainder is 2
:
for (i in 0..20) {
if (i % 3 == 2) {
println(i)
}
}
The key concept here is that of %
, the remainder operator (sometimes called the modulo operator). The result of x % y
will be the remainder when x
is divided by y
. Odd numbers have a remainder of 1
when divided by 2
, so i % 2 == 1
will be true only for (positive) odd numbers.
Upvotes: 1
Reputation: 2039
To check even you need to do i%2==0
and for odd just check i%2!=0
.
for (i in 1..13){
if(i%2!=0){
println("odd number "+i);
}
if(i%2==0){
println("even number "+i);
}
}
Hope this will help you.
Upvotes: 0