Create a certain number sequence, storing it in ArrayList

-5

I need to develop a Java algorithm that returns the following sequence:

  

9, 16, 25, 36, 49 ...

I have already identified that the default is as follows:

9 = 3²
16 = 4²
25 = 5²
36 = 6²

Values must be stored in ArrayList and be displayed at the end.

    
asked by anonymous 02.04.2016 / 22:24

1 answer

2

Try this:

    int valorInicial = 3;
    int n = 7;
    ArrayList<Integer> lista = new ArrayList<>();
    // usando math
    for(int i = valorInicial; i <= n; i++){
        lista.add((int)Math.pow(i,2));
    }

    for(Integer num : lista){
        System.out.print(num + " ");
    }

or without using the Math class:

    int valorInicial = 3;
    int n = 7;
    ArrayList<Integer> lista = new ArrayList<>();
    //sem usar math
    for(int i = valorInicial; i <= n; i++){
        lista.add(i*i);
    }

    for(Integer num : lista){
        System.out.print(num + " ");
    }

In this ideone link, you can see the result (which will be the same) of the two working methods.

    
02.04.2016 / 23:00