This blog is under construction

Saturday, 27 July 2013

C program to check whether the given array has consecutive elements or not

Write a C program to check whether the given array has non-consecutive elements or not.


  #include <stdio.h>
  #define MAX 256

  int main() {
        int i, j, n, flag = 0, array[MAX];

        /* get the number of array entries from the user */
        printf("Enter the number of array elements:");
        scanf("%d", &n);

        /* get the array entries from the user */
        printf("Enter your array entries:\n");
        for (i = 0; i < n; i++) {
                printf("Data[%d]: ", i);
                scanf("%d", &array[i]);
        }

        /* checking whether the array entries are in descending order */
        for (i = 1; i < n; i++) {
                if (array[i - 1] > array[i]) {
                        flag = 1;
                        break;
                }
        }

        /* if flag is 0, then the given i/p array has consecutive elements */
        if (!flag) {
                printf("Given array has consecutive elements\n");
                return 0;
        }

        /* checking whether the array entries are in ascending order */
        for (i = 1; i < n; i++) {
                if (array[i - 1] < array[i]) {
                        flag = 0;
                        break;
                }
        }

        /* print the result */
        if (flag) {
                printf("Given array has consecutive elements\n");
        } else {
                printf("Given array has non-consecutive elements\n");
        }

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of array elements:7
  Enter your array entries:
  Data[0]: 10
  Data[1]: 20
  Data[2]: 30
  Data[3]: 40
  Data[4]: 50
  Data[5]: 60
  Data[6]: 70
  Given array has consecutive elements

  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of array elements:4
  Enter your array entries:
  Data[0]: 40
  Data[1]: 30
  Data[2]: 20
  Data[3]: 10
  Given array has consecutive elements

  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of array elements:5
  Enter your array entries:
  Data[0]: 10
  Data[1]: 30
  Data[2]: 20
  Data[3]: 40
  Data[4]: 50
  Given array has non-consecutive elements


No comments:

Post a Comment