Home > front end >  Search number in array C
Search number in array C

Time:07-15

For some reason, the option does not work for me when I enter a number that is not in the array. And at the same time, how can I do it when, for example, I enter

Enter the 1st element (-1 for the end of the entry): 1
Enter the 1st element (-1 for the end of the entry): 3
Enter the 1st element (-1 for the end of the entry): 4
Enter the 1st element (-1 for the end of the entry): 6
Enter the 1st element (-1 for the end of the entry): 3
Enter the 1st element (-1 for the end of the entry): -1

and when I enter to search for the position of the number 3, they print the last position, that is, that the number 3 is in the 5th position, and not in the 2nd position

 #include <stdio.h>
int main() {
 
 double a[100];
 int n;
 int i,element,pos=0;
 for(i=0;i<n;i  )
 {
 printf("Enter %d. element (-1 for end): ",i 1);
 scanf("%lf",&a[i]);
 
 if(a[i]==-1) break;
}
printf("Enter number for search: ");
   scanf("%d",&element);

   for(i=0; i<n; i  )
   {
     if(a[i]==element)
     {
       printf("The number %d was entered as %d number per line.", element, i 1);
       return 0;
     }
   }

   printf("%d not found.", element);
   return 0;
}

CodePudding user response:

  • You invoked undefined behavior by using the value of uninitialized non-static local variable n in the loop conditions i<n. You should use the number of elements of the array instead of n in the first loop, and set n to i after the first loop.
  • To find the last occurance of a number, you should search from the last element of the array.
  • It should be natural to use double for element because the elements of the array a are double.
  • You should check the return values of scanf() to see if it successfully read what is expected for safety.

Fixed code:

#include <stdio.h>
#define MAX 100
int main() {

  double a[MAX],element;
  int n;
  int i,pos=0;
  for(i=0;i<MAX;i  )
  {
    printf("Enter %d. element (-1 for end): ",i 1);
    if(scanf("%lf",&a[i])!=1)
    {
      fputs("read error\n", stderr);
      return 1;
    }

    if(a[i]==-1) break;
  }
  n=i;
  printf("Enter number for search: ");
  if(scanf("%lf",&element)!=1)
  {
    fputs("read error\n", stderr);
    return 1;
  }

  for(i=n-1; i>=0; i--)
  {
    if(a[i]==element)
    {
      printf("The number %g was entered as %d number per line.", element, i 1);
      return 0;
    }
  }

  printf("%g not found.", element);
  return 0;
}
  • Related