Click here to Skip to main content
15,886,857 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
an integer array Arr of size N and a number X.print all the indexes of the given X in the array, else print -1.

give output in 1-based indexing.

Input

5 6
2 6 3 6 6
Output:

2 4 5

What I have tried:

solution

int flag =0;
		int index =-1;
    for(int i=0; i<N; i++){
			if(arr[i]==X){
				flag =1;
				index = i+1;
			
			if(flag==1){
			 System.out.print(index + " ");
				
			}
			else{
				System.out.print("-1");
			   
			}
				}
Posted
Updated 20-Dec-22 7:22am

You never clear the status of your flag: once set, it stays set for teh duration of your application ... Since your printing is all inside your loop, that could be important, wouldn't you say?

If you had used the debugger, a couple of minutes would have shown you what was wrong with your code: that would have been a lot quicker than asking here!
How you use it depends on your compiler system, but a quick Google for the name of your IDE and "debugger" should give you the info you need. Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.
 
Share this answer
 
Comments
CPallini 20-Dec-22 8:25am    
5.
This is your third question today, I think it is time you went to Java Tutorials Learning Paths[^] and did some studying.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900