Write a program in Java to show whether a given sequence is an Arithmetic Progression or not
Answers
Answer:
// Java program to check if a given array
// can form arithmetic progression
import java.util.Arrays;
class GFG {
// Returns true if a permutation of
// arr[0..n-1] can form arithmetic
// progression
static boolean checkIsAP(int arr[], int n)
{
if (n == 1)
return true;
// Sort array
Arrays.sort(arr);
// After sorting, difference between
// consecutive elements must be same.
int d = arr[1] - arr[0];
for (int i = 2; i < n; i++)
if (arr[i] - arr[i-1] != d)
return false;
return true;
}
//driver code
public static void main (String[] args)
{
int arr[] = { 20, 15, 5, 0, 10 };
int n = arr.length;
if(checkIsAP(arr, n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Anant Agarwal.
Explanation:
Answer:
import java.util.*;
class TestAP
{
static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no of elements of the series..");
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
System.out.print("["+i+"]>>");
a[i]=sc.nextInt();
}
for(int i=1;i<n;i++)
{
if(a[i-1]>a[i])
{
int temp=a[i-1];
a[i-1]=a[i];
a[i]=temp;
i=0;
}
}
int d=a[1]-a[0];
boolean x=true;
for(int i=1;i<n;i++)
{
int r=a[i]-a[i-1];
x=(d==r)?true:false;
}
if(x==true)
System.out.println("Given series are in AP");
else
System.out.println("Given series are not in AP");
}
}
Explanation:
Hope it helps you..Please mark this answer as the brainliest.
10 thanks + follow = inbox ✌✌