Don't really know how I would write this in code so I'll do it in plain english and mix in some C++ if I can.
My algorithm for finding 'k' in a list of numbers (a1,a2,....an) is as follows:
First define 'k' as whichever number you want to find. Say you want to see if 23 is in the list just do : int k = 23;
Then let 'i' equal your current number and go through the list using n (i+1).
Next the program compares 'i' to 'k' in an if/else statement.
if (i == k) {
cout << "YES!";
}
else if ( i != k) {
move to the next number
}
This algorithm could just run in a loop until it goes though all the numbers or finds a match to 'k'.
If it goes through the whole list and never finds a match then: cout << "NO!";
This algorithm is finite because it either finds 'k' or doesn't and has a statement to print to the screen in either situation. It is also correct because the relational operators ( == ) and ( != ) confirm if any values are equal to or not equal to 'k'.
No comments:
Post a Comment