Reputation: 11
i am trying to print The maximum product of adjacent elements in an array but i am getting an error in my program:
if input is [2, 5, 8, 9, 6]
then desired output is : 72
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Product=0;
int len = sc.nextInt();
int[] arr = new int[len];
for(int i=0; i < len; i++){
arr[i] = sc.nextInt();
}
for(int i = 0; i<len-1; i++){
Product = arr[i]*arr[i+1];
int Nproduct = arr[i+1]*arr[i+2];
{
if(Product<Nproduct){
Product = Nproduct;
}
}
}
System.out.println(Product);
}
}
please help me where i am wrong. i am new here so please ignore my mistakes or edit if possible
Upvotes: 0
Views: 662
Reputation: 665
your code needs some changes
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Product=0;
int len = sc.nextInt();
int[] arr = new int[len];
for(int i=0; i < len; i++){
arr[i] = sc.nextInt();
}
for(int i = 0; i<len-1; i++){
if (arr[i]*arr[i+1]>Product){
Product=arr[i]*arr[i+1];
}
}
System.out.println(Product);
}
}
for reference click here : GFG Problem
Upvotes: 0
Reputation: 347
There is some logical error as well as Run time error in your code.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Product=0;
int len = sc.nextInt();
int[] arr = new int[len];
for(int i=0; i < len; i++){
arr[i] = sc.nextInt();
}
for(int i = 0; i<len-1; i++){
if (arr[i]*arr[i+1]>Product){
Product=arr[i]*arr[i+1]; // update Product only if we get greater product
}
}
System.out.println(Product);
}
}
Upvotes: 3
Reputation: 2222
Change second loop for (int i = 0; i<len-1; i++)
to for (int i = 0; i<len-2; i++)
to prevent running out of upper array's bound
Upvotes: 1