If we are doing without recursion, the array is printing 0

public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = { 10, 20, 30, 10, 30, 10, 30, 40, 50 };
System.out.println(“enter the number”);
Scanner scn = new Scanner(System.in);
int data = scn.nextInt();
int i = 0;
int counter = 0;
while (i < a.length) {
if (a[i] == data)
{
counter = counter + 1;
}
i++;
// first i found out the array length
}
System.out.println(counter);
int[] array = null;// declared new array
array = new int[counter];
while(i<a.length) {
if(a[i]==data) {
for(int j =0;j<counter;j++) {
array[j] = i;
}
}
i++;
}
for( i=0;i<counter;i++) {
System.out.println(array[i]);
}

}

}

array = new int[counter];
while(i<a.length) {
if(a[i]==data) {
for(int j =0;j<counter;j++) {
array[j] = i;
}
}

here you are reusing the variable i , so its already starting from a.length due to the previous loop
form a new variable for this loop

but when changed it is printing the last index only

public static void main(String[] args) { 		// TODO Auto-generated method stub 		int a[] = { 10, 20, 30, 10, 30, 10, 30, 40, 50 }; 		System.out.println("enter the number"); 		Scanner scn = new Scanner(System.in); 		int data = scn.nextInt(); 		int i = 0; 		int counter = 0; 		while (i < a.length) { 			if (a[i] == data) 			{ 				counter = counter + 1; 			} 			i++; 			// first i found out the array length 		} 		System.out.println(counter); 		int[] array = null;// declared new array  		array = new int[counter]; 		int k =0; 		while(k<a.length) { 	if(a[k]==data) { 		for(int j =0;j<counter;j++) { 			array[j] = k; 		} 	}	 	k++; 		} 		for( k=0;k<counter;k++) { 			System.out.println(array[k]); 		}  	} }

bro please share your code after saving it on ide.codingblocks.com
how will i read/edit the code like this?

i have saved in the name of allindices.java

when you save a code ur url gets updated .copy that and share here

only increment j when u get data= a[k]


if this solves your doubt please mark it as resolved :slight_smile: