How to print specific numbers from a for loop using Kotlin

Preston :

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?

Ben P. :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=175200&siteId=1