0

Hwo can help me in java ? Lenght of even numbers

public class Program { public static void main(String[] args) { for(int x=0; x<=10; x=x+2) { int[] aa = new int[x]; System.out.print(aa.length + " "); } } } // I cant have a length of even numbers

4th Nov 2020, 9:44 PM
Раз Мхитарян
Раз Мхитарян - avatar
6 Answers
+ 5
Ohh.. so you wanna count how many even numbers are present in the array. Edit: Modified according to your need. Although here count actually counts how many time the loop has been executed. The array is not necessary. https://code.sololearn.com/c16B3pn3k8dN/?ref=app . . Explanation to why your code isn't giving your desired output.. for(int x=0; x<=10; x=x+2) { int[] aa = new int[x]; System.out.print(aa.length + " "); } 1st iteration x = 0 int[] aa = new int[0] <- length of array 0 _______________ 2nd iteration x = 0+2 int[] aa = new int[2] <- length of array 2 _______________ 3rd iteration x = 2 +2 int[] aa = new int[4] <- length of array 4 ------------------ 4th iteration x = 4 + 2 int[] aa = new int[6] <- length of array 6 ------------------ 5th iteration x = 6 + 2 int[] aa = new int[8] <- length of array 8 ------------------ 6th iteration x = 8+2 int[] aa = new int[10] <- length of array 10 ------------------ That's how it prints 0 2 4 6 8 10 :)
5th Nov 2020, 6:09 AM
Minho
Minho - avatar
+ 5
What do you expect the output to be?
4th Nov 2020, 10:17 PM
_cm_
+ 4
eli Please don't provide any code snippets that you haven't tested before. Your code snippet will result in a compile error because int[] arr doesn’t get initialized. In order to make it compile, you would have to change the second line to: int[] arr = new int[6];
5th Nov 2020, 3:26 AM
_cm_
+ 2
Thankh you Minho , but i have a question , can you do this by another version , see I want to compile the even numbers in one array , and print array length , can you do same?
5th Nov 2020, 6:13 AM
Раз Мхитарян
Раз Мхитарян - avatar
+ 1
Expected result must be 6 ; because the even numbers are 0,2,4,6,8,10, length of this numbers are 6
5th Nov 2020, 6:04 AM
Раз Мхитарян
Раз Мхитарян - avatar
0
int i=0; int arr[]=new int [10]; for(int x=0; x<=10; x+=2, i++){ arr[i]=x; } //print i or length of arr I think it would be working but i not check this:)
5th Nov 2020, 1:42 AM
eli
eli - avatar