IT, Programming, & Web Development › Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 3: [Algorithms] – Linear Search, Binary Search, Bubble Sort, Selection Sort, Recursion, Merge Sort › What is wrong with this for loop with array as counter
Tagged: arrays, linear search, loop
- This topic is empty.
-
AuthorPosts
-
March 7, 2022 at 1:53 pm #253
[dm_code_snippet background=”yes” background-mobile=”no” slim=”yes” line-numbers=”yes” bg-color=”#abb8c3″ theme=”dark” language=”clike” wrapped=”yes” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
#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[i] = 0; t[i] < m; t[i]++) { if(t[i] == 'a') { printf("found"); } } }
[/dm_code_snippet]
Instead of
for (int i = 0; i < m; i++),
if the same set
for(t[i] = 0; t[i] < m; t[i]++)
the program is compiling successfully but not giving desired output. Apparently, both seem to perform the same action.
Reply
for(t[i] = 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.
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
for(t[i] = 0; t[i] < m; t[i]++)
[/dm_code_snippet]
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
-
set i=0
-
if i >= m then terminate the loop
-
examine t[i], using the current value of i
-
increment i
-
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]
i variable will be always 0, and t[i] 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]
-
-
AuthorPosts
- You must be logged in to reply to this topic.