Skip to main content

C Program to Search for Character in Array

Language


A program that has a function to search
per character in an array and return:
- Yes, if the character is found
- No, if the character is not found
Function provided with array with constant
data objects, constant pointer

Main program:
-To request user for character to search
-To tell user whether character found or not

  1. #include <stdio.h> /* C Standard Input and Output Library*/
  2. #define array_size 40 /* Constant size of the array to be searched*/
  3.  
  4. /*Variable declarations*/
  5. const char array_to_be_searched[array_size]="Today is a good day";
  6. char search_character;
  7. const char *pointer_search_character;
  8. int array_search_counter;
  9. char return_after_search;
  10.  
  11. /* Prototyping of functions*/
  12. char search_array_for_character(const char *pointer_search_character);
  13.  
  14. int main() /* The main method*/
  15. {
  16.  
  17. printf("Please enter the character to be searched :\n");/* Prompt to instruct use to enter the character to be searched*/
  18. scanf("%c",&search_character); /* Capture of the search character by the system*/
  19.  
  20. pointer_search_character=&search_character; /* Providing the pointer with the location(address) of the search character*/
  21.  
  22. search_array_for_character(pointer_search_character);/* Calling the function search_array_for_character and passing to it the pointer_search_character as a parameter*/
  23.  
  24. return 0;/* An indication that the program runs successfully*/
  25. } /* The end of the main method*/
  26.  
  27.  
  28. char search_array_for_character(const char *pointer_search_character)
  29. {
  30. for(array_search_counter=0;array_search_counter<array_size; array_search_counter++)
  31. {
  32. if(array_to_be_searched[array_search_counter]==*pointer_search_character)
  33. {
  34. printf("\nCharacter \"%c\" found at position %d in the phrase \"Today is a good day\"\n\n",*pointer_search_character, (array_search_counter+1), array_to_be_searched);
  35. return 0;
  36. }
  37. }
  38.  
  39. printf("\nCharacter \"%c\" not found in the phrase \"Today is a good day\"\n\n",*pointer_search_character);
  40. return 0;
  41. }
  42.  
  43.  
  44. <c>

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.