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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • polkodot
    New Member
    • Nov 2012
    • 1

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

    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:


    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	int d[]={1,2,3,4,5,6,1,7,9, 10};
    	int i=0,j=0,c=0,missing=0;
    
    for (i = 0; i < 9; i++)
    {
        cout << "input: ";
        cin >> d[i];
    	c = 0;
    	for (j = 0; j<10; j++)
    	{
    		if (i == d[j])
    		{
    			c = i;
    		}
    	}
    	if (i==d[j])
    	{
    		missing = j;
    
    	}
    }
    	cout << "missing is " << missing << endl;
    	return 0;
    }
    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.
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    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.
    Last edited by whodgson; Nov 27 '12, 06:31 AM. Reason: to provide further explanation *

    Comment

    • wholetthedogout
      New Member
      • Nov 2012
      • 6

      #3
      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.

      Comment

      • whodgson
        Contributor
        • Jan 2007
        • 542

        #4
        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.
        Code:
        2)If (array[i]!= loop (i))cout<<i<<" ";//not in array so print
        Last edited by whodgson; Nov 28 '12, 02:02 AM. Reason: use code tags

        Comment

        Working...