Reputation: 21
I have an array with 5 elements (1024,1025,1026,1027,1028).How can I check these elements are in sequential or not.I could do the same if array has even number of elements.
Upvotes: 2
Views: 348
Reputation: 490453
Loop through the array and ensure the previous member (if it exists) is equal to the current minus 1
.
for (int i = 1; i < 5; i++) {
if (arr[i - 1] != arr[i] - 1) {
// It's not sequential.
break;
}
}
Upvotes: 2
Reputation: 11277
I would suggest this solution (if by saying sequential
you mean just ordered
):
#include <stdio.h>
int isArraySequential(int * array, int size) {
int isAscendingFirst;
int isAscendingCurrent;
int isChangeFound = 0;
int i;
// arrays of length 0/1/2 are assumed to be sequential
if (size < 3)
return 1;
for (i=1; i < size; i++) {
// in case there is a change
if (array[i] != array[i-1]) {
isAscendingCurrent = (array[i] > array[i-1]);
// on first change
if (!isChangeFound) {
isChangeFound = 1;
isAscendingFirst = isAscendingCurrent;
}
// on subsequent changes
else {
if (isAscendingFirst != isAscendingCurrent)
return 0;
}
}
}
return 1;
}
int main(){
int array1[4] = {1, 1, 0, -1};
int array2[4] = {2, 2, 2, 2};
int array3[4] = {1, 2, 4, 3};
printf("Is array1 sequential ? %d\n", isArraySequential(array1, 4));
printf("Is array2 sequential ? %d\n", isArraySequential(array2, 4));
printf("Is array3 sequential ? %d\n", isArraySequential(array3, 4));
return 0;
}
because in general sequential array can be in ascending
OR descending
order and this must be taken into account. Also there are corner cases - arrays of length 0/1/2 are always sequential (i am not sure about length 0).
EDIT: I've fixed code for situation when first array elements are with same values. Now it should work OK.
Upvotes: 0
Reputation: 69
You should compare the two neighboring numbers and you have to do the same thing for many times. So, a loop is necessary. An easy programme is as followed.
#include<stdio.h>
int main()
{
int a[5]={1024,1025,1026,1027,1028};
int i,s;
for(i=0;i<4;i=i+1)
{
if(a[i]+1 != a[i+1])
{ s=-1; break; }
else
{ s=0; }
}
if(s=0)
{ printf("sequential."); }
else
{ printf("not sequential."); }
}
I hope that my answer could help you. Thank you.
Upvotes: 0
Reputation: 1598
Simply iterate through the array:
bool is_sequence(int *arr, int size)
{
int i;
for(i = 0; i < (size - 1); i++)
{
if((arr[i] + 1) != arr[i])
/* array is not sequential */
return false;
}
/* array is sequential */
return true;
}
<...>
if(is_sequence(my_array, 5))
printf("sequential!"
else
printf("not sequential");
Upvotes: 0