arithmetic sequence ?

hello i'm making a program that finds an arithmetic sequence (for example 5,7,9,11,13,...) in some numbers but my if clause is way too long so i was wondering if someone knows a easier way to solve this. also if i alter the size the if clause isn't completely correct anymore so i need some kind of loop that solves this to

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
string suffix(int a) {
	string suffix="th";
	if (a==1) {
		suffix="st";
	} else if (a==2) {
		suffix="nd";
	} else if (a==3) {
		suffix="rd";
	} 
	return suffix;
}

string arithmetic(int* n,int size) {
	string seq="";
	if (n[size-1]-n[size-2]==n[size-2]-n[size-3]&&n[size-1]-n[size-2]==n[size-3]-n[size-4]&&n[size-1]-n[size-2]==n[size-4]-n[size-5])
//this is way to long in my opinion
 {
		seq="ok";
		return seq;
	} else {
		return seq;
	}

}

int main()
{
	string seq="";
	int size = 5;
	int* n = new int[size];
  for (int i=1;i<=size;i++) {
	  cout << "please enter the "<< i<<suffix(i)<<" number"<<endl;
	  cin >> n[i-1];
  }
  seq=arithmetic(n,size);
  cout<<seq<<endl;
  system("pause");
  return 0;
}
Last edited on
not tested

1
2
3
4
5
6
7
8
9
10
11
12
13
string arithmetic(int* n,int size) 
{
	string seq="ok";
	for(int i=1;i < size -1 ;i++)
	{
		if( n[i+1] - n[i] != n[1] - n[0])
		{
			seq="";
			break;
		}
	}
	return seq;
}
Last edited on
thanks and it works
Last edited on
Topic archived. No new replies allowed.