c code

  • c
  • given unsorted dynamic array of size n , find and display the number of elements between two elements a and b.

    Given an unsorted dynamic array of size n, WAP to find and display the number of elements between two elements a and b (both inclusive). E.g. Input : arr = [1, 2, 2, 7, 5, 4], a=2 and b=5, Output : 4 and the numbers are: 2, 2, 5, 4

    Code

    #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> void printarray(int *arr, int n) { for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); } int maximum(int *arr, int n) { int max = INT_MIN; for (int i = 0; i < n; i++) { if (arr[i] > max) { max = arr[i]; } } return max; } void countsort(int *arr, int n) { int max = maximum(arr, n); int *count = (int *)calloc(max, sizeof(int)); for (int i = 0; i < n; i++) { count[arr[i]] = count[arr[i]] + 1; } int i = 0, j = 0; while (i <= max) { if (count[i] > 0) { arr[j] = i; count[i]--; j++; } else { i++; } } } void range(int *arr, int a, int b, int n) { int y=0; for (int i = 0; i < n; i++) { if(arr[i]>=a && arr[i]<=b){ y++; } } printf("numbers are: %d\n",y); int x[y],j=0; for (int i = 0; i < n; i++) { if(arr[i]>=a && arr[i]<=b){ x[j]= arr[i]; j++; } } printarray(x,y); } int main() { int n, a, b; printf("enter the total elements of array\n"); scanf("%d", &n); int *arr = (int *)malloc(n * (sizeof(int))); for (int i; i < n; i++) { printf("enter the element %d :\n", i + 1); scanf("%d",&arr[i]); } printarray(arr, n); countsort(arr, n); printarray(arr, n); printf("enter the element between u want to find\n"); scanf("%d",&a); scanf("%d",&b); range(arr, a, b, n); return 0; }