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 › Help for code conducting a linear search
Tagged: arrays, linear search, loop
- This topic is empty.
-
AuthorPosts
-
March 7, 2022 at 12:59 pm #251
[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]
Help/clue appreciated why the above program fails to find ‘a’.
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’.
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[i] = “a”
string, here you’re including the string (arrays of character) into the loop when you’re not supposed to. So it’s:
-
For (int i =0; i<strlen(t) or m; i++) { If ( t[i] == “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]
-
-
AuthorPosts
- You must be logged in to reply to this topic.