• This topic is empty.
Viewing 1 post (of 1 total)
  • Author
    Posts
  • #253
    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");
              }
          }
      }

       

      Instead of

      for (int i = 0; i < m; i++),

      if the same set

      for(t = 0; t < m; t++)

      the program is compiling successfully but not giving desired output. Apparently, both seem to perform the same action.


      Reply


      for(t = 0; i < m; i++) , the index has to checked with the length of the string and increment till it reaches the end. The above compares the content of the string at the index ‘i’ not the value of index ‘i’ with the length of the string.


      This appears to be trying to say “for every t-sub-i in the range zero to m”.

      This is all fine in terms of normal pure math notation, but it doesn’t work in program code. You have to think about a point in time, as the program executes line by line.

      The steps involved in looping here are something like

      1. set i=0

      2. if i >= m then terminate the loop

      3. examine t, using the current value of i

      4. increment i

      5. go back to step 2

      Another way to think about it is that the thing that is being operated on by the loop is “i”, and inside the loop’s code block you use that to access t


      i variable will be always 0, and t in this code will always look at t[0], so only number under t[0] will be changed.

      That being said, it will always look at first letter in string.

      Just use normal for loop because I don’t see any sense in doing array here. It might be actually nice trick for not doing nested loop, but it can’t be implemented like this.


      https://edstem.org/us/courses/176/discussion/1246940

       

       [learn_press_profile]

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