-
printf problem
I am having a bit of a problem with my code. I only want it to print out
Code:
printf("Number not found after %d steps\n", steps);
once at the end when it has finished searching but at the moment it prints out everytime. Any help in correcting this would be tops.
Code:
void linearSearch(int numbers[], int value)
{
/* Use linear search to find value in numbers.
Print the number of steps it takes to find or not find value
*/
int steps = 1, i;
for (i=0; i < SIZE; i++)
{
if (value == numbers[i])
{
printf("Number found after %d steps\n", steps);
return;
}
else
printf("Number not found after %d steps\n", steps);
steps++;
}
}
-
According to your indention, you'll need {} after else and after steps:
Code:
} else {
printf(blah)
steps++;
}
-
That wasn't the problem, just poor setting out on my part.
I have worked it out though.
Thanks.
-
Actually there seems to be a few problems with this as there would be a lot of printf calls even when you follow Kennedy's advice.
Consider something like this:
Code:
#include <stdio.h>
void linearSearch (int numbers[], size_t size, int value)
{
/*
** Perform a linear search, that is, sequentially check every value
** in a group for a match
*/
int i;
int stpflg = 0;
for (i = 0; !stpflg && i < size; ++i)
{
if (numbers[i] == value)
{
stpflg = 1;
}
}
printf("Number%sfound after %d steps.\n", stpflg ? " " : " not ", i);
}
int main(void)
{
int numbers[] = { 42, 3, 6, 5, 2, };
size_t size = sizeof numbers / sizeof numbers[0];
linearSearch(numbers, size, 5); /* should be there */
linearSearch(numbers, size, 7); /* not supposed to be there */
return 0;
}
$ ./a.exe
Number found after 4 steps.
Number not found after 5 steps.
-
Or you can avoid the stpflg by just breaking out of the loop when you find the value and then changing the condition in the printf() from stpflg to i == size.