• This topic is empty.
Viewing 1 post (of 1 total)
  • Author
    Posts
  • #251
    admin
    Keymaster
      
      
      #include<stdio.h>
      #include<cs50.h>
      #include<string.h>
      int main(void)//to search 'a' from a string
      {
      string t = get_string("enter");
      int m = strlen(t);
      printf("number of words %i",m);
      int i = 0;
          for(t = 0; t < m; t++)
          {
              if(t == 'a')
              {
              printf("found");
              }
          }
      }

      Help/clue appreciated why the above program fails to find ‘a’.

      r/cs50 - Help for code conducting a linear search

      On trying with debugger50, it appears that the value of i not incremented. Even I tried with a sample string with first character a. But that too did not succeed in spotting ‘a’.

      r/cs50 - Help for code conducting a linear search


      Reply


      Looking at the code ? The first obvious bug I could see has to do with the condition of your for loop. In other to loop through the string you have to start from 0 to Len of string minus one . Thus (int i = 0 ; I< m ; i++)

      Then you can check in the loop if t = “a”


      string, here you’re including the string (arrays of character) into the loop when you’re not supposed to. So it’s:

      1. For (int i =0; i<strlen(t) or m; i++) { If ( t == “a”) { Printf(“found\n”) }

      }

      On line one you’re creating an integer i that will start counting at 0 until the strlen of t (length of the t string). Line 3 is asking each time if the “i th” character of that string is equal to the letter a. So it starts with is the zero th character an a if not go to the top of the loop and start with 1. Else if it is print found.

      [learn_press_profile]

    Viewing 1 post (of 1 total)
    • You must be logged in to reply to this topic.
    Scroll to Top