Search code examples
carraysrepeatlinear-search

Repeat the Program for again Search Array Element


Repeat the Program for again Search Array Element.

 #include <stdio.h>
#define MAX_SIZE 100  

  int main()
  {
    int arr[MAX_SIZE];
    int size, i, toSearch, found;
    char repeat;

    printf("Enter the size of an array\n");
    scanf("%d", &size);
    printf("Enter the array elements\n");
    for (i = 0; i < size; i++) 
    {
      scanf("%d", &arr[i]);
    }
do{
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
found = 0; 

 for(i=0; i<size; i++)
  {
      if(arr[i] == toSearch)
      {
          found = 1;
          break;
     }
 }
 
  if(found == 1)
  {
      printf("\n%d is found at position %d", toSearch, i + 1);
  }
 else
  {
      printf("\n%d is not found in the array \n", toSearch);
  }
  printf("\n \n \nPress Y to again Search Any Element in Array\n \nPress Any other Key to Exit the Program\n\n");
scanf(" %c \t",&repeat);
}
while(repeat == 'y' || repeat == 'Y' );
return 0;

}

I want to repeat my program when user give the input of Y || y otherwise it'll exit the program. In this code i want to make an array then search the element after this show's the results and in last repeat the code from the search the element block.


Solution

  • I ran your code and everything seems to be working properly except for this line:

    scanf(" %c \t",&repeat);
    

    Remove the \t from the scanf and it should work properly. You don't want to scan for a tab character, just the 'Y' or 'y' character.

    Also, your use of newlines is a bit unusual. Try putting newline characters at the end of your strings as opposed to the beginning.

    Updated code:

    #include <stdio.h>
    #define MAX_SIZE 100  
    
    int main() {
      int arr[MAX_SIZE];
      int size, i, toSearch, found;
      char repeat = ' ';
    
      printf("Enter the size of an array\n");
      scanf("%d", &size);
      printf("Enter the array elements\n");
      for (i = 0; i < size; i++) 
        scanf("%d", &arr[i]);
        
      do{
        printf("Enter element to search: \n");
        scanf("%d", &toSearch);
        found = 0; 
    
        for(i=0; i<size; i++) {
          if(arr[i] == toSearch) {
            found = 1;
            break;
          }
        }
        
        if(found == 1)
          printf("%d is found at position %d\n", toSearch, i + 1);
        else printf("%d is not found in the array\n", toSearch);
        
        printf("Press Y to again Search Any Element in Array\nPress Any other Key to Exit the Program\n");
        scanf(" %c",&repeat);
      }
      while(repeat == 'y' || repeat == 'Y' );
      return 0;
    }