ITDeveloper : Java Programs of Class 12
Java Programs
Step by Step Tutorials
![]() Share with a Friend |
Pseudo Arithmetic Sequence Program - ISC 2011 Theory
You are given a sequence of N integers, which are called as pseudo arithmetic sequences (sequences that are in arithmetic progression).
Sequence of N integers: 2, 5, 6, 8, 9, 12.
We observe that 2 + 12 = 5 + 9 = 6 + 8 = 14.
The sum of the above sequence can be calculated as 14 × 3 = 42.
For sequence containing an odd number of elements, the rule is to double the middle element, for example 2, 5, 7, 9, 12.
2 + 12 = 5 + 9 = 7 + 7 = 14.
14 × 3 = 42 (middle element = 7)
A class PseudoArithmetic determines whether a given sequence is a pseudo-arithmetic sequence.
The details of the class are given below:
Class name: PseudoArithmetic
Data members/instance variables:
n: to store the size of the sequence.
a[ ]: integer array to store the sequence of numbers.
ans, flag: store the status
sum: store the sum of sequence of numbers.
r: store the sum of the two numbers.
PseudoArithmetic(): default constructor.
void accept(int num): to assign num to n and to create an integer array. Fill in the elements of the array.
boolean check(): return true if the sequence is a pseudo-arithmetic sequence otherwise returns false.
Specify the class PseudoArithmetic, giving details of the constructor, void accept(int) and boolean check(). Also define a main() function to create an object and call the member functions accordingly to enable the task.
import java.io.*;
class PseudoArithmetic{
private int n;
private int a[];
private boolean flag;
private boolean ans;
private int sum;
private int r;
public PseudoArithmetic(){
n = 0;
flag = true;
ans = false;
sum = 0;
r = 0;
}
public void accept(int num)throws IOException{
n = num;
a = new int[n];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter array elements:");
for(int i = 0; i < n; i++)
a[i] = Integer.parseInt(br.readLine());
}
public boolean check(){
int i = 0;
int j = n - 1;
r = a[i] + a[j];
int count = 0;
do{
int temp = a[i] + a[j];
if(temp != r){
flag = false;
break;
}
if(i == j)
sum += a[i] * 2;
else
sum += a[i] + a[j];
i++;
j--;
count++;
}while(i <= j);
ans = (sum == r * count);
return (flag && ans);
}
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("N = ");
int num = Integer.parseInt(br.readLine());
PseudoArithmetic obj = new PseudoArithmetic();
obj.accept(num);
if(obj.check())
System.out.println("Pseuso arithmetic sequence.");
else
System.out.println("Not a pseudo arithmetic sequence.");
}
}
