Home > Net >  Number of elements in between two elements (Both Inclusive)
Number of elements in between two elements (Both Inclusive)

Time:07-28

Given an unsorted array of size n, write a program to find number of elements between two user-defined elements a and b (where a and b both are inclusive) of a user-defined array. Input : arr = [1, 2, 2, 7, 5, 4] a=2 b=5 Output : 4

Here is my code. What is wrong with this code. Can you please explain me my mistake and explain the logic?

**#include <stdio.h>
int main()
{
    int a[100],n,i,m,b,count=0;
    printf("Enter the number of elements you want to enter in any array:");
    scanf("%d",&n);

    printf("Enter the elements you want to enter in the array:\n");

    for(i=0;i<n;i  )
    {
        scanf("%d",&a[i]);
    }
    
    printf("Array:\n");

    for(i=0;i<n;i  )
    {
        printf("%d\t",a[i]);
    }
    
   printf("\nEnter lower limit element & upper limit element respectively: ");
   scanf("%d %d",&m,&b);
    
   for(i=0;i<n;i  )
    { 
         if(a[i]==m || a[i]==b)
         {
            count  ;
         }
        if(a[i]>m && a[i]<b)
        {
            count  ;
        }
    }

    printf("Number of elements in between two elements (Both Inclusive) = %d",count);
    return 0;
}**

CodePudding user response:

Think about the challenge. Rather than trying to count, simply find the index of each target and calculate the difference between them.

int loInd = -1, hiInd = -1;

for( i = 0; i < n; i   ) { 
    if( a[ i ] == m && loInd < 0 )
        loInd = i;
    if( a[ i ] == b )
        hiInd = i;
}

if( loInd >= 0 && hiInd >= 0 )
    printf( "(Inclusive) Gap is %d\n", hiInd - loInd   1 );
else
    printf( "value(s) not found\n" );

CodePudding user response:

   for(i=0;i<n;i  )
    { 
         if(a[i]==m || a[i]==b)
         {
            count  ;
         }
        if(a[i]>m && a[i]<b)
        {
            count  ;
        }
    }

The logic of this part of code is to count the array element whose VALUE is between a and b. But i guess the subject is to count elements whose POSITION IN ARRAY between a and b.

For example a array = { 0, 2, 4, 1, 3, 5}, given a = 2, b = 3 When count value between a and b include a and b, the result should be 2,3; while count position between them, that should be 2,4,1,3 See difference?

And there are a lot redundancy of your code, you can write as:

   for(i = 0; i < n; i  )
    { 
        if(a[i] >= m && a[i] <= b)
        {
            count  ;
        }
    }

CodePudding user response:

There is no error in the logic, but you'd better use else if to make the logic judgment only execute once. Or just judge the case where no count is needed.

for (i = 0; i < n; i  ) {
    if (a[i] < m || a[i] > b) {
        continue;
    }
    count  ;
}
  • Related