Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,924 questions

51,857 answers

573 users

How to replace every element in array by multiplication of next and previous elements with Java

1 Answer

0 votes
// arr[first] = arr[first] (itself) * arr[next];
// arr[last] = prev * arr[last] (itself);

public class MyClass {
    private static void MultiplyNextPrevious(int[] arr) {
    	int size = arr.length;
    	
    	if (size <= 1) {
    		return;
    	}
    
    	int prev = arr[0];
    
    	arr[0] = arr[0] * arr[1];
    
    	for (int i = 1; i < size - 1; i++) {
    		int curr = arr[i];
    
    		arr[i] = prev * arr[i + 1]; // arr[i + 1] = next
    
    		prev = curr;
    	}
    
    	arr[size - 1] = prev * arr[size - 1];
    }

    public static void main(String args[]) {
        int[] arr = {2, 3, 5, 6, 12, 8, 10, 7};

	    MultiplyNextPrevious(arr);

	    for (int i = 0; i < arr.length; i++){
		    System.out.print(arr[i] + " ");
	    }
    }
}




/*
run:
 
6 10 18 60 48 120 56 70 
 
*/

 



answered Oct 2, 2022 by avibootz
...