#include #include // Linear search with replacement in an unsorted array. void print_array(int a[], int n) { int i; printf("\nIndex i: "); for(i=0; i< n; i++) printf("%2d, ", i); printf("\nElement a[i]: "); for(i=0; i< n; i++) printf("%2d, ", a[i]); printf("\n\n"); } #define N 12 int main() { int a[N] = { 4, 21, 36, 14, 62, 91, 8, 22, 7, 81, 62, 10}; int i; print_array(a, N); int target = 62; int newValue = 65; //int target = 72; // Try this target next to see how the search fails int count=0; int idx[5]; // a helper array that keeps the indexes of all entries == target value int found=0; for(i=0; i< N; i++) { if(a[i] == target) { found = 1; idx[count] = i; count++; } } if(found == 0) printf("Not found!\n\n"); else { printf("Found it a total of %d times.\n", count); for(i=0; i< count; i++) printf("\t Found @ index %d \n", idx[i]); } printf("\nReplacing all occurences of target=%d with %d\n", target, newValue); // Now replace all found occurences with a nother number for(i=0; i< count; i++) a[ idx[i] ] = newValue; print_array(a, N); system("pause"); }