There is a Java task:
Print those array elements whose indices are full squares (1, 4, 9, 16, ...).

I can not understand the task. Explain what kind of cycle and condition is needed?

public static void main(String[] args) { // TODO Auto-generated method stub int f[] =new int [10]; for (int i=0; i<f.length; i++) { f[i]= (int) (Math.random()*(10-0)+1)+0); } for (int i=0; i<f.length;i++) { System.out.print(f[i]+""); } } } 
  • You can not understand the wording, or how to write the code - decide ... - Vladimir Martyanov
  • If the root of a number gives an integer, and not something with the remainder, then it is needed - Alexey Shimansky
  • How to write program code. I apologize for the inaccuracies and illiteracy. - Ivan Ivanov

2 answers 2

A series of full squares of 1, 4, 9, 16, ... is beautiful because the difference of neighboring numbers in it is a sequence of odd numbers 3, 5, 7, ... On this, you can build a solution without using multiplication, using only addition operations:

 int i = 1, d = 3; while (i < array.length) { System.out.println(array[i]); i += d; d += 2; } 

If you need to start from scratch, the variable initialization string will change to the following:

 int i = 0, d = 1; 

PS: Using the for loop, you can write about the same code as follows (starting from zero):

 for (int i = 0, d = -1; i < array.length; i += d += 2) { System.out.println(array[i]); } 
  • just wondering. Why while? Why not for? - pavel
  • @pavel can be made and for , as it is convenient :) - Alex Chermenin
  • When starting the program on the console: 000 (zeros). - Ivan Ivanov
  • one
    @IvanIvanov, did you write anything to the array? - m. vokhm

On pseudo-language will be so

 var index = 0; while (index * index < array.length) { print(array[index*index]); index ++; } 

A full square is a natural number, the root of which is also a natural number.

This means that the square of any natural number is a complete square. The above code is based on this - short, cheap and cheerful :)

The above code is the smallest source for your task (I think). Well, except that 0 is not a complete square and an index, but then simply assign it to the index at the beginning of 1.

  • one
    well, by the way, 0 is a complete square ... Purely formal. - pavel