- This topic is empty.
Viewing 1 post (of 1 total)
Viewing 1 post (of 1 total)
- You must be logged in to reply to this topic.
This site is best visible on desktop/laptop. Due to a technical problem, codes are not properly displaying on smartphone.
CS50's Introduction to Computer Science on Edx: Supplementary resource
CS50 threads to aide as a supplementary resource
CS50 threads to aide as a supplementary resource › Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 3 › Help for code conducting a linear search
Tagged: arrays, linear search, loop
#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’.
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 = “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 == “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.