1

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes I mean't 17 for that one, or atleast that's the number I was instructed to generate. Other than that thanks!
Actually wait it is supposed to be 17, not 19. Sorry for the confusion.
0

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.

1 Comment

@Preston If the answer helps you request you to mark the answer as accepted so that it will helps others too. thanks
0

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 + ", ");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.