Read a series of numbers into an integer array, until -1 is entered. The input will have at least one number (not counting -1) and may consist of up to 100 numbers. Print to the screen all distinct numbers in the array, sequentially. In other words, every number that appears in the array will be printed to the screen exactly once, in order by its first appearance, even if it appears multiple times in the array.
ex. Enter integer values into the array, or -1 to stop:
3
5
2
5
3
1
4
4
2
-1
Distinct values in the array:
(3,5,2,1,4)
Im getting a compile error for line 17 on the scope of x in nums[x] but im not sure why.
That is not legal in C++. The size of array must be a constant value that is known already before the code is compiled.
The constness aside, how many elements are in array int nums[0];?
How many is ?
The input may consist of up to 100 numbers.
You need room for at most 100 numbers. Make it so:
1 2
constexprint MAX = 100;
int nums[MAX];
until -1 is entered while(input != 1)
Do you have a typo?
That is not all in:
1 2 3 4 5 6 7
while ( input != 1 ) {
for ( int x = 0; x < 100; x++ )
cin >> nums[x];
size++;
input = nums[x];
}
That code does not compile. Read your compiler's error messages carefully.
You do repeat the
1 2 3 4 5
for ( int x = 0; x < 100; x++ ) {
cin >> nums[x];
}
size++;
input = nums[x]; // error: x is unknown
until input becomes 1. On every iteration you do read 100 values (to array that has no room).
Test input before you use it:
1 2 3 4 5 6
int size = 0;
int input = 0;
while ( size < MAX && std::cin >> input && input != -1 ) {
// never store the sentinel into the array
nums[size++] = input;
}
One way to skip duplicates is to mark them unusable.
We do know that the array won't have any -1.
FOR EACH candidate in nums
IF candidate is good
THEN
show candidate
mark duplicates bad in the rest of the nums
I reconstructed taking in my integer array with the constant 100 and that works and cuts off when -1 enters but now im struggling to pull and print te distinct elements heres what i have. When i run it nothing prints so i assume i've made an error in the loops.
yes. you need to sort the input, and then once it is sorted your assumption that you can look at the (current and next or current and previous as you see fit) to find duplicates will work. But I don't see any sorting code in there, so that assumption isnt true.
what I tried to show you 1)sorts it 2) counts the duplicates (not used) 3) can print the original (not shown) 4) can print without duplicates (shown).