C++ How do I print elements of an array but leave out repeats? -
my assignment have user type in how many elements in array enter integer number put in array. have sort through array , find largest number , print out elements of array if there repeat print number 1 time. have print out number of times each element in array occurs. example if user types in there 5 elements enters 2, 1, 2, -3, 2 should print -3 1 count, 1 1 count, , 2 3 count. far have print out elements , delete repeats cant print out correct number of occurrences each element. code far.
void findrepeats(int numbers[], int num) { int instances = 0; cout << "number" << " " << "occurrences" << endl; (int = 0; < num; i++) { bool matching = false; instances = 1; (int j = 0; (j < i); j++) { if (numbers[i] == numbers[j]) { instances++; matching = true; } } if (!matching) cout << numbers[i] << " " << instances << endl; } }
right saying number occur 1 time
one approach take, sort numbers first, before deciding how many duplicates there are. way, easier avoid printing results same number more once, , won't have loop through entire array each number.
void findrepeats(int numbers[], int num); int main(){ int array[] = {2, 1, 2, -3, 2}; findrepeats(array,5); } void findrepeats(int numbers[], int num) { //sort array first std::sort(numbers, numbers + num); int last = numbers[0]; int count = 0; cout << "number of occurrences\n"; (int = 0; < num; i++) { if (last == numbers[i]) { ++count; } else { cout << last << " " << count << '\n'; count = 1; } last = numbers[i]; } if (count > 0) { cout << last << " " << count << '\n'; } }
prints:
number of occurrences -3 1 1 1 2 3
Comments
Post a Comment