Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ array excercise-help needed
    text
    copied!<p>I'm C++ begginer. I did this excercise from Deitel's book:</p> <blockquote> <p>Use a one-dimensional array to solve the following problem. Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, validate it and store it in the array only if it is not a duplicate of a number already read. After reading all the values, display only the unique values that the user entered. Provide for the "worst case" in which all 20 numbers are different. Use the smallest possible array to solve this problem.</p> </blockquote> <p>Here is my code:</p> <pre><code>#include &lt;iostream&gt; using namespace std; bool compare(int arrayNum[],int arraySize,int element); int main() { const int size=20; int i=1; int num[size]; int arrayElement; int counter=0; while(i&lt;=20) { cin&gt;&gt;arrayElement; if(i==1) //stores first element in array num[0]=arrayElement; //compare new element with stored elements //if element is not a duplicate store it in array else if (compare(num,size,arrayElement)) { counter++; num[counter]=arrayElement; } i++; } //displays array elements for(int k=0;k&lt;=counter;k++) cout&lt;&lt;num[k]&lt;&lt;endl; return 0; } //compare elements in array bool compare(int arrayNum[],int arraySize,int element) { for(int j=0;j&lt;arraySize;j++) { if(arrayNum[j]==element) return false; } return true; } </code></pre> <p>It works, but I'm not sure if I have interpreted the task correctly. I assume then I don't have to include conditional statement for range of numbers (10 to 100 inclusive), as this will be read from the keyboard and input by me. Therefore why was this instruction included? Also at the end it says </p> <blockquote> <p>use the smallest possible array</p> </blockquote> <p>I assume the max size has to be 20,but I don't think there is a way to dynamically expand array size (for example while storing new elements) as array size is const. I would appreciate if someone could help me with this. Any comments regarding code, or better solution are welcome. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload