Missing element of AP

QUESTION

Find the missing element from an ordered array A[ ], consisting of N elements representing an Arithmetic Progression (AP) .\n \n\nInput:\nThe first line of input contains an integer T denoting the number of test cases. Then T test cases follow. \nThe first line of each test case contains an integer N, where N is the size of the array A[ ].\nThe second line of each test case contains N space separated integers of an Arithmetic Progression denoting elements of the array A[ ].\n \n\nNote: The series should have a missing element in between a perfect A.P. with no missing element will not be considered.\n \n\nOutput:\nPrint out the missing element. \n \n\nConstraints:\n1 <= T <= 100\n2 <= N <= 10\n-50 <= A[i] <=50\n

ANSWER

#include<stdio.h>
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,i;
        scanf("%d",&n);
        int a[n];
        for(i=0;i<n;i++)
            scanf("%d",&a[i]);
        if(n==2)
            printf("%d",(a[0]+a[1])/2);
        int d;
        if(n==3)
        {
            if((a[1]-a[0])<(a[2]-a[1]))
              {
                    d=a[1]-a[0];
                    printf("%d",a[1]+d);
              }
            else
               {
                   d=a[2]-a[1];
                   printf("%d",a[0]+d);
               }

        }
        else
        {
            if((a[1]-a[0])<(a[2]-a[1]))
                d=a[1]-a[0];
            else
                 d=a[2]-a[1];
            for(i=1;i<n;i++)
            {
                if((a[i]-a[i-1])!=d){
                    printf("%d",a[i-1]+d);
                    break;
                }
            }
        }
        printf("\n");
    }
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.