Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reverse array code did not work #6

Open
subhanssingh opened this issue Feb 8, 2022 · 5 comments
Open

reverse array code did not work #6

subhanssingh opened this issue Feb 8, 2022 · 5 comments

Comments

@subhanssingh
Copy link

In for loop of reversing array there should be i-- not i++.

@arpitverma123
Copy link

that's right

@kuleen179
Copy link

In for loop of reversing array there should be i-- not i++.

Try this..

reverseofArray.txt

@kumarikajal05
Copy link

That's right, Here's what the code does:

The code declares a new integer array 'a' with some initial values {1, 2, 3, 4, 5, 6, 7, 8}.

It declares a new integer array 'b' with the same length as array 'a'.

It uses 'a' for loop to iterate through array 'a' from the end to the beginning. During each iteration, it assigns the current value of 'a[i]' to the corresponding position in array 'b', starting from the beginning.

Finally, it uses a for-each loop to print out each element in array 'b' in the reversed order.

So the output of the program would be:' 8 7 6 5 4 3 2 1'.

@pankaj-254
Copy link

pankaj-254 commented Aug 26, 2023

try this

public class MyClass {
public static void main(String args[]) {

     int x[]={1, 2, 3, 4, 5, 6, 7, 8};
//not reverse this array x
//first create a array of same length as 'x'
     int y[]=new int[x.length];
//now traverse all the elements of x and assign to y in reverse manner
 for(int i=0;i<x.length;i++)
 {
     //here we are assigning element of y in reverse manner
     y[i]=x[x.length-i-1];
 }
    
    for(int X:y) 
    {
      System.out.print(X+",");
    }
        
        
}

}

@Afzal14786
Copy link

it is also possible to reverse the same array using constant space with O(n) time complexity .//

class Main {
    public static void main(String[] args) {
        int[] array = {1,2,3,4,5};
        
        **// it just return the array in reverse manner without any extra space or any temp array //**
        for (int i = array.length-1; i>=0; i--) {
            System.out.print(array[i] +" ");
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants