By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,581 Members | 2,007 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,581 IT Pros & Developers. It's quick & easy.

Help me fix this code: Finding the missing number in the array

P: 1
I'm trying to write a program where in you input 9 numbers from 1-10, then it determines the missing number. Here's my code. It has a lot of errors. Help me do the right structure. Maybe after that, I'll improve it by setting conditions like no repetition/ 0< number <10. Just help me to fix this first:


Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6.     int d[]={1,2,3,4,5,6,1,7,9, 10};
  7.     int i=0,j=0,c=0,missing=0;
  8.  
  9. for (i = 0; i < 9; i++)
  10. {
  11.     cout << "input: ";
  12.     cin >> d[i];
  13.     c = 0;
  14.     for (j = 0; j<10; j++)
  15.     {
  16.         if (i == d[j])
  17.         {
  18.             c = i;
  19.         }
  20.     }
  21.     if (i==d[j])
  22.     {
  23.         missing = j;
  24.  
  25.     }
  26. }
  27.     cout << "missing is " << missing << endl;
  28.     return 0;
  29. }
  30.  
  31.  
I'm so new to C++. It always prints out the number 10 even though I typed it already. I really have no idea how to determine the missing one.
Nov 27 '12 #1
Share this Question
Share on Google+
3 Replies


100+
P: 542
There are 10 numbers between 1 and 10 inclusive and there are 10
integers in d[]. Your two loop conditions are 8 and 9. Other than those observations I have no idea what you are doing.
*"It always prints out the number 10"
this is because when j<10 or 9 (and finishes iterating)it has reached the last array element which contains 10. Remember j starts counting at 0.
Nov 27 '12 #2

P: 6
Can't this be an easiest approach

1) Sort the given sequence
2) fix the no. with the difference of two consecutive no. as > 1; duplicates can be filtered out with the difference as zero.

Hope this help.
Nov 27 '12 #3

100+
P: 542
Or you could:
1)Inside a loop iterate through the array and at each element compare loop i with array[i].If they are equal (==) continue.
Expand|Select|Wrap|Line Numbers
  1. 2)If (array[i]!= loop (i))cout<<i<<" ";//not in array so print
Nov 28 '12 #4

Post your reply

Sign in to post your reply or Sign up for a free account.