I want to make an array of int with size 500 and fill this in with;

  • 0,1,2,...,499
  • 1,2,3,...,500
  • 500,499,498,...,1

    public static void main(String[] args) { int[] numbers = new int[500]; for(int i=0; i<500; i++) { System.out.println(numbers[i]); } 

I know I need to do this with a for loop but I can't get the right code yet. Can anybody help me please?

3

3 Answers

You need to assign a value to each array-element

int[] numbers = new int[500]; for(int i=0; i<500; i++) { numbers[i] = i; System.out.println(numbers[i]); } int[] numbers2 = new int[500]; for(int i=500; i>0; i--) { numbers2[i-1] = i; System.out.println(numbers2[i-1]); } 
1

You can use a for loop for each case.

for(int i=0; i<500; i++) { numbers[i] = i;//0,1,2,...,499 } int j = 0; for(int i=500; i > 0; i--) { numbers[j++] = i;//500,499,498,...,1 } for(int i=1; i<=500; i++) { numbers[i-1] = i;//1,2,3,...,500 } 

You can fill both in single for loop

 int[] numbers = new int[500]; int[] numbers2 = new int[500]; for(int i=0; i<500; i++) { numbers[i] = i + 1; numbers2[i] = 500 - i; } 

and just for printing purpose

 for(int i=0; i<500; i++) { System.out.print(numbers[i]+" "); } System.out.println(); for(int i=0; i<500; i++) { System.out.print(numbers2[i]+" "); } 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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