Reputation: 47
This code works in a wrong way, I am kind of finding the solution but I can't apply it. I want to separate a line of code that is outside the for
loop but inside the if
statement knowing that if
statement is inside a nested loop.
I mean this line: printf("\n fianl result %d has appeard %d in the array", j, count);
int main() {
int array[10];
int i, j;
int count = 0;
printf("Enter numbers\n");
for (i = 0; i <= 9; i++) {
scanf("%d", &array[i]);
}
printf("Enter the number you are looking for:\n");
scanf("%d", &j);
for (i = 0; i <= 9; i++) {
if (j == array[i]) {
printf("%d is in the array it is in entery %d\n", j, i+1);
count++;
printf("\n fianl result %d has appeard %d in the array", j, count);
printf("Enter another number \n");
scanf("%d", &j);
} else {
printf("%d is not the array", j);
printf("Enter another number");
scanf("%d", &j);
}
}
return 0;
}
Upvotes: 0
Views: 1416
Reputation: 1714
You should move your scanfs out of the for loop so they aren't executed while you are scanning through the array. Entering -1 ends the while loop.
// your variables and array setup goes here
...
printf("Enter the number you are looking for:\n");
scanf("%d", &j);
while (j != -1) {
int count = 0;
for (i = 0; i <= 9; i++) {
if (j == array[i]) {
printf("%d is in the array it is in entery %d\n", j, i+1);
count++;
}
}
if (count == 0) {
printf("%d is not the array", j);
} else {
printf("\n final result %d has appeared %d times in the array", j, count);
}
printf("Enter the number you are looking for:\n");
scanf("%d", &j);
}
Upvotes: 1