George
George

Reputation: 15

For loop to produce a sequence of numbers

I am struggling with a particular sequence from a worksheet I'm working on in uni.

I am supposed to write/modify for loops to produce the following sequences:

  1. 4,5,6,7,8,9,10,11
  2. 10, 13, 16, 19
  3. 1, 4, 7, 10, 13, 16
  4. 2, 4, 6, 8, 10, 12
  5. 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
  6. -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10
  7. -20, -15, -10, -5, 5, 10, 15, 20

I've been flying through the first 4, but the 5th one is just not getting through to me.

This is what I've been doing so far. The 6th and 7th are fine, but the 5th is confusing the heck out of me.

public class Lab4_4 {
    static public void main(String args[]){

        int i;

        System.out.println("Demo Sequence");
        for(i=0;i<10;++i){
            System.out.println(i);
        }

        System.out.println("First Sequence");
        for(i=4;i<=11;++i){
            System.out.println(i);
        }

        System.out.println("Second Sequence");
        for(i=10;i<=19;++i){
            System.out.println(i);
        }

        System.out.println("Third Sequence");
        for(i=1;i<=16;i +=3){
            System.out.println(i);
        }

        System.out.println("Fourth Sequence");
        for(i=2;i<=12;i +=2){
           System.out.println(i);
        }       

    }
}

I need some enlightenment with this problem. Also, feel free to drop any advice on how I've gone though those loops :)

EDIT: I thought the 7th is just a +5 thing but it should skip 0 so it goes from -5 to 5. Not quite sure what I'm supposed to do.

Upvotes: 1

Views: 3416

Answers (3)

Bruno Zamengo
Bruno Zamengo

Reputation: 860

System.out.println("Fifth Sequence");
for(i=1;i<=10;i++){
    // System.out.println(i^2); // first but wrong answer...
    System.out.println(Math.pow(i,2));
}       

but I dare say this is a "problem-solving" question rather than a loop one ;)

Upvotes: 0

Sourav Purakayastha
Sourav Purakayastha

Reputation: 775

    System.out.println("Second Sequence");
    for (int i = 10; i <= 19; ++i) {
        System.out.println(i);
    }

    System.out.println("Third Sequence");
    for (int i = 1; i <= 16; i += 3) {
        System.out.println(i);
    }

    System.out.println("Fifth Sequence");
    for (int i = 1; i <= 10; ++i) {
        System.out.println(i * i);
    }

    System.out.println("Sixth Sequence");
    for (int i = -10; i <= 10; i = i + 2) {
        System.out.println(i);
    }

    System.out.println("Seventh Sequence");
    for (int i = -20; i <= 10; i = i + 5) {
        System.out.println(i);
    }

Upvotes: 0

Doron Yakovlev Golani
Doron Yakovlev Golani

Reputation: 5470

for(i=1;i<=10;i++){
    System.out.println(i*i);
}   

Upvotes: 2

Related Questions